java邮件解析3

比较完整的例子:

今天闲着无事,研究了一下javaMail发送电子邮件的方法,自己总结了个步骤:

1、首先需要获取发送邮件的Session对象

Session session = Session.getDefaultInstance(properties,authorcator);

2、根据session对象,获取待发送的邮件消息

MimeMessage mimeMessage = new MimeMessage(session);

3、设置发件人,收件人,标题,邮件内容,附件,发送时间等;

4、利用Transport发送邮件

 

以下是居然的实现代码:

1、邮件信息类:

Java代码  收藏代码
  1. package com.china.test.mail;  
  2.   
  3. import java.util.Properties;  
  4.   
  5. /** 
  6.  * 发送邮件需要使用的基本信息  
  7.  * @author dove * 
  8.  */  
  9. public class MailSenderInfo {  
  10.     // 发送邮件的服务器的IP  
  11.     private String mailServerHost;      
  12.     // 发送邮件的服务器的端口      
  13.     private String mailServerPort = "25";      
  14.     // 邮件发送者的地址      
  15.     private String fromAddress;      
  16.     // 邮件接收者的地址      
  17.     private String[] toAddress;  
  18.     // 邮件密送接收者的地址  
  19.     private String[] toBlindCarbonCopyAddress;  
  20.     // 邮件抄送接收者的地址  
  21.     private String[] toCarbonCopyAddress;  
  22.     // 登陆邮件发送服务器的用户名  
  23.     private String userName;  
  24.     // 登陆邮件发送服务器的密码      
  25.     private String password;      
  26.     // 是否需要身份验证      
  27.     private boolean validate = false;      
  28.     // 邮件主题      
  29.     private String subject;      
  30.     // 邮件的文本内容      
  31.     private String content;      
  32.     // 邮件附件的文件名      
  33.     private String[] attachFileNames;  
  34.       
  35.     /** 
  36.      * 获得邮件会话属性 
  37.      */  
  38.     public Properties getProperties() {  
  39.         Properties pro = new Properties();  
  40.         pro.put("mail.smtp.host"this.mailServerHost);  
  41.         pro.put("mail.smtp.port"this.mailServerPort);  
  42.         pro.put("mail.smtp.auth", validate ? "true" : "false");  
  43.         return pro;  
  44.     }  
  45.       
  46.     public String getMailServerHost() {  
  47.         return mailServerHost;  
  48.     }  
  49.     public void setMailServerHost(String mailServerHost) {  
  50.         this.mailServerHost = mailServerHost;  
  51.     }  
  52.     public String getMailServerPort() {  
  53.         return mailServerPort;  
  54.     }  
  55.     public void setMailServerPort(String mailServerPort) {  
  56.         this.mailServerPort = mailServerPort;  
  57.     }  
  58.     public String getFromAddress() {  
  59.         return fromAddress;  
  60.     }  
  61.     public void setFromAddress(String fromAddress) {  
  62.         this.fromAddress = fromAddress;  
  63.     }  
  64.     public String[] getToAddress() {  
  65.         return toAddress;  
  66.     }  
  67.     public void setToAddress(String[] toAddress) {  
  68.         this.toAddress = toAddress;  
  69.     }  
  70.     public String getUserName() {  
  71.         return userName;  
  72.     }  
  73.     public void setUserName(String userName) {  
  74.         this.userName = userName;  
  75.     }  
  76.     public String getPassword() {  
  77.         return password;  
  78.     }  
  79.     public void setPassword(String password) {  
  80.         this.password = password;  
  81.     }  
  82.     public boolean isValidate() {  
  83.         return validate;  
  84.     }  
  85.     public void setValidate(boolean validate) {  
  86.         this.validate = validate;  
  87.     }  
  88.     public String getSubject() {  
  89.         return subject;  
  90.     }  
  91.     public void setSubject(String subject) {  
  92.         this.subject = subject;  
  93.     }  
  94.     public String getContent() {  
  95.         return content;  
  96.     }  
  97.     public void setContent(String content) {  
  98.         this.content = content;  
  99.     }  
  100.     public String[] getAttachFileNames() {  
  101.         return attachFileNames;  
  102.     }  
  103.     public void setAttachFileNames(String[] attachFileNames) {  
  104.         this.attachFileNames = attachFileNames;  
  105.     }  
  106.   
  107.     public String[] getToBlindCarbonCopyAddress() {  
  108.         return toBlindCarbonCopyAddress;  
  109.     }  
  110.   
  111.     public void setToBlindCarbonCopyAddress(String[] toBlindCarbonCopyAddress) {  
  112.         this.toBlindCarbonCopyAddress = toBlindCarbonCopyAddress;  
  113.     }  
  114.   
  115.     public String[] getToCarbonCopyAddress() {  
  116.         return toCarbonCopyAddress;  
  117.     }  
  118.   
  119.     public void setToCarbonCopyAddress(String[] toCarbonCopyAddress) {  
  120.         this.toCarbonCopyAddress = toCarbonCopyAddress;  
  121.     }  
  122.       
  123. }  

 

2、身份验证类

 

Java代码  收藏代码
  1. package com.china.test.mail;  
  2.   
  3. import javax.mail.Authenticator;  
  4. import javax.mail.PasswordAuthentication;  
  5. /** 
  6.  * 身份验证器 
  7.  * @author dove 
  8.  * 
  9.  */  
  10. public class MyAuthenticator extends Authenticator {  
  11.     private String username;  
  12.     private String password;  
  13.     public MyAuthenticator(){  
  14.           
  15.     }  
  16.       
  17.     public MyAuthenticator(String username, String password) {  
  18.         this.username = username;  
  19.         this.password = password;  
  20.     }  
  21.   
  22.     @Override  
  23.     protected PasswordAuthentication getPasswordAuthentication() {  
  24.         return new PasswordAuthentication(username, password);  
  25.     }  
  26.       
  27.     public String getUsername() {  
  28.         return username;  
  29.     }  
  30.     public void setUsername(String username) {  
  31.         this.username = username;  
  32.     }  
  33.     public String getPassword() {  
  34.         return password;  
  35.     }  
  36.     public void setPassword(String password) {  
  37.         this.password = password;  
  38.     }  
  39. }  

 

3、发送邮件类

该类有两个功能,一个是发送普通文本邮件;一个是发送html邮件,两者的本质是相同的,mime类型有所区别而已,具体请看代码:

Java代码  收藏代码
  1. package com.china.test.mail;  
  2.   
  3. import java.io.UnsupportedEncodingException;  
  4. import java.util.Date;  
  5. import java.util.Properties;  
  6.   
  7. import javax.activation.DataHandler;  
  8. import javax.activation.DataSource;  
  9. import javax.activation.FileDataSource;  
  10. import javax.mail.Address;  
  11. import javax.mail.BodyPart;  
  12. import javax.mail.Message;  
  13. import javax.mail.MessagingException;  
  14. import javax.mail.Multipart;  
  15. import javax.mail.Session;  
  16. import javax.mail.Transport;  
  17. import javax.mail.internet.AddressException;  
  18. import javax.mail.internet.InternetAddress;  
  19. import javax.mail.internet.MimeBodyPart;  
  20. import javax.mail.internet.MimeMessage;  
  21. import javax.mail.internet.MimeMultipart;  
  22. import javax.mail.internet.MimeUtility;  
  23.   
  24. /** 
  25.  * 简单邮件发送器 
  26.  * @author dove * 
  27.  */  
  28. public class SimpleMailSender {  
  29.     /** 
  30.      * 以文本格式发送邮件 (支持群发,带附件) 
  31.      * @param senderInfo 待发送的邮件的信息  
  32.      * @return 
  33.      */  
  34.     public static boolean sendMail(MailSenderInfo senderInfo){  
  35.         boolean flag = false;  
  36.           
  37.         // 判断是否需要身份验证  
  38.         MyAuthenticator authenticator = null;  
  39.         Properties props = senderInfo.getProperties();  
  40.         if(senderInfo.isValidate()){  
  41.             // 如果需要身份认证,则创建一个密码验证器     
  42.             authenticator = new MyAuthenticator(senderInfo.getUserName(), senderInfo.getPassword());  
  43.         }  
  44.         // 根据邮件会话属性和密码验证器构造一个发送邮件的session  
  45.         Session sendMailSession = Session.getDefaultInstance(props, authenticator);  
  46.           
  47.         try {  
  48.             // 根据session创建一个邮件消息  
  49.             Message sendMailMessage = new MimeMessage(sendMailSession);  
  50.             // 创建邮件发送者地址  
  51.             Address from = new InternetAddress(senderInfo.getFromAddress());  
  52.             // 设置邮件消息的发送者  
  53.             sendMailMessage.setFrom(from);  
  54.               
  55.             // 创建邮件接收者地址  
  56.             String[] tos = senderInfo.getToAddress();  
  57.             if(tos != null && tos.length != 0){  
  58.                 InternetAddress[] to = new InternetAddress[tos.length];  
  59.                 // 设置邮件消息的发送者  
  60.                 for (int i = 0; i < tos.length; i++) {  
  61.                     to[i] = new InternetAddress(tos[i]);  
  62.                 }  
  63.                 sendMailMessage.setRecipients(Message.RecipientType.TO, to);  
  64.             }  
  65.               
  66.             // 设置邮件抄送者地址  
  67.             String[] toCCs = senderInfo.getToCarbonCopyAddress();  
  68.             if(toCCs != null && toCCs.length != 0){  
  69.                 InternetAddress[] toCC = new InternetAddress[toCCs.length];  
  70.                 // 设置邮件消息的发送者  
  71.                 for (int i = 0; i < toCCs.length; i++) {  
  72.                     toCC[i] = new InternetAddress(toCCs[i]);  
  73.                 }  
  74.                 sendMailMessage.addRecipients(Message.RecipientType.CC, toCC);  
  75.             }  
  76.               
  77.             // 设置邮件密送者地址  
  78.             String[] toBCCs = senderInfo.getToBlindCarbonCopyAddress();  
  79.             if(toBCCs != null && toBCCs.length != 0){  
  80.                 InternetAddress[] toBCC = new InternetAddress[toBCCs.length];  
  81.                 for (int i = 0; i < toBCCs.length; i++) {  
  82.                     toBCC[i] = new InternetAddress(toBCCs[i]);  
  83.                 }  
  84.                 sendMailMessage.addRecipients(Message.RecipientType.BCC, toBCC);  
  85.             }  
  86.               
  87.             // 设置邮件主题  
  88.             sendMailMessage.setSubject(MimeUtility.encodeText(senderInfo.getSubject(),"utf-8","B"));  
  89.             // 设置邮件内容  
  90.             //sendMailMessage.setText(senderInfo.getContent());  
  91.             Multipart multipart = new MimeMultipart();  
  92.             // 邮件文本内容  
  93.             if(senderInfo.getContent() != null && !"".equals(senderInfo.getContent())){  
  94.                 BodyPart part = new MimeBodyPart();  
  95.                 part.setContent(senderInfo.getContent(), "text/plain;charset=utf-8");//设置邮件文本内容  
  96.                 multipart.addBodyPart(part);  
  97.             }  
  98.               
  99.             // 附件  
  100.             String attachFileNames[] = senderInfo.getAttachFileNames();  
  101.             int leng = attachFileNames == null ? 0 : attachFileNames.length;  
  102.             for (int i = 0; i < leng; i++) {  
  103.                 BodyPart part = new MimeBodyPart();  
  104.                 // 根据文件名获取数据源  
  105.                 DataSource dataSource = new FileDataSource(attachFileNames[i]);  
  106.                 DataHandler dataHandler = new DataHandler(dataSource);  
  107.                 // 得到附件本身并至入BodyPart  
  108.                 part.setDataHandler(dataHandler);  
  109.                 // 得到文件名同样至入BodyPart  
  110.                 part.setFileName(MimeUtility.encodeText(dataSource.getName()));  
  111.                 multipart.addBodyPart(part);  
  112.             }  
  113.               
  114.             sendMailMessage.setContent(multipart);  
  115.             // 设置邮件发送的时间  
  116.             sendMailMessage.setSentDate(new Date());  
  117.             // 发送邮件  
  118.             //Transport.send(sendMailMessage);  
  119.             Transport transport = sendMailSession.getTransport("smtp");  
  120.             transport.connect(senderInfo.getUserName(), senderInfo.getPassword());  
  121.             transport.send(sendMailMessage,sendMailMessage.getAllRecipients());  
  122.             transport.close();  
  123.               
  124.             flag = true;  
  125.         } catch (AddressException e) {  
  126.             e.printStackTrace();  
  127.         } catch (MessagingException e) {  
  128.             e.printStackTrace();  
  129.         } catch (UnsupportedEncodingException e) {  
  130.             e.printStackTrace();  
  131.         }  
  132.           
  133.         return flag;  
  134.     }  
  135.       
  136.     public static boolean sendHtmlMail(MailSenderInfo senderInfo){  
  137.         boolean flag = false;  
  138.           
  139.         // 判断是否需要身份验证  
  140.         MyAuthenticator authenticator = null;  
  141.         Properties props = senderInfo.getProperties();  
  142.         if(senderInfo.isValidate()){  
  143.             // 如果需要身份认证,则创建一个密码验证器     
  144.             authenticator = new MyAuthenticator(senderInfo.getUserName(), senderInfo.getPassword());  
  145.         }  
  146.         // 根据邮件会话属性和密码验证器构造一个发送邮件的session  
  147.         Session sendMailSession = Session.getDefaultInstance(props, authenticator);  
  148.           
  149.         try {  
  150.             // 根据session创建一个邮件消息  
  151.             Message sendMailMessage = new MimeMessage(sendMailSession);  
  152.             // 创建邮件发送者地址  
  153.             Address from = new InternetAddress(senderInfo.getFromAddress());  
  154.             // 设置邮件消息的发送者  
  155.             sendMailMessage.setFrom(from);  
  156.               
  157.             // 创建邮件接收者地址  
  158.             String[] tos = senderInfo.getToAddress();  
  159.             if(tos != null && tos.length != 0){  
  160.                 InternetAddress[] to = new InternetAddress[tos.length];  
  161.                 // 设置邮件消息的发送者  
  162.                 for (int i = 0; i < tos.length; i++) {  
  163.                     to[i] = new InternetAddress(tos[i]);  
  164.                 }  
  165.                 sendMailMessage.setRecipients(Message.RecipientType.TO, to);  
  166.             }  
  167.               
  168.             // 设置邮件抄送者地址  
  169.             String[] toCCs = senderInfo.getToCarbonCopyAddress();  
  170.             if(toCCs != null && toCCs.length != 0){  
  171.                 InternetAddress[] toCC = new InternetAddress[toCCs.length];  
  172.                 // 设置邮件消息的发送者  
  173.                 for (int i = 0; i < toCCs.length; i++) {  
  174.                     toCC[i] = new InternetAddress(toCCs[i]);  
  175.                 }  
  176.                 sendMailMessage.addRecipients(Message.RecipientType.CC, toCC);  
  177.             }  
  178.               
  179.             // 设置邮件密送者地址  
  180.             String[] toBCCs = senderInfo.getToBlindCarbonCopyAddress();  
  181.             if(toBCCs != null && toBCCs.length != 0){  
  182.                 InternetAddress[] toBCC = new InternetAddress[toBCCs.length];  
  183.                 for (int i = 0; i < toBCCs.length; i++) {  
  184.                     toBCC[i] = new InternetAddress(toBCCs[i]);  
  185.                 }  
  186.                 sendMailMessage.addRecipients(Message.RecipientType.BCC, toBCC);  
  187.             }  
  188.               
  189.             // 设置邮件主题  
  190.             sendMailMessage.setSubject(MimeUtility.encodeText(senderInfo.getSubject(),"utf-8","B"));  
  191.             // 设置邮件内容  
  192.             //sendMailMessage.setText(senderInfo.getContent());  
  193.             Multipart multipart = new MimeMultipart();  
  194.             // 邮件文本内容  
  195.             if(senderInfo.getContent() != null && !"".equals(senderInfo.getContent())){  
  196.                 BodyPart part = new MimeBodyPart();  
  197.                 part.setContent(senderInfo.getContent(), "text/html;charset=utf-8");//设置邮件文本内容  
  198.                 multipart.addBodyPart(part);  
  199.             }  
  200.               
  201.             // 附件  
  202.             String attachFileNames[] = senderInfo.getAttachFileNames();  
  203.             int leng = attachFileNames == null ? 0 : attachFileNames.length;  
  204.             for (int i = 0; i < leng; i++) {  
  205.                 BodyPart part = new MimeBodyPart();  
  206.                 // 根据文件名获取数据源  
  207.                 DataSource dataSource = new FileDataSource(attachFileNames[i]);  
  208.                 DataHandler dataHandler = new DataHandler(dataSource);  
  209.                 // 得到附件本身并至入BodyPart  
  210.                 part.setDataHandler(dataHandler);  
  211.                 // 得到文件名同样至入BodyPart  
  212.                 part.setFileName(MimeUtility.encodeText(dataSource.getName()));  
  213.                 multipart.addBodyPart(part);  
  214.             }  
  215.               
  216.             sendMailMessage.setContent(multipart);  
  217.             // 设置邮件发送的时间  
  218.             sendMailMessage.setSentDate(new Date());  
  219.             // 发送邮件  
  220.             //Transport.send(sendMailMessage);  
  221.             Transport transport = sendMailSession.getTransport("smtp");  
  222.             transport.connect(senderInfo.getUserName(), senderInfo.getPassword());  
  223.             transport.send(sendMailMessage,sendMailMessage.getAllRecipients());  
  224.               
  225.             // 关闭transport  
  226.             transport.close();  
  227.               
  228.             flag = true;  
  229.         } catch (AddressException e) {  
  230.             e.printStackTrace();  
  231.         } catch (MessagingException e) {  
  232.             e.printStackTrace();  
  233.         } catch (UnsupportedEncodingException e) {  
  234.             e.printStackTrace();  
  235.         }  
  236.           
  237.         return flag;  
  238.     }  
  239.       
  240.     public static void main(String[] args) {  
  241.         MailSenderInfo mailInfo = new MailSenderInfo();  
  242.         mailInfo.setMailServerHost("smtp.sina.com");  
  243.         mailInfo.setMailServerPort("25");  
  244.         mailInfo.setValidate(true);  
  245.         mailInfo.setUserName("********@sina.com");  
  246.         mailInfo.setPassword("*********");// 您的邮箱密码  
  247.         mailInfo.setFromAddress("[email protected]");  
  248.         String[] to = {"********@bj.china.com"};  
  249.         mailInfo.setToAddress(to);  
  250.         String[] toCC = {"**********@qq.com"};  
  251.         mailInfo.setToCarbonCopyAddress(toCC);  
  252.         String[] toBCC = {"*******@sina.com"};  
  253.         mailInfo.setToBlindCarbonCopyAddress(toBCC);  
  254.         mailInfo.setAttachFileNames(new String[]{"C:/Documents and Settings/Administrator/桌面/考勤休假制度表格(新).xls","C:/Documents and Settings/Administrator/桌面/dove.jpg"});  
  255.         mailInfo.setSubject("发送HTML邮件");  
  256.         String body = "你好你好你好";  
  257.         mailInfo.setContent(body);  
  258.         // 这个类主要来发送邮件  
  259.         System.out.println(SimpleMailSender.sendHtmlMail(mailInfo));;//发送文体格式  
  260.     }  
  261. }  

 


你可能感兴趣的:(java邮件发送解析)