电子邮件系统 6----JavaMail发送带附件的电子邮件示例(1)

  1. /** 
  2.  * CrazyItTest 
  3.  * 使用JavaMail发送带附件的电子邮件示例 
  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.MessagingException;  
  14. import javax.mail.Session;  
  15. import javax.mail.Transport;  
  16. import javax.mail.Message.RecipientType;  
  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.  * @author Bill Tu 
  25.  * @since May 26, 2011(21:03:36 PM) 
  26.  * 
  27.  */  
  28. public class SendEmailTest {  
  29.      private static Session getSession(String protocol){  
  30.          Properties mailProps=new Properties();  
  31.          mailProps.put("mail.smtp.auth""true");//向SMTP服务器提交用户认证   
  32.          mailProps.put("mail.transport.protocol", protocol);//指定发送邮件协议   
  33.            
  34.          //getInstance每次都会拿一个新的session,而getDefaultInstance拿的是同一个session   
  35.          Session session=Session.getDefaultInstance(mailProps);  
  36.          //session.setDebug(true);//调试模式   
  37.          return session;  
  38.      }  
  39.       
  40.       
  41.      private static void sendEmail(MimeMessage message,String protocol) throws MessagingException{  
  42.          String host="smtp.163.com";//连接发送方的SMTP服务器   
  43.          String user="iwtxokhtd";//用户名   
  44.          String password="123456";//密码   
  45.         //从session中取mail.smtp.protocol指定协议的Transport   
  46.          Transport transport=getSession(protocol).getTransport();  
  47.          //建立与指定的SMTP服务器的连接   
  48.          transport.connect(host, user, password);  
  49.         //发给所有指定的收件人,若使用message.getAllRecipients()则还包括抄送和暗送的人   
  50.          transport.sendMessage(message, message.getRecipients(RecipientType.TO));  
  51.          //关闭连接   
  52.          transport.close();  
  53.            
  54.          /** 
  55.           * Transport的send静态方法包括了connect,saveChanges,sendMessage,close等一系列操作, 
  56.           * 但它连接同一个SMTP服务器每发一封邮件给服务器都得重新建立连接和断开连接, 
  57.           * 虽然使用较方便,但开销较大,不值得推荐。 
  58.           */  
  59.         // Transport.send(message, message.getRecipients(RecipientType.TO));   
  60.      }  
  61.        
  62.       
  63.      private static MimeMessage getTextMessage(Session session) throws AddressException,   
  64.             MessagingException, UnsupportedEncodingException{  
  65.           MimeMessage message=new MimeMessage(session);  
  66.           String from="iwtxokhtd@163.com";//发送方邮件地址   
  67.           String to="277515433@qq.com";//接收方邮件地址   
  68.             
  69.           String subject="从163发到QQ来的邮件";//邮件主题,注意是中文的   
  70.             
  71.           String content="<h1>试试可以不</h1><img src="cid:my1.jpg" mce_src="cid:my1.jpg"/>";//cid为my1.jpg,下文会设置此cid   
  72.           message.setFrom(new InternetAddress(from));  
  73.           message.setRecipient(RecipientType.TO, new InternetAddress(to));  
  74.           message.setSubject(subject);  
  75.           message.setSentDate(new Date());//发送时间   
  76.             
  77.           MimeBodyPart picBodyPart=getPicBodyPart(content,"F://My头像.jpg");  
  78.           MimeBodyPart attached1BodyPart=getAttachedBodyPart("F://nginx中文.txt");//注意附件名是中文的  
  79.           MimeBodyPart attached2BodyPart=getAttachedBodyPart("F://nginx英文.doc");  
  80.             
  81.           MimeMultipart mmp=new MimeMultipart("mixed");//MIME消息头组合类型是mixed(html+附件)   
  82.           mmp.addBodyPart(picBodyPart);  
  83.           mmp.addBodyPart(attached1BodyPart);  
  84.           mmp.addBodyPart(attached2BodyPart);  
  85.             
  86.           message.setContent(mmp);  
  87.           message.saveChanges();  
  88.             
  89.           return message;  
  90.         
  91.      }  
  92.        
  93.      /** 
  94.       * 处理文件名 
  95.       * 此处是针对Window下的。 
  96.       * @param filePath 
  97.       * @return 
  98.       */  
  99.      private static String doHandlerFileName(String filePath){  
  100.           String fileName=filePath;  
  101.           if(null !=filePath && !"".equals(filePath)){  
  102.            fileName=filePath.substring(filePath.lastIndexOf("//")+1);  
  103.           }  
  104.           return fileName;  
  105.      }  
  106.        
  107.        
  108.      private static MimeBodyPart getAttachedBodyPart(String filePath) throws MessagingException,  
  109.             UnsupportedEncodingException{  
  110.           MimeBodyPart attached=new MimeBodyPart();  
  111.           FileDataSource fds=new FileDataSource(filePath);  
  112.           attached.setDataHandler(new DataHandler(fds));  
  113.           String fileName=doHandlerFileName(filePath);  
  114.           attached.setFileName(MimeUtility.encodeWord(fileName));//处理附件文件的中文名问题   
  115.           return attached;  
  116.      }  
  117.        
  118.      /** 
  119.       * 处理html加图片的类型(related) 
  120.       * @param content 
  121.       * @param picName 
  122.       * @return 
  123.       * @throws MessagingException 
  124.       */  
  125.      private static MimeBodyPart getPicBodyPart(String content,String picName) throws MessagingException{  
  126.           MimeBodyPart contentPart=new MimeBodyPart();  
  127.             
  128.           MimeMultipart mmp=new MimeMultipart("related");//此处MIME消息头组合类型为related   
  129.           MimeBodyPart contented=new MimeBodyPart();  
  130.           contented.setContent(content,"text/html;charset=gb2312");//因正文内容中有中文   
  131.             
  132.           mmp.addBodyPart(contented);  
  133.             
  134.           MimeBodyPart picBodyPart=new MimeBodyPart();  
  135.           FileDataSource fds=new FileDataSource(picName);  
  136.           picBodyPart.setDataHandler(new DataHandler(fds));  
  137.           picBodyPart.setContentID("my1.jpg");//设置contentId   
  138.             
  139.           mmp.addBodyPart(picBodyPart);  
  140.             
  141.           contentPart.setContent(mmp);  
  142.             
  143.           return contentPart;  
  144.      }  
  145.        
  146.        
  147.      public static void main(String[] args) throws AddressException,   
  148.             MessagingException, FileNotFoundException, IOException {  
  149.          String protocol="smtp";  
  150.          sendEmail(getTextMessage(getSession(protocol)),protocol);  
  151.         
  152.      }  
  153. }  

/** * CrazyItTest * 使用JavaMail发送带附件的电子邮件示例 */ package com.labci.javamail.test; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.Message.RecipientType; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; /** * @author Bill Tu * @since May 26, 2011(21:03:36 PM) * */ public class SendEmailTest { private static Session getSession(String protocol){ Properties mailProps=new Properties(); mailProps.put("mail.smtp.auth", "true");//向SMTP服务器提交用户认证 mailProps.put("mail.transport.protocol", protocol);//指定发送邮件协议 //getInstance每次都会拿一个新的session,而getDefaultInstance拿的是同一个session Session session=Session.getDefaultInstance(mailProps); //session.setDebug(true);//调试模式 return session; } private static void sendEmail(MimeMessage message,String protocol) throws MessagingException{ String host="smtp.163.com";//连接发送方的SMTP服务器 String user="iwtxokhtd";//用户名 String password="123456";//密码 //从session中取mail.smtp.protocol指定协议的Transport Transport transport=getSession(protocol).getTransport(); //建立与指定的SMTP服务器的连接 transport.connect(host, user, password); //发给所有指定的收件人,若使用message.getAllRecipients()则还包括抄送和暗送的人 transport.sendMessage(message, message.getRecipients(RecipientType.TO)); //关闭连接 transport.close(); /** * Transport的send静态方法包括了connect,saveChanges,sendMessage,close等一系列操作, * 但它连接同一个SMTP服务器每发一封邮件给服务器都得重新建立连接和断开连接, * 虽然使用较方便,但开销较大,不值得推荐。 */ // Transport.send(message, message.getRecipients(RecipientType.TO)); } private static MimeMessage getTextMessage(Session session) throws AddressException, MessagingException, UnsupportedEncodingException{ MimeMessage message=new MimeMessage(session); String from="iwtxokhtd@163.com";//发送方邮件地址 String to="277515433@qq.com";//接收方邮件地址 String subject="从163发到QQ来的邮件";//邮件主题,注意是中文的 String content="<h1>试试可以不</h1><img src="cid:my1.jpg" mce_src="cid:my1.jpg"/>";//cid为my1.jpg,下文会设置此cid message.setFrom(new InternetAddress(from)); message.setRecipient(RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setSentDate(new Date());//发送时间 MimeBodyPart picBodyPart=getPicBodyPart(content,"F://My头像.jpg"); MimeBodyPart attached1BodyPart=getAttachedBodyPart("F://nginx中文.txt");//注意附件名是中文的 MimeBodyPart attached2BodyPart=getAttachedBodyPart("F://nginx英文.doc"); MimeMultipart mmp=new MimeMultipart("mixed");//MIME消息头组合类型是mixed(html+附件) mmp.addBodyPart(picBodyPart); mmp.addBodyPart(attached1BodyPart); mmp.addBodyPart(attached2BodyPart); message.setContent(mmp); message.saveChanges(); return message; } /** * 处理文件名 * 此处是针对Window下的。 * @param filePath * @return */ private static String doHandlerFileName(String filePath){ String fileName=filePath; if(null !=filePath && !"".equals(filePath)){ fileName=filePath.substring(filePath.lastIndexOf("//")+1); } return fileName; } private static MimeBodyPart getAttachedBodyPart(String filePath) throws MessagingException, UnsupportedEncodingException{ MimeBodyPart attached=new MimeBodyPart(); FileDataSource fds=new FileDataSource(filePath); attached.setDataHandler(new DataHandler(fds)); String fileName=doHandlerFileName(filePath); attached.setFileName(MimeUtility.encodeWord(fileName));//处理附件文件的中文名问题 return attached; } /** * 处理html加图片的类型(related) * @param content * @param picName * @return * @throws MessagingException */ private static MimeBodyPart getPicBodyPart(String content,String picName) throws MessagingException{ MimeBodyPart contentPart=new MimeBodyPart(); MimeMultipart mmp=new MimeMultipart("related");//此处MIME消息头组合类型为related MimeBodyPart contented=new MimeBodyPart(); contented.setContent(content,"text/html;charset=gb2312");//因正文内容中有中文 mmp.addBodyPart(contented); MimeBodyPart picBodyPart=new MimeBodyPart(); FileDataSource fds=new FileDataSource(picName); picBodyPart.setDataHandler(new DataHandler(fds)); picBodyPart.setContentID("my1.jpg");//设置contentId mmp.addBodyPart(picBodyPart); contentPart.setContent(mmp); return contentPart; } public static void main(String[] args) throws AddressException, MessagingException, FileNotFoundException, IOException { String protocol="smtp"; sendEmail(getTextMessage(getSession(protocol)),protocol); } } 

 

查看结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值