电子邮件系统 5----使用Java Mail Authenticator子类进行用户认证来发送电子邮件示例 .

  1. /** 
  2.  * CrazyItTest 
  3.  * 使用JavaMail的Authenticator类进行用户认证发送带附件的电子邮件示例 
  4.  */  
  5. package com.labci.javamail.test;  
  6. import java.io.FileNotFoundException;  
  7. import java.io.IOException;  
  8. import java.io.UnsupportedEncodingException;  
  9. import java.util.Date;  
  10. import java.util.Properties;  
  11. import javax.activation.DataHandler;  
  12. import javax.activation.FileDataSource;  
  13. import javax.mail.Authenticator;  
  14. import javax.mail.MessagingException;  
  15. import javax.mail.PasswordAuthentication;  
  16. import javax.mail.Session;  
  17. import javax.mail.Transport;  
  18. import javax.mail.Message.RecipientType;  
  19. import javax.mail.internet.AddressException;  
  20. import javax.mail.internet.InternetAddress;  
  21. import javax.mail.internet.MimeBodyPart;  
  22. import javax.mail.internet.MimeMessage;  
  23. import javax.mail.internet.MimeMultipart;  
  24. import javax.mail.internet.MimeUtility;  
  25. /** 
  26.  * @author Bill Tu 
  27.  * @since May 26, 2011(21:03:36 PM) 
  28.  * 
  29.  */  
  30. public class SendEmailTest {  
  31.     private static final String USERNAME="iwtxokhtd";//用户名   
  32.     private static final String PASSWORD="123456";//密码   
  33.     private static final String PROTOCOL="smtp";//邮件传输协议   
  34.     private static final String HOST="smtp.163.com";//SMTP服务器主机地址   
  35.       
  36.     /** 
  37.      * 客户端程序自己实现Authenticator子类用于用户认证 
  38.      */  
  39.     static class MyAuthenricator extends Authenticator{  
  40.         String user=null;  
  41.         String pass="";  
  42.         public MyAuthenricator(String user,String pass){  
  43.             this.user=user;  
  44.             this.pass=pass;  
  45.         }  
  46.         @Override  
  47.         protected PasswordAuthentication getPasswordAuthentication() {  
  48.             return new PasswordAuthentication(user,pass);  
  49.         }  
  50.           
  51.     }  
  52.       
  53.      private static Session getSession(){  
  54.          Properties mailProps=new Properties();  
  55.          mailProps.put("mail.smtp.auth""true");//向SMTP服务器提交用户认证   
  56.          mailProps.put("mail.transport.protocol", PROTOCOL);//指定发送邮件协议   
  57.          mailProps.put("mail.host", HOST);//SMTP服务器主机地址   
  58.            
  59.          //拿session的时候传入Authenticator子类进行验证   
  60.          Session session=Session.getDefaultInstance(mailProps,new MyAuthenricator(USERNAME,PASSWORD));  
  61.          return session;  
  62.      }  
  63.       
  64.       
  65.      private static void sendEmail(MimeMessage message) throws MessagingException{  
  66.         //从session中取mail.smtp.protocol指定协议的Transport   
  67.          Transport transport=getSession().getTransport();  
  68.          //建立与指定的SMTP服务器的连接   
  69.          transport.connect();//此时不需要任务参数   
  70.         //发给所有指定的收件人,若使用message.getAllRecipients()则还包括抄送和暗送的人   
  71.          transport.sendMessage(message, message.getRecipients(RecipientType.TO));  
  72.          //关闭连接   
  73.          transport.close();  
  74.            
  75.          /** 
  76.           * Transport的send静态方法包括了connect,saveChanges,sendMessage,close等一系列操作, 
  77.           * 但它连接同一个SMTP服务器每发一封邮件给服务器都得重新建立连接和断开连接, 
  78.           * 虽然使用较方便,但开销较大,不值得推荐。 
  79.           */  
  80.         // Transport.send(message, message.getRecipients(RecipientType.TO));   
  81.      }  
  82.        
  83.       
  84.      private static MimeMessage getTextMessage(Session session) throws AddressException,   
  85.             MessagingException, UnsupportedEncodingException{  
  86.           MimeMessage message=new MimeMessage(session);  
  87.           String from="[email protected]";//发送方邮件地址   
  88.           String to="[email protected]";//接收方邮件地址   
  89.             
  90.           String subject="从163发过来的邮件";//邮件主题,注意是中文的   
  91.             
  92.           String content="<h1>看看能收到不,JavaMail写的邮件发送程序,带附件哦</h1><img src="cid:my1.jpg" mce_src="cid:my1.jpg"/>";//cid为my1.jpg,下文会设置此cid   
  93.           message.setFrom(new InternetAddress(from));  
  94.           message.setRecipient(RecipientType.TO, new InternetAddress(to));  
  95.           message.setSubject(subject);  
  96.           message.setSentDate(new Date());//发送时间   
  97.             
  98.           MimeBodyPart picBodyPart=getPicBodyPart(content,"F://My头像.jpg");  
  99.           MimeBodyPart attached1BodyPart=getAttachedBodyPart("F://nginx中文.txt");//注意附件名是中文的  
  100.           MimeBodyPart attached2BodyPart=getAttachedBodyPart("F://nginx英文.doc");  
  101.             
  102.           MimeMultipart mmp=new MimeMultipart("mixed");//MIME消息头组合类型是mixed(html+附件)   
  103.           mmp.addBodyPart(picBodyPart);  
  104.           mmp.addBodyPart(attached1BodyPart);  
  105.           mmp.addBodyPart(attached2BodyPart);  
  106.             
  107.           message.setContent(mmp);  
  108.           message.saveChanges();  
  109.             
  110.           return message;  
  111.         
  112.      }  
  113.        
  114.      /** 
  115.       * 处理文件名 
  116.       * 此处是针对Window下的。 
  117.       * @param filePath 
  118.       * @return 
  119.       */  
  120.      private static String doHandlerFileName(String filePath){  
  121.           String fileName=filePath;  
  122.           if(null !=filePath && !"".equals(filePath)){  
  123.            fileName=filePath.substring(filePath.lastIndexOf("//")+1);  
  124.           }  
  125.           return fileName;  
  126.      }  
  127.        
  128.        
  129.      private static MimeBodyPart getAttachedBodyPart(String filePath) throws MessagingException,  
  130.             UnsupportedEncodingException{  
  131.           MimeBodyPart attached=new MimeBodyPart();  
  132.           FileDataSource fds=new FileDataSource(filePath);  
  133.           attached.setDataHandler(new DataHandler(fds));  
  134.           String fileName=doHandlerFileName(filePath);  
  135.           attached.setFileName(MimeUtility.encodeWord(fileName));//处理附件文件的中文名问题   
  136.           return attached;  
  137.      }  
  138.        
  139.      /** 
  140.       * 处理html加图片的类型(related) 
  141.       * @param content 
  142.       * @param picName 
  143.       * @return 
  144.       * @throws MessagingException 
  145.       */  
  146.      private static MimeBodyPart getPicBodyPart(String content,String picName) throws MessagingException{  
  147.           MimeBodyPart contentPart=new MimeBodyPart();  
  148.             
  149.           MimeMultipart mmp=new MimeMultipart("related");//此处MIME消息头组合类型为related   
  150.           MimeBodyPart contented=new MimeBodyPart();  
  151.           contented.setContent(content,"text/html;charset=gb2312");//因正文内容中有中文   
  152.             
  153.           mmp.addBodyPart(contented);  
  154.             
  155.           MimeBodyPart picBodyPart=new MimeBodyPart();  
  156.           FileDataSource fds=new FileDataSource(picName);  
  157.           picBodyPart.setDataHandler(new DataHandler(fds));  
  158.           picBodyPart.setContentID("my1.jpg");//设置contentId   
  159.             
  160.           mmp.addBodyPart(picBodyPart);  
  161.             
  162.           contentPart.setContent(mmp);  
  163.             
  164.           return contentPart;  
  165.      }  
  166.        
  167.        
  168.      public static void main(String[] args) throws AddressException,   
  169.             MessagingException, FileNotFoundException, IOException {  
  170.          sendEmail(getTextMessage(getSession()));  
  171.         
  172.      }  
  173. }  

猜你喜欢

转载自2277259257.iteye.com/blog/2159472