JavaMail发送邮件

来源:互联网 发布:陕西官员被网络大V攻击 编辑:程序博客网 时间:2024/06/07 14:31
MailInfo.java
[java] view plain copy
  1. import java.util.Properties;  
  2.   
  3. public class MailInfo {  
  4.     private String mailServerHost;// 服务器ip  
  5.     private String mailServerPort;// 端口  
  6.     private String fromAddress;// 发送者的邮件地址  
  7.     private String toAddress;// 邮件接收者地址  
  8.     private String username;// 登录邮件发送服务器的用户名  
  9.     private String password;// 登录邮件发送服务器的密码  
  10.     private boolean validate = false;// 是否需要身份验证  
  11.     private String subject;// 邮件主题  
  12.     private String content;// 邮件内容  
  13.     private String[] attachFileNames;// 附件名称  
  14.       
  15.     public Properties getProperties() {  
  16.         Properties p = new Properties();  
  17.         p.put("mail.smtp.host"this.mailServerHost);  
  18.         p.put("mail.smtp.port"this.mailServerPort);  
  19.         p.put("mail.smtp.auth", validate ? "true" : "false");  
  20.         return p;  
  21.     }  
  22.   
  23.     public String getMailServerHost() {  
  24.         return mailServerHost;  
  25.     }  
  26.   
  27.     public void setMailServerHost(String mailServerHost) {  
  28.         this.mailServerHost = mailServerHost;  
  29.     }  
  30.   
  31.     public String getMailServerPort() {  
  32.         return mailServerPort;  
  33.     }  
  34.   
  35.     public void setMailServerPort(String mailServerPort) {  
  36.         this.mailServerPort = mailServerPort;  
  37.     }  
  38.   
  39.     public String getFromAddress() {  
  40.         return fromAddress;  
  41.     }  
  42.   
  43.     public void setFromAddress(String fromAddress) {  
  44.         this.fromAddress = fromAddress;  
  45.     }  
  46.   
  47.     public String getToAddress() {  
  48.         return toAddress;  
  49.     }  
  50.   
  51.     public void setToAddress(String toAddress) {  
  52.         this.toAddress = toAddress;  
  53.     }  
  54.   
  55.     public String getUsername() {  
  56.         return username;  
  57.     }  
  58.   
  59.     public void setUsername(String username) {  
  60.         this.username = username;  
  61.     }  
  62.   
  63.     public String getPassword() {  
  64.         return password;  
  65.     }  
  66.   
  67.     public void setPassword(String password) {  
  68.         this.password = password;  
  69.     }  
  70.   
  71.     public boolean isValidate() {  
  72.         return validate;  
  73.     }  
  74.   
  75.     public void setValidate(boolean validate) {  
  76.         this.validate = validate;  
  77.     }  
  78.   
  79.     public String getSubject() {  
  80.         return subject;  
  81.     }  
  82.   
  83.     public void setSubject(String subject) {  
  84.         this.subject = subject;  
  85.     }  
  86.   
  87.     public String getContent() {  
  88.         return content;  
  89.     }  
  90.   
  91.     public void setContent(String content) {  
  92.         this.content = content;  
  93.     }  
  94.   
  95.     public String[] getAttachFileNames() {  
  96.         return attachFileNames;  
  97.     }  
  98.   
  99.     public void setAttachFileNames(String[] attachFileNames) {  
  100.         this.attachFileNames = attachFileNames;  
  101.     }  
  102.   
  103. }  

MyAuthenticator.Java

[java] view plain copy
  1. import javax.mail.Authenticator;  
  2. import javax.mail.PasswordAuthentication;  
  3.   
  4. public class MyAuthenticator extends Authenticator {  
  5.     private String username = null;  
  6.     private String password = null;  
  7.   
  8.     public MyAuthenticator() {  
  9.     };  
  10.   
  11.     public MyAuthenticator(String username, String password) {  
  12.         this.username = username;  
  13.         this.password = password;  
  14.     }  
  15.   
  16.     protected PasswordAuthentication getPasswordAuthentication() {  
  17.         return new PasswordAuthentication(username, password);  
  18.     }  
  19.   
  20. }  

SimpleMail.java
[java] view plain copy
  1. import java.io.File;  
  2. import java.util.Date;  
  3. import java.util.Properties;  
  4.   
  5. import javax.activation.DataHandler;  
  6. import javax.activation.FileDataSource;  
  7. import javax.mail.Address;  
  8. import javax.mail.Message;  
  9. import javax.mail.Multipart;  
  10. import javax.mail.Session;  
  11. import javax.mail.Transport;  
  12. import javax.mail.internet.InternetAddress;  
  13. import javax.mail.internet.MimeBodyPart;  
  14. import javax.mail.internet.MimeMessage;  
  15. import javax.mail.internet.MimeMultipart;  
  16.   
  17. public class SimpleMail {  
  18.   
  19.     // 以文本格式发送邮件  
  20.     public static boolean sendTextMail(MailInfo mailInfo) {       
  21.         //判断是否需要身份认证  
  22.         MyAuthenticator authenticator = null;  
  23.         Properties properties = mailInfo.getProperties();  
  24.         if (mailInfo.isValidate()) {  
  25.             //如果需要身份认证,则创建一个密码验证器  
  26.             authenticator = new MyAuthenticator(mailInfo.getUsername(), mailInfo.getPassword());  
  27.         }  
  28.           
  29.         //根据邮件会话属性和密码验证器构造一个发送邮件的session  
  30.         Session sendMailSession = Session.getDefaultInstance(properties, authenticator);  
  31.         try {  
  32.             Message mailMessage = new MimeMessage(sendMailSession);//根据session创建一个邮件消息   
  33.             Address from = new InternetAddress(mailInfo.getFromAddress());//创建邮件发送者地址  
  34.             mailMessage.setFrom(from);//设置邮件消息的发送者  
  35.             Address to = new InternetAddress(mailInfo.getToAddress());//创建邮件的接收者地址  
  36.             mailMessage.setRecipient(Message.RecipientType.TO, to);//设置邮件消息的接收者  
  37.             mailMessage.setSubject(mailInfo.getSubject());//设置邮件消息的主题  
  38.             mailMessage.setSentDate(new Date());//设置邮件消息发送的时间  
  39.             //mailMessage.setText(mailInfo.getContent());//设置邮件消息的主要内容  
  40.               
  41.             //MimeMultipart类是一个容器类,包含MimeBodyPart类型的对象  
  42.             Multipart mainPart = new MimeMultipart();  
  43.             MimeBodyPart messageBodyPart = new MimeBodyPart();//创建一个包含附件内容的MimeBodyPart  
  44.             //设置HTML内容  
  45.             messageBodyPart.setContent(mailInfo.getContent(),"text/html; charset=utf-8");  
  46.             mainPart.addBodyPart(messageBodyPart);  
  47.   
  48.             //存在附件  
  49.             String[] filePaths = mailInfo.getAttachFileNames();  
  50.             if (filePaths != null && filePaths.length > 0) {  
  51.                 for(String filePath:filePaths){  
  52.                     messageBodyPart = new MimeBodyPart();  
  53.                     File file = new File(filePath);   
  54.                     if(file.exists()){//附件存在磁盘中  
  55.                         FileDataSource fds = new FileDataSource(file);//得到数据源  
  56.                         messageBodyPart.setDataHandler(new DataHandler(fds));//得到附件本身并至入BodyPart  
  57.                         messageBodyPart.setFileName(file.getName());//得到文件名同样至入BodyPart  
  58.                         mainPart.addBodyPart(messageBodyPart);  
  59.                     }  
  60.                 }  
  61.             }  
  62.               
  63.             //将MimeMultipart对象设置为邮件内容     
  64.             mailMessage.setContent(mainPart);  
  65.             Transport.send(mailMessage);//发送邮件  
  66.             return true;  
  67.         } catch (Exception e) {  
  68.             e.printStackTrace();    
  69.         }  
  70.         return false;  
  71.     }     
  72.       
  73.     // 以HTML格式发送邮件   
  74.     public static boolean sendHtmlMail(MailInfo mailInfo) {       
  75.         //判断是否需要身份认证  
  76.         MyAuthenticator authenticator = null;  
  77.         Properties properties = mailInfo.getProperties();  
  78.         if (mailInfo.isValidate()) {  
  79.             // 如果需要身份认证,则创建一个密码验证器  
  80.             authenticator = new MyAuthenticator(mailInfo.getUsername(), mailInfo.getPassword());  
  81.         }  
  82.   
  83.         // 根据邮件会话属性和密码验证器构造一个发送邮件的session  
  84.         Session sendMailSession = Session.getDefaultInstance(properties, authenticator);  
  85.         try{  
  86.             Message mailMessage = new MimeMessage(sendMailSession);//根据session创建一个邮件消息   
  87.             Address from = new InternetAddress(mailInfo.getFromAddress());//创建邮件发送者地址  
  88.             mailMessage.setFrom(from);//设置邮件消息的发送者  
  89.             Address to = new InternetAddress(mailInfo.getToAddress());//创建邮件的接收者地址  
  90.             mailMessage.setRecipient(Message.RecipientType.TO, to);//设置邮件消息的接收者  
  91.             mailMessage.setSubject(mailInfo.getSubject());//设置邮件消息的主题  
  92.             mailMessage.setSentDate(new Date());//设置邮件消息发送的时间  
  93.               
  94.             //MimeMultipart类是一个容器类,包含MimeBodyPart类型的对象  
  95.             Multipart mainPart = new MimeMultipart();  
  96.             MimeBodyPart messageBodyPart = new MimeBodyPart();//创建一个包含HTML内容的MimeBodyPart  
  97.             //设置HTML内容  
  98.             messageBodyPart.setContent(mailInfo.getContent(),"text/html; charset=utf-8");  
  99.             mainPart.addBodyPart(messageBodyPart);  
  100.               
  101.             //存在附件  
  102.             String[] filePaths = mailInfo.getAttachFileNames();  
  103.             if (filePaths != null && filePaths.length > 0) {  
  104.                 for(String filePath:filePaths){  
  105.                     messageBodyPart = new MimeBodyPart();  
  106.                     File file = new File(filePath);   
  107.                     if(file.exists()){//附件存在磁盘中  
  108.                         FileDataSource fds = new FileDataSource(file);//得到数据源  
  109.                         messageBodyPart.setDataHandler(new DataHandler(fds));//得到附件本身并至入BodyPart  
  110.                         messageBodyPart.setFileName(file.getName());//得到文件名同样至入BodyPart  
  111.                         mainPart.addBodyPart(messageBodyPart);  
  112.                     }  
  113.                 }  
  114.             }  
  115.               
  116.             //将MimeMultipart对象设置为邮件内容     
  117.             mailMessage.setContent(mainPart);  
  118.             Transport.send(mailMessage);//发送邮件  
  119.             return true;  
  120.         }catch (Exception e) {  
  121.             e.printStackTrace();  
  122.         }  
  123.         return false;  
  124.     }  
  125.   
  126. }  

emailTest.java
[java] view plain copy
  1. public class emailTest {  
  2.     public static void main(String[] args) {  
  3.         MailInfo mailInfo = new MailInfo();  
  4.         mailInfo.setMailServerHost("smtp.163.com");  
  5.         mailInfo.setMailServerPort("25");  
  6.         mailInfo.setValidate(true);  
  7.         mailInfo.setUsername("xxx@163.com");  
  8.         mailInfo.setPassword("xxxxx");// 您的邮箱密码  
  9.         mailInfo.setFromAddress("xxxx@163.com");  
  10.         mailInfo.setToAddress("xxxx@163.com");  
  11.         mailInfo.setSubject("设置邮箱标题");  
  12.                   
  13.         //附件  
  14.         String[] attachFileNames={"d:/Sunset.jpg"};  
  15.         mailInfo.setAttachFileNames(attachFileNames);  
  16.           
  17.         // 这个类主要来发送邮件  
  18.         //mailInfo.setContent("设置邮箱内容");  
  19.         //SimpleMail.sendTextMail(mailInfo);// 发送文体格式  
  20.         StringBuffer demo = new StringBuffer();  
  21.         demo.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">")  
  22.         .append("<html>")  
  23.         .append("<head>")  
  24.         .append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">")  
  25.         .append("<title>测试邮件</title>")  
  26.         .append("<style type=\"text/css\">")  
  27.         .append(".test{font-family:\"Microsoft Yahei\";font-size: 18px;color: red;}")  
  28.         .append("</style>")  
  29.         .append("</head>")  
  30.         .append("<body>")  
  31.         .append("<span class=\"test\">大家好,这里是测试Demo</span>")  
  32.         .append("</body>")  
  33.         .append("</html>");  
  34.         mailInfo.setContent(demo.toString());  
  35.         SimpleMail.sendHtmlMail(mailInfo);// 发送html格式  
  36.     }  
  37. }  
原创粉丝点击