Java发送邮件

因为工作需要发送邮件。所以上网找了例子,整理了一下发表出来。

封装邮件信息的一个实体类。

 

 


  1. package com.base.myproject.mail;          
  2.           
  3. import java.util.ArrayList;          
  4. import java.util.List;          
  5. import java.util.Properties;          
  6.           
  7. public class MailSenderInfo {          
  8.               
  9.      public static String TEXT = "text/plain;charset=gb2312";          
  10.      public static String HTML = "text/html;charset=gb2312";          
  11.               
  12.     private String mailServerHost;                // 发送邮件的服务器的IP和端口             
  13.     private String mailServerPort = "25";                   
  14.               
  15.     private String fromAddress;                   // 邮件发送者的地址          
  16.     private String toAddress;                     // 邮件接收者的地址             
  17.                 
  18.     private String userName;             
  19.     private String password;                      // 登陆邮件发送服务器的用户名和密码           
  20.               
  21.     private boolean validate = false;             // 是否需要身份验证             
  22.                 
  23.     private String subject;                       // 邮件主题           
  24.     private String content;                       // 邮件的文本内容          
  25.     private List<Object> attaches = new ArrayList<Object>();                         //邮件附件;                       
  26.               
  27.     private String cc;                           //抄送邮件给某人          
  28.     private String bc;                           //隐蔽副本 隐蔽抄送给某人          
  29.               
  30.     /**         
  31.       * 获得邮件会话属性         
  32.       */             
  33.     public Properties getProperties(){             
  34.       Properties p = new Properties();             
  35.       p.put("mail.smtp.host"this.mailServerHost);             
  36.       p.put("mail.smtp.port"this.mailServerPort);             
  37.       p.put("mail.smtp.auth", validate ? "true" : "false");             
  38.       return p;             
  39.     }             
  40.     public String getMailServerHost() {             
  41.       return mailServerHost;             
  42.     }             
  43.     public void setMailServerHost(String mailServerHost) {             
  44.       this.mailServerHost = mailServerHost;             
  45.     }            
  46.     public String getMailServerPort() {             
  47.       return mailServerPort;             
  48.     }            
  49.     public void setMailServerPort(String mailServerPort) {             
  50.       this.mailServerPort = mailServerPort;             
  51.     }            
  52.     public boolean isValidate() {             
  53.       return validate;             
  54.     }            
  55.     public void setValidate(boolean validate) {             
  56.       this.validate = validate;             
  57.     }            
  58.     public String getFromAddress() {             
  59.       return fromAddress;             
  60.     }             
  61.     public void setFromAddress(String fromAddress) {             
  62.       this.fromAddress = fromAddress;             
  63.     }            
  64.     public String getPassword() {             
  65.       return password;             
  66.     }            
  67.     public void setPassword(String password) {             
  68.       this.password = password;             
  69.     }            
  70.     public String getToAddress() {             
  71.       return toAddress;             
  72.     }             
  73.     public void setToAddress(String toAddress) {             
  74.       this.toAddress = toAddress;             
  75.     }             
  76.     public String getUserName() {             
  77.       return userName;             
  78.     }            
  79.     public void setUserName(String userName) {             
  80.       this.userName = userName;             
  81.     }            
  82.     public String getSubject() {             
  83.       return subject;             
  84.     }            
  85.     public void setSubject(String subject) {             
  86.       this.subject = subject;             
  87.     }            
  88.     public String getContent() {             
  89.       return content;             
  90.     }            
  91.     public void setContent(String textContent) {             
  92.       this.content = textContent;             
  93.     }          
  94.     public List<Object> getAttaches() {          
  95.         return attaches;          
  96.     }          
  97.     public void setAttaches(List<Object> attaches) {          
  98.         this.attaches = attaches;          
  99.     }          
  100.     public String getCc() {          
  101.         return cc;          
  102.     }          
  103.     public void setCc(String cc) {          
  104.         this.cc = cc;          
  105.     }          
  106.     public String getBc() {          
  107.         return bc;          
  108.     }          
  109.     public void setBc(String bc) {          
  110.         this.bc = bc;          
  111.     }            
  112.               
  113.               
  114. }      

邮件用户名密码认证

 


  1. Java 代码复制内容到剪贴板  
  2.       
  3. package com.base.myproject.mail;          
  4.           
  5. import javax.mail.Authenticator;          
  6. import javax.mail.PasswordAuthentication;          
  7.           
  8. public class MyAuthenticator extends Authenticator{          
  9.           
  10.     String userName = null;            
  11.     String password = null;            
  12.                  
  13.     public MyAuthenticator(){            
  14.                   
  15.     }            
  16.     public MyAuthenticator(String username, String password) {             
  17.         this.userName = username;             
  18.         this.password = password;             
  19.     }             
  20.     protected PasswordAuthentication getPasswordAuthentication(){            
  21.         return new PasswordAuthentication(userName, password);            
  22.     }            
  23. }      

发送邮件类


  1. Java 代码复制内容到剪贴板  
  2.       
  3. package com.base.myproject.mail;          
  4.           
  5. import java.net.URL;          
  6. import java.util.Date;          
  7. import java.util.Properties;          
  8.           
  9. import javax.activation.DataHandler;          
  10. import javax.activation.FileDataSource;          
  11. import javax.activation.URLDataSource;          
  12. import javax.mail.BodyPart;          
  13. import javax.mail.Message;          
  14. import javax.mail.Multipart;          
  15. import javax.mail.Session;          
  16. import javax.mail.Transport;          
  17. import javax.mail.internet.InternetAddress;          
  18. import javax.mail.internet.MimeBodyPart;          
  19. import javax.mail.internet.MimeMessage;          
  20. import javax.mail.internet.MimeMultipart;          
  21. import javax.mail.internet.MimeUtility;          
  22.           
  23. public class SendEmail {          
  24.           
  25.               
  26.     private BodyPart body;          
  27.     private MailSenderInfo mailInfo;          
  28.               
  29.     public SendEmail(MailSenderInfo mailInfo){          
  30.         this.mailInfo = mailInfo;          
  31.     }          
  32.               
  33.     /*       
  34.      * 设置文件内容的形式       
  35.      */          
  36.     public void setBody(String string, String contentType) {          
  37.         try {          
  38.                 body = new MimeBodyPart();          
  39.                 DataHandler dh = new DataHandler(string, contentType);          
  40.                 body.setDataHandler(dh);          
  41.         } catch (Exception e) {          
  42.             e.printStackTrace();          
  43.         }          
  44.     }          
  45.               
  46.     //设置邮件的内容的格式为文本格式          
  47.     public void setBodyAsText(String string) {          
  48.         setBody(string, MailSenderInfo.TEXT);          
  49.     }          
  50.               
  51.     //以HTMl的形式存放内容          
  52.     public void setBodyAsHTML(String string) {          
  53.         setBody(string, MailSenderInfo.HTML);          
  54.     }          
  55.               
  56.     //从文件中自动导入邮件内容          
  57.     public void setBodyFromFile(String filename) {          
  58.         try {          
  59.             BodyPart mdp = new MimeBodyPart();          
  60.             FileDataSource fds = new FileDataSource(filename);          
  61.             DataHandler dh = new DataHandler(fds);          
  62.             mdp.setDataHandler(dh);          
  63.             mailInfo.getAttaches().add(mdp);          
  64.         } catch (Exception e) {          
  65.             e.printStackTrace();          
  66.         }          
  67.     }          
  68.               
  69.     //从一个URL导入邮件的内容          
  70.     public void setBodyFromUrl(String url) {          
  71.         try {          
  72.             BodyPart mdp = new MimeBodyPart();          
  73.             URLDataSource ur = new URLDataSource(new URL(url));          
  74.             DataHandler dh = new DataHandler(ur);          
  75.             mdp.setDataHandler(dh);          
  76.             mailInfo.getAttaches().add(mdp);          
  77.         } catch (Exception e) {          
  78.             e.printStackTrace();          
  79.         }          
  80.     }          
  81.               
  82.               
  83.     /**       
  84.     * 将String中的内容存放入文件showname,并将这个文件作为附件发送给收件人       
  85.     * @param string 为邮件的内容       
  86.     * @param showname 显示的文件的名字       
  87.     */          
  88.     public void addAttachFromString(String string, String showname) {          
  89.         try {          
  90.             BodyPart mdp = new MimeBodyPart();          
  91.             DataHandler dh = new DataHandler(string, MailSenderInfo.TEXT);          
  92.             mdp.setFileName(MimeUtility.encodeWord(showname, "gb2312"null));          
  93.             mdp.setDataHandler(dh);          
  94.             mailInfo.getAttaches().add(mdp);          
  95.         } catch (Exception e) {          
  96.             e.printStackTrace();          
  97.         }          
  98.     }          
  99.               
  100.               
  101.     /**       
  102.     * filename为邮件附件       
  103.     * 在收信人的地方以showname这个文件名来显示       
  104.     * @param filename       
  105.     * @param showname       
  106.     */          
  107.     public void addAttachFromFile(String filename, String showname) {          
  108.         try {          
  109.             BodyPart mdp = new MimeBodyPart();          
  110.             FileDataSource fds = new FileDataSource(filename);          
  111.             DataHandler dh = new DataHandler(fds);          
  112.             mdp.setFileName(MimeUtility.encodeWord(showname, "gb2312"null));          
  113.             mdp.setDataHandler(dh);          
  114.             mailInfo.getAttaches().add(mdp);          
  115.         } catch (Exception e) {          
  116.             e.printStackTrace();          
  117.         }          
  118.     }          
  119.               
  120.     /**       
  121.     * 将互联网上的一个文件作为附件发送给收信人       
  122.     * 并在收信人处显示文件的名字为showname       
  123.     * @param url       
  124.     * @param showname       
  125.     */          
  126.     public void addAttachFromUrl(String url, String showname) {          
  127.         try {          
  128.             BodyPart mdp = new MimeBodyPart();          
  129.             URLDataSource ur = new URLDataSource(new URL(url));          
  130.             DataHandler dh = new DataHandler(ur);          
  131.             mdp.setFileName(MimeUtility.encodeWord(showname, "gb2312"null));          
  132.             mdp.setDataHandler(dh);          
  133.             mailInfo.getAttaches().add(mdp);          
  134.         } catch (Exception e) {          
  135.             e.printStackTrace();          
  136.         }          
  137.     }          
  138.               
  139.     public void send() throws Exception {          
  140.         try {          
  141.             MyAuthenticator authenticator = null//判断身份是否需要验证          
  142.             // *****会话类*****//          
  143.             Properties props = mailInfo.getProperties();          
  144.             if (mailInfo.isValidate()) {          
  145.                 // 如果需要身份认证,则创建一个密码验证器          
  146.                 authenticator = new MyAuthenticator(mailInfo.getUserName(),          
  147.                         mailInfo.getPassword());          
  148.             }          
  149.             Session session = Session.getInstance(props,authenticator);          
  150.             // *****消息类*****//          
  151.             MimeMessage msg = new MimeMessage(session);          
  152.             msg.setSubject(mailInfo.getSubject());            // 设置邮件主题          
  153.             msg.setSentDate(new Date());                      // 设置邮件发送时间          
  154.             // *****地址类*****//          
  155.             if (mailInfo.getFromAddress() != null)          
  156.                 msg.addFrom(InternetAddress.parse(mailInfo.getFromAddress()));   // 指定发件人          
  157.             else          
  158.                 throw new Exception("没有指定发件人");          
  159.             if (mailInfo.getToAddress() != null)          
  160.                 msg.addRecipients(Message.RecipientType.TO, InternetAddress.parse(mailInfo.getToAddress()));// 指定收件人          
  161.             else          
  162.                 throw new Exception("没有指定收件人地址");          
  163.             if (mailInfo.getCc() != null)          
  164.                 msg.addRecipients(Message.RecipientType.CC, InternetAddress.parse(mailInfo.getCc()));// 指定抄送          
  165.             if (mailInfo.getBc() != null)          
  166.                 msg.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(mailInfo.getBc()));// 指定密送          
  167.                       
  168.             Multipart mm = new MimeMultipart();          
  169.             if (body != null)          
  170.                 mm.addBodyPart(body);// 设置邮件的附件          
  171.             if(mailInfo.getAttaches() != null){          
  172.                 for (int i = 0; i < mailInfo.getAttaches().size(); i++) {          
  173.                     BodyPart part = (BodyPart) mailInfo.getAttaches().get(i);          
  174.                     mm.addBodyPart(part);          
  175.                 }          
  176.             }          
  177.             msg.setContent(mm);// 设置邮件的内容          
  178.                       
  179.             // *****传输类*****//          
  180.             msg.saveChanges();// 保存所有改变          
  181.             Transport.send(msg);          
  182.             System.out.println("发送成功");          
  183.         } catch (Exception e) {          
  184.             e.printStackTrace();          
  185.             throw new Exception("发送邮件失败:", e);          
  186.         }          
  187.     }          
  188. }      

 

测试类

 


  1. Java 代码复制内容到剪贴板  
  2.       
  3. package com.base.myproject.mail;          
  4.           
  5. public class SendEmailTest {          
  6.           
  7.     /**       
  8.      * @param args       
  9.      */          
  10.     public static void main(String[] args) {          
  11.         MailSenderInfo mailInfo = new MailSenderInfo();          
  12.         mailInfo.setMailServerHost("smtp.qq.com");          
  13.         mailInfo.setValidate(true);          
  14.         mailInfo.setUserName("452655443@qq.com");          
  15.         mailInfo.setPassword("********");// 您的邮箱密码          
  16.                   
  17.         mailInfo.setFromAddress("452655443@qq.com");          
  18.         mailInfo.setToAddress("1302758061@qq.com");          
  19.                   
  20.         mailInfo.setSubject("Send Email TEST");          
  21.                   
  22.         SendEmail sms = new SendEmail(mailInfo);          
  23. //      sms.addAttachFromUrl("http://photo...._01.jpg", "mzba.jpg");          
  24.     //  sms.setBodyFromUrl("http://www.it...;          
  25.         sms.setBodyAsHTML("邮件测试啊。");          
  26.     //  sms.addAttachFromFile("D:\\db.pro", "mzba.pro");          
  27.         try {          
  28.             sms.send();          
  29.         } catch (Exception e) {          
  30.             // TODO Auto-generated catch block          
  31.             e.printStackTrace();          
  32.         }          
  33.     }          
  34.           
  35. }      

 



     本文转自06peng 51CTO博客,原文链接:http://blog.51cto.com/06peng/962467,如需转载请自行联系原作者




上一篇:WCF发布多个服务


下一篇:课时13:多环境切换、注解方式与增删改返回值问题