javamail smtp 发送邮件

简介:
Java代码   收藏代码
  1. /* 
  2.  * 邮件发送类 
  3.  */  
  4. public class MailSenderUtil{  
  5.       
  6.   /** 
  7.   * 以HTML格式发送邮件,可带附件,本方法可作为对外接口提供。 
  8.   * @param mailInfo 待发送的邮件信息  
  9.  * @throws MessagingException  
  10.  * @throws AddressException  
  11.  * @throws UnsupportedEncodingException  
  12.   */    
  13.     public static void sendHtmlMailWithLocalAttach(MailSenderInfo mailInfo) throws AddressException, MessagingException, UnsupportedEncodingException {  
  14.           
  15.         // 判断是否需要身份认证  
  16.         MyAuthenticator authenticator = null;  
  17.           
  18.         // 如果需要身份认证,则创建一个密码验证器  
  19.         if (mailInfo.isValidate()) {  
  20.             authenticator = new MyAuthenticator(mailInfo.getUserName(),mailInfo.getPassword());  
  21.         }  
  22.         // 根据邮件会话属性和密码验证器构造一个发送邮件的session  
  23.         Properties pro = mailInfo.getProperties();  
  24.         Session sendMailSession = Session.getDefaultInstance(pro, authenticator);  
  25.   
  26.         // 根据session创建一个邮件消息  
  27.         Message mailMessage = new MimeMessage(sendMailSession);  
  28.           
  29.         // 设置发送人  
  30.         mailMessage.setFrom(new InternetAddress(mailInfo.getFromAddress()));  
  31.           
  32.         // 设置收件人  
  33.         String[] toAddress = mailInfo.getToAddress();  
  34.         if(toAddress == null || toAddress.length < 1){  
  35.             throw new RuntimeException("收件人不得为空!");  
  36.         }  
  37.         for (int i = 0; i < toAddress.length; i++) {  
  38.             mailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress[i]));  
  39.         }  
  40.   
  41.         //设置抄送人  
  42.         String[] ccAddress = mailInfo.getCcAddress();  
  43.         if(ccAddress != null && ccAddress.length > 0){  
  44.             for (int i = 0; i < ccAddress.length; i++) {  
  45.                 mailMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(ccAddress[i]));  
  46.             }  
  47.         }  
  48.           
  49.         // 设置邮件消息的主题  
  50.         mailMessage.setSubject(mailInfo.getTitle());  
  51.         // 设置邮件消息发送的时间  
  52.         mailMessage.setSentDate(new Date());  
  53.         // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象  
  54.         Multipart mainPart = new MimeMultipart();  
  55.         // 创建一个包含HTML内容的MimeBodyPart  
  56.         BodyPart html = new MimeBodyPart();  
  57.         // 设置HTML内容  
  58.         html.setContent(mailInfo.getContent(), "text/html; charset=GBK");  
  59.         mainPart.addBodyPart(html);  
  60.   
  61.         // 添加附件  
  62.         addAttachment(mailInfo, mainPart);  
  63.           
  64.         // 将MiniMultipart对象设置为邮件内容  
  65.         mailMessage.setContent(mainPart);  
  66.   
  67.         // 发送邮件  
  68.         Transport.send(mailMessage);  
  69.     }   
  70.       
  71.     /* 
  72.      * 添加邮件附件,用本地的文件作为附件 
  73.      */  
  74.     private static void addAttachment(MailSenderInfo mailInfo,Multipart mainPart) throws MessagingException, UnsupportedEncodingException{  
  75.              
  76.            String[] attachFileNames = mailInfo.getAttachFileNames();  
  77.            if(attachFileNames != null && attachFileNames.length > 0){  
  78.             for (int i = 0; i < attachFileNames.length; i++) {  
  79.                 MimeBodyPart mdp = new MimeBodyPart();  
  80.   
  81.                 // FileDataSource/DataHandler 会用到  
  82.                 // activation-1.1.jar,jdk6中已经包含了该jar中内容,不再需要单独下载  
  83.                 // activation-1.1.jar  
  84.                 FileDataSource fds = new FileDataSource(attachFileNames[i]);  
  85.                 DataHandler dh = new DataHandler(fds);  
  86.                 mdp.setDataHandler(dh);  
  87.   
  88.                 // 保持附件名称与原文件名称一致的写法,MimeUtility.encodeText()可以解决中文附件乱码。  
  89.                 mdp.setFileName(MimeUtility.encodeText(fds.getName()));  
  90.                 mainPart.addBodyPart(mdp);  
  91.             }  
  92.            }  
  93.     }  
  94. }   
  95. /** 
  96.  * MyAuthenticator bean 
  97.  */  
  98. class MyAuthenticator extends Authenticator{   
  99.       String userName=null;   
  100.       String password=null;   
  101.           
  102.       public MyAuthenticator(){   
  103.       }   
  104.       public MyAuthenticator(String username, String password) {    
  105.         this.userName = username;    
  106.         this.password = password;    
  107.       }    
  108.       protected PasswordAuthentication getPasswordAuthentication(){   
  109.         return new PasswordAuthentication(userName, password);   
  110.       }   
  111.     }   
  112. /** 
  113.  * MailSenderInfo bean 
  114.  */  
  115. class MailSenderInfo {  
  116.     // 发送邮件的服务器的IP和端口  
  117.     private String mailServerHost;  
  118.     private String mailServerPort;;  
  119.     // 邮件发送者的地址  
  120.     private String fromAddress;  
  121.     //接收人地址  
  122.     private String[] toAddress;  
  123.     //抄送人地址  
  124.     private String[] ccAddress;  
  125.     // 登陆邮件发送服务器的用户名和密码  
  126.     private String userName;  
  127.     private String password;  
  128.       
  129.     // 是否需要身份验证  
  130.     private boolean validate = false;  
  131.     // 邮件主题  
  132.     private String title;  
  133.     // 邮件的文本内容  
  134.     private String content;  
  135.       
  136.     // 邮件附件的文件名,含磁盘物理路径,如D:\\Desktop\\index.html  
  137.     private String[] attachFileNames;  
  138.   
  139.     /** 
  140.      *  获得邮件会话属性  
  141.      * @return Properties 
  142.      */  
  143.     public Properties getProperties() {  
  144.         Properties p = new Properties();  
  145.         p.put("mail.smtp.host"this.mailServerHost);  
  146.         p.put("mail.smtp.port"this.mailServerPort);  
  147.         p.put("mail.smtp.auth", validate ? "true" : "false");  
  148.         return p;  
  149.     }  
  150.   
  151.     public String[] getCcAddress() {  
  152.         return ccAddress;  
  153.     }  
  154.   
  155.     public void setCcAddress(String[] ccAddress) {  
  156.         this.ccAddress = ccAddress;  
  157.     }  
  158.   
  159.     public String getMailServerHost() {  
  160.         return mailServerHost;  
  161.     }  
  162.   
  163.     public void setMailServerHost(String mailServerHost) {  
  164.         this.mailServerHost = mailServerHost;  
  165.     }  
  166.   
  167.     public String getMailServerPort() {  
  168.         return mailServerPort;  
  169.     }  
  170.   
  171.     public void setMailServerPort(String mailServerPort) {  
  172.         this.mailServerPort = mailServerPort;  
  173.     }  
  174.   
  175.     public boolean isValidate() {  
  176.         return validate;  
  177.     }  
  178.   
  179.     public void setValidate(boolean validate) {  
  180.         this.validate = validate;  
  181.     }  
  182.   
  183.     public String[] getAttachFileNames() {  
  184.         return attachFileNames;  
  185.     }  
  186.   
  187.     public void setAttachFileNames(String[] fileNames) {  
  188.         this.attachFileNames = fileNames;  
  189.     }  
  190.   
  191.     public String getFromAddress() {  
  192.         return fromAddress;  
  193.     }  
  194.   
  195.     public void setFromAddress(String fromAddress) {  
  196.         this.fromAddress = fromAddress;  
  197.     }  
  198.   
  199.     public String getPassword() {  
  200.         return password;  
  201.     }  
  202.   
  203.     public void setPassword(String password) {  
  204.         this.password = password;  
  205.     }  
  206.   
  207.     public String[] getToAddress() {  
  208.         return toAddress;  
  209.     }  
  210.   
  211.     public void setToAddress(String[] toAddress) {  
  212.         this.toAddress = toAddress;  
  213.     }  
  214.   
  215.     public String getUserName() {  
  216.         return userName;  
  217.     }  
  218.   
  219.     public void setUserName(String userName) {  
  220.         this.userName = userName;  
  221.     }  
  222.   
  223.     public String getTitle() {  
  224.         return title;  
  225.     }  
  226.   
  227.     public void setTitle(String title) {  
  228.         this.title = title;  
  229.     }  
  230.   
  231.     public String getContent() {  
  232.         return content;  
  233.     }  
  234.   
  235.     public void setContent(String textContent) {  
  236.         this.content = textContent;  
  237.     }  
  238. }  

 

使用

 

Java代码   收藏代码
  1. public static void main(String[] args) throws AddressException, UnsupportedEncodingException, MessagingException {  
  2.   
  3.         MailSenderInfo mail = new MailSenderInfo();  
  4.           
  5.         //设置附件  
  6.         mail.setAttachFileNames(new String[]{  
  7.                 "D:\\Desktop\\首页.jpg",  
  8.                 "D:\\Desktop\\测试账户.java"  
  9.         });  
  10.         //设置抄送人  
  11.         mail.setCcAddress(new String[]{"1@1.com","2@2.com"});  
  12.         //设置正文  
  13.         mail.setContent("<h3>http://www.baidu.com</h3>");  
  14.         //设置发件邮箱  
  15.         mail.setFromAddress("33@33.com");  
  16.         //设置发件邮箱密码  
  17.         mail.setPassword("123456");  
  18.         //设置邮件服务器  
  19.         mail.setMailServerHost("mail.XX.com");  
  20.         mail.setMailServerPort("25");  
  21.         //设置邮件主题  
  22.         mail.setTitle("我是主题");  
  23.         //设置收件人  
  24.         mail.setToAddress(new String[]{"44@44.com"});  
  25.         //设置用户名  
  26.         mail.setUserName("33");  
  27.         mail.setValidate(true);  
  28.         MailSenderUtil.sendHtmlMailWithLocalAttach(mail);  
  29.     }  

 

有些邮件服务器中,username需要写全称(即包含@及之后的数据,如33@163.com),否则会报错:

javax.mail.AuthenticationFailedException: 535 5.7.0 Error: authentication failed: authentication failure

 

http://huangqiqing123.iteye.com/blog/1688119

相关文章
|
2月前
|
Ruby
|
3月前
|
数据安全/隐私保护 Ruby
|
3月前
|
数据安全/隐私保护 Ruby
|
5月前
|
网络安全 数据安全/隐私保护
用smtp发送邮件,语法错误,无法识别命令。 服务器响应为:Authentication is re
用smtp发送邮件,语法错误,无法识别命令。 服务器响应为:Authentication is re
94 0
|
8月前
|
网络安全 数据安全/隐私保护 Python
|
8月前
|
Python
|
8月前
|
Python
|
8月前
|
Python
|
网络安全 数据安全/隐私保护 Python
开心档-软件开发入门之Python SMTP发送邮件
本文主要讲解SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。