`
Clayz
  • 浏览: 292766 次
  • 性别: Icon_minigender_1
  • 来自: 东京
社区版块
存档分类
最新评论

用Java Mail发送带图片附件

    博客分类:
  • Java
阅读更多

1,读入图片的方式:
发现网上讲的很多读取图片的方式都不对,按下面提供的这个方法来读取,保证成功。

java 代码
 
  1. private   byte [] getImageBytes(String file) {  
  2.     byte [] myData =  null ;  
  3.     InputStream input = getClass().getClassLoader().getResourceAsStream(file);  
  4.     try  {  
  5.         ByteArrayOutputStream byteArray = new  ByteArrayOutputStream();  
  6.         int  ch =  0 ;  
  7.         while  ((ch = input.read()) != - 1 ) {  
  8.         byteArray.write(ch);  
  9.     }  
  10.     // System.out.println(byteArray.size());   
  11.     myData = byteArray.toByteArray();  
  12.     // System.out.println(myData.length);   
  13.     }  
  14.     catch  (Exception e) {  
  15.         e.printStackTrace();}  
  16.         return  myData;  
  17.     }  


2,发送邮件的“机关”

java 代码
 
  1. MimeMessage msg =  new  MimeMessage(mailSession);  
  2. msg.setFrom(new  InternetAddress( this .getSenderAddress()));  
  3. msg.setSubject(this .getTitle());  
  4. msg.setSentDate(new  Date());  
  5. Address[] adds = InternetAddress.parse(getToAddress());  
  6. msg.addRecipients(javax.mail.Message.RecipientType.TO, adds);  
  7. // 新建一个MimeMultipart对象用来存放BodyPart对象(事实上可以存放多个)   
  8. MimeMultipart mm = new  MimeMultipart( "related" );  
  9. // 新建一个存放信件内容的BodyPart对象   
  10. BodyPart mdp = new  MimeBodyPart();  
  11. // 给BodyPart对象设置内容和格式/编码方式   
  12. mdp.setContent(this .getContent(),  "text/html;charset=utf-8" );  
  13. // 这句很重要,千万不要忘了   
  14. mm.addBodyPart(mdp);  
  15.   
  16. // ---------图片处理开始!!!!!!!!!!!!!!!!   
  17. mdp = new  MimeBodyPart();  
  18. byte  bbb[] =  new   byte [ 1024  *  10 ];  
  19. this .getClass().getClassLoader().getResourceAsStream( "notice.jpg" ).read(bbb);  
  20. DataHandler dh = new  DataHandler( new  ByteArrayDataSource( this .getImageBytes( "notice.jpg" ), "application/octet-stream" ));  
  21. mdp.setDataHandler(dh);  
  22. // 加上这句将作为附件发送,否则将作为信件的文本内容   
  23. mdp.setFileName("1.jpg" );  
  24. mdp.setHeader("content-id" "<IMG1>" );  
  25. // 将含有附件的BodyPart加入到MimeMultipart对象中   
  26. mm.addBodyPart(mdp);  
  27.   
  28. // 把mm作为消息对象的内容   
  29. msg.setContent(mm); 


3,一个实际应用的完整代码
要求根据一个格式文件和模版,发一封漂亮的邮件,所以需要用到HTML格式来发送邮件。不多说了,看代码吧!

java 代码
 
  1. import  java.io.ByteArrayOutputStream;  
  2. import  java.io.File;  
  3. import  java.io.FileReader;  
  4. import  java.io.IOException;  
  5. import  java.io.InputStream;  
  6. import  java.util.Date;  
  7. import  java.util.HashMap;  
  8. import  java.util.Map;  
  9. import  java.util.Properties;  
  10. import  javax.activation.DataHandler;  
  11. import  javax.mail.Address;  
  12. import  javax.mail.BodyPart;  
  13. import  javax.mail.internet.InternetAddress;  
  14. import  javax.mail.internet.MimeBodyPart;  
  15. import  javax.mail.internet.MimeMessage;  
  16. import  javax.mail.internet.MimeMultipart;  
  17. import  javax.mail.util.ByteArrayDataSource;  
  18. /** */ /**  
  19. *  
  20. * @author robin  
  21. * @version $Revision: 1.4 $  
  22. */   
  23. public   class  SendMailUtil {  
  24.     private  String mailServerAddress;  
  25.     private  String user;  
  26.     private  String password;  
  27.     private  String toAddress;  
  28.     private  String ccAddress;  
  29.     private  String title;  
  30.     private  String content;  
  31.     private   boolean  isHtml =  true ;  
  32.     private  Map attachmentFiles =  null ;  
  33.     private  String senderAddress;  
  34.   
  35.     private   byte [] getImageBytes(String file) {  
  36.         byte [] myData =  null ;  
  37.         InputStream input = getClass().getClassLoader().getResourceAsStream(file);  
  38.         try  {  
  39.             ByteArrayOutputStream byteArray = new  ByteArrayOutputStream();  
  40.             int  ch =  0 ;  
  41.             while  ((ch = input.read()) != - 1 ) {  
  42.                 byteArray.write(ch);  
  43.             }  
  44.             // System.out.println(byteArray.size());   
  45.             myData = byteArray.toByteArray();  
  46.             // System.out.println(myData.length);   
  47.         } catch  (Exception e) {  
  48.             e.printStackTrace();  
  49.         }  
  50.         return  myData;  
  51.     }  
  52.   
  53.     public   void  sendMail()  throws  Exception {  
  54.         Properties pos = new  Properties();  
  55.         pos.put("mail.smtp.host" "10.5.1.1" );  
  56.         javax.mail.Session mailSession = javax.mail.Session.getInstance(pos,null );  
  57.         MimeMessage msg = new  MimeMessage(mailSession);  
  58.         msg.setFrom(new  InternetAddress( this .getSenderAddress()));  
  59.         msg.setSubject(this .getTitle());  
  60.         msg.setSentDate(new  Date());  
  61.         Address[] adds = InternetAddress.parse(getToAddress());  
  62.         msg.addRecipients(javax.mail.Message.RecipientType.TO, adds);  
  63.         // 新建一个MimeMultipart对象用来存放BodyPart对象(事实上可以存放多个)   
  64.         MimeMultipart mm = new  MimeMultipart( "related" );  
  65.         // 新建一个存放信件内容的BodyPart对象   
  66.         BodyPart mdp = new  MimeBodyPart();  
  67.         // 给BodyPart对象设置内容和格式/编码方式   
  68.         mdp.setContent(this .getContent(),  "text/html;charset=utf-8" );  
  69.         // 这句很重要,千万不要忘了   
  70.         mm.addBodyPart(mdp);  
  71.   
  72.         // ---------图片处理开始!!!!!!!!!!!!!!!!   
  73.         mdp = new  MimeBodyPart();  
  74.         byte  bbb[] =  new   byte [ 1024  *  10 ];  
  75.         this .getClass().getClassLoader().getResourceAsStream( "notice.jpg" ).read(bbb);  
  76.         DataHandler dh = new  DataHandler( new  ByteArrayDataSource( this .getImageBytes( "notice.jpg" ),  "application/octet-stream" ));  
  77.         mdp.setDataHandler(dh);  
  78.         // 加上这句将作为附件发送,否则将作为信件的文本内容   
  79.         mdp.setFileName("1.jpg" );  
  80.         mdp.setHeader("content-id" "<IMG1>" );  
  81.         // 将含有附件的BodyPart加入到MimeMultipart对象中   
  82.         mm.addBodyPart(mdp);  
  83.         // ---------图片处理结束!!!!!!!!!!!!!!!!   
  84.   
  85.         // 把mm作为消息对象的内容   
  86.         msg.setContent(mm);  
  87.         msg.saveChanges();  
  88.         javax.mail.Transport transport = mailSession.getTransport("smtp" );  
  89.         transport.connect();  
  90.         transport.sendMessage(msg, msg.getAllRecipients());  
  91.         transport.close();  
  92.     }  
  93.   
  94.     public  String getCcAddress() {  
  95.         return  ccAddress;  
  96.     }  
  97.   
  98.     public  String getContent() {  
  99.         if  (content ==  null ) {  
  100.             return   "" ;  
  101.         } else  {  
  102.             return  content;  
  103.         }  
  104.     }  
  105.   
  106.     public  String getMailServerAddress() {  
  107.         return   "10.5.1.1" ;  
  108.     }  
  109.   
  110.     public  String getUser() {  
  111.         if  (user ==  null  || user.equals( "" )) {  
  112.             user = "" ;  
  113.         }  
  114.         return  user;  
  115.     }  
  116.   
  117.     public  String getPassword() {  
  118.         if  (password ==  null  || password.equals( "" )) {  
  119.             password = "" ;  
  120.         }  
  121.         return  password;  
  122.     }  
  123.   
  124.     public  String getTitle() {  
  125.         if  (title ==  null ) {  
  126.             return   "" ;  
  127.         } else  {  
  128.             return  title;  
  129.         }  
  130.     }  
  131.   
  132.     public  String getToAddress() {  
  133.         return  toAddress;  
  134.     }  
  135.   
  136.     public   boolean  isHtml() {  
  137.         return  isHtml;  
  138.     }  
  139.   
  140.     public   void  setCcAddress(String ccAddress) {  
  141.         this .ccAddress = ccAddress;  
  142.     }  
  143.   
  144.     public   void  setContent(String content) {  
  145.         this .content = content;  
  146.     }  
  147.   
  148.     public   void  setMailServerAddress(String mailServerAddress) {  
  149.         this .mailServerAddress = mailServerAddress;  
  150.     }  
  151.   
  152.     public   void  setUser(String user) {  
  153.         this .user = user;  
  154.     }  
  155.   
  156.     public   void  setPassword(String password) {  
  157.         this .password = password;  
  158.     }  
  159.   
  160.     public   void  setTitle(String title) {  
  161.         this .title = title;  
  162.     }  
  163.   
  164.     public   void  setToAddress(String toAddress) {  
  165.         this .toAddress = toAddress;  
  166.     }  
  167.   
  168.     public   void  setIsHtml( boolean  isHtml) {  
  169.         this .isHtml = isHtml;  
  170.     }  
  171.   
  172.     public   void  setAttachmentFiles(Map attachmentFiles) {  
  173.         this .attachmentFiles = attachmentFiles;  
  174.     }  
  175.   
  176.     public  Map getAttachmentFiles() {  
  177.         return  attachmentFiles;  
  178.     }  
  179.   
  180.     public   void  setHtml( boolean  isHtml) {  
  181.         this .isHtml = isHtml;  
  182.     }  
  183.   
  184.     public  String getSenderAddress() {  
  185.         return  senderAddress;  
  186.     }  
  187.   
  188.     public   void  setSenderAddress(String senderAddress) {  
  189.         this .senderAddress = senderAddress;  
  190.     }  
  191.   
  192.     public  String readMailTemplate(String year, String season) throws  IOException {  
  193.         ClassLoader loder = this .getClass().getClassLoader();  
  194.         InputStream is = loder.getResourceAsStream("t.html" );  
  195.         byte [] buf =  new   byte [ 1024  *  5 ];  
  196.         is.read(buf);  
  197.         String t = new  String(buf,  "utf-8" );  
  198.         t = t.replaceFirst("#year" , year);  
  199.         t = t.replaceFirst("#season" , season);  
  200.         // System.out.println(t);   
  201.         return  t;  
  202.     }  
  203.   
  204.     public   static   void  sendNoticeMail(String title, String year, String season,String sender, File f) {  
  205.         SendMailUtil logic = new  SendMailUtil();  
  206.         try  {  
  207.             logic.setTitle(title);  
  208.             // logic.setMailServerAddress("10.5.1.1");   
  209.             String temp = logic.readMailTemplate(year, season);  
  210.             logic.setSenderAddress(sender);  
  211.             FileReader fr = new  FileReader(f);  
  212.   
  213.             char [] ch =  new   char [ new  Long(f.length()).intValue()];  
  214.             fr.read(ch);  
  215.             StringBuffer sb = new  StringBuffer( new  Long(f.length()).intValue());  
  216.             for  ( int  i =  0 ; i < ch.length; i++) {  
  217.                 sb.append(ch[i]);  
  218.             }  
  219.             String[] all = sb.toString().split("\n" );  
  220.   
  221.             // System.out.println(sb.toString());   
  222.             for  ( int  i =  0 ; i < all.length; i++) {  
  223.                 if  (all[i].equals( "" )) {  
  224.                     continue ;  
  225.                 }  
  226.                 String t = temp;  
  227.                 String[] item = all[i].split("," );  
  228.                 logic.setToAddress(item[2 ]);  
  229.                 // 处理内容   
  230.                 t = t.replaceFirst("#name" , item[ 1 ] +  "("  + item[ 0 ] +  ")" );  
  231.                 t = t.replaceAll("#total" , item[ 3 ]);  
  232.                 t = t.replaceFirst("#tax" , item[ 4 ]);  
  233.                 t = t.replaceFirst("#actualTotal" , item[ 5 ]);  
  234.                 logic.setContent(t);  
  235.                 logic.sendMail();  
  236.             }  
  237.         } catch  (Exception e) {  
  238.             e.printStackTrace();  
  239.         }  
  240.     }  
  241. }  


4,小技巧
我第一次发送后,发现读取图片的程序不对,在Outlook 2003中打开邮件,发现没有出现图片,搞半天也不知道是什么原因,后来我用FoxMail打开邮件,发现图片附件上打了个叉叉,才知道是附件中的图片读 取不对,如果你有这样的问题,不妨换个Mail客户端试试。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics