分享

使用 JavaMail 收发邮件,解决中文附件问题

 吹风散 2011-07-11
几天来一直在开发一个项目,其中一部分需要用 JavaMail 收发邮件,于是就在网上找了一些相关的源代码,最后经过整理和修改,终于好使了,希望能够给使用 JavaMail 收发邮件的朋友提供一个参考 J
    使用 JavaMail 收发邮件只需要下载两个开源的 jar 文件, mail.jar 和 activation.jar, 这两个 jar 包可以很容易的在网上找到,这里就不提供下载链接了。
下面是发送邮件SendMail.java(含附件)代码:
Java代码 复制代码 收藏代码
  1. //SendMail.java   
  2. import javax.mail.*;   
  3. import javax.mail.internet.*;   
  4. import java.util.*;   
  5. import javax.activation.*;   
  6.   
  7. public class SendMail ...{   
  8.        
  9.     public static void send(String customMailBoxAddress,String username,String password,String serverMailBoxAddress,String subject,String attachmentPath,String attachmentName) ...{   
  10.         //这里面使用新浪作为发送邮件的邮件服务器,其他的smtp服务器可以到相关网站上查到。   
  11.         String host = "smtp.sina.com.cn";   
  12.         //发送方邮箱地址(如BlogJava2006@blog.com.cn.)   
  13.         String from = customMailBoxAddress;   
  14.         //收件人邮箱地址   
  15.         String to = serverMailBoxAddress;   
  16.         //发送者的邮箱用户名   
  17.         String user = username;   
  18.         //发送者的邮箱密码   
  19.         String ps = password;   
  20.            
  21.         Properties props = new Properties();   
  22.            
  23.         //设置发送邮件的邮件服务器的属性(这里使用新浪的smtp服务器)   
  24.         props.put("mail.smtp.host", host);   
  25.         //需要经过授权,也就是有户名和密码的校验,这样才能通过验证(一定要有//这一条)   
  26.         props.put("mail.smtp.auth""true");   
  27.            
  28.         //用刚刚设置好的props对象构建一个session   
  29.         Session session = Session.getDefaultInstance(props);   
  30.            
  31.         //有了这句便可以在发送邮件的过程中在console处显示过程信息,供调试使   
  32.         //用(有的时候网络连通性不够好,发送邮件可能会有延迟,在这里面会有所//提示,所以最好是加上这句,避免盲目的等待)   
  33.         session.setDebug(true);   
  34.            
  35.         //定义消息对象   
  36.         MimeMessage message = new MimeMessage(session);   
  37.         try...{   
  38.             message.setFrom(new InternetAddress(from));   
  39.             message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));   
  40.             message.setSubject(subject);   
  41.                
  42.             // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件   
  43.             Multipart multipart = new MimeMultipart();   
  44.             //设置邮件的文本内容   
  45.             BodyPart contentPart = new MimeBodyPart();   
  46.             contentPart.setText("邮件的具体内容在此");   
  47.             multipart. addBodyPart(contentPart);   
  48.             //添加附件   
  49.             BodyPart attachmentPart= new MimeBodyPart();   
  50.             DataSource source = new FileDataSource(attachmentPath);   
  51.             attachmentPart.setDataHandler(new DataHandler(source));   
  52.             //注意:下面定义的enc对象用来处理中文附件名,否则名称是中文的附//件在邮箱里面显示的会是乱码,   
  53.             sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();   
  54.             messageBodyPart.setFileName("=?GBK?B?"+enc.encode(attachmentName.getBytes())+"?=");   
  55.             multipart.addBodyPart(messageBodyPart);   
  56.                
  57.             //将multipart对象放到message中   
  58.             message.setContent(multipart);   
  59.             //发送邮件   
  60.             message.saveChanges();   
  61.             Transport transport = session.getTransport("smtp");   
  62.             transport.connect(host, username, password);   
  63.             transport.sendMessage(message, message.getAllRecipients());   
  64.             transport.close();   
  65.         }catch(Exception e)...{   
  66.             e.printStackTrace();   
  67.         }   
  68.     }   
  69. }  

ReceiveMail.java代码如下:
Java代码 复制代码 收藏代码
  1. import javax.mail.*;   
  2. import java.util.*;   
  3. import java.io.*;   
  4.   
  5. public class ReceiveMail ...{   
  6.   
  7.     //处理任何一种邮件都需要的方法   
  8.     private void handle(Message msg) throws Exception ...{   
  9.         System.out.println("邮件主题:" + msg.getSubject());   
  10.         System.out.println("邮件作者:" + msg.getFrom()[0].toString());   
  11.         System.out.println("发送日期:" + msg.getSentDate());   
  12.     }   
  13.   
  14.     //处理文本邮件   
  15.     private void handleText(Message msg) throws Exception ...{   
  16.         this.handle(msg);   
  17.         System.out.println("邮件内容:"+msg.getContent());   
  18.     }   
  19.   
  20.     //处理Multipart邮件,包括了保存附件的功能   
  21.     private static void handleMultipart(Message msg) throws Exception ...{   
  22.         String disposition;   
  23.         BodyPart part;   
  24.   
  25.         Multipart mp = (Multipart) msg.getContent();   
  26.         //Miltipart的数量,用于除了多个part,比如多个附件   
  27.         int mpCount = mp.getCount();   
  28.         for (int m = 0; m < mpCount; m++) ...{   
  29.             this.handle(msg);   
  30.             part = mp.getBodyPart(m);   
  31.             disposition = part.getDisposition();   
  32.             //判断是否有附件   
  33.             if (disposition != null && disposition.equals(Part.ATTACHMENT))   
  34.             ...{   
  35.                 //这个方法负责保存附件   
  36.                 saveAttach(part);   
  37.             } else ...{   
  38.                 //不是附件,就只显示文本内容   
  39.                 System.out.println(part.getContent());   
  40.             }   
  41.         }   
  42.     }   
  43.   
  44.     private static void saveAttach(BodyPart part) throws Exception ...{   
  45.         //得到未经处理的附件名字   
  46.         String temp = part.getFileName();   
  47.         //除去发送邮件时,对中文附件名编码的头和尾,得到正确的附件名   
  48.         //(请参考发送邮件程序SendMail的附件名编码部分)   
  49.         String s = temp.substring(8, temp.indexOf("?="));   
  50.         //文件名经过了base64编码,下面是解码   
  51.         String fileName = base64Decoder(s);   
  52.         System.out.println("有附件:" + fileName);   
  53.   
  54.         InputStream in = part.getInputStream();   
  55.         FileOutputStream writer = new FileOutputStream(new File(   
  56.                 "保存附件的本地路径""\"+fileName));   
  57.         byte[] content = new byte[255];   
  58.         int read = 0;   
  59.         while ((read = in.read(content)) != -1) ...{   
  60.             writer.write(content);   
  61.         }   
  62.         writer.close();   
  63.         in.close();   
  64.     }   
  65.     //base64解码   
  66.     private static String base64Decoder(String s) throws Exception ...{   
  67.         sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();   
  68.         byte[] b = decoder.decodeBuffer(s);   
  69.         return (new String(b));   
  70.     }   
  71.   
  72.     public static void receive(String receiverMailBoxAddress, String username,String password) ...{   
  73.         //本人用的是yahoo邮箱,故接受邮件使用yahoo的pop3邮件服务器   
  74.         String host = "pop.mail.yahoo.com.cn";   
  75.         try ...{   
  76.             //连接到邮件服务器并获得邮件   
  77.             Properties prop = new Properties();   
  78.             prop.put("mail.pop3.host", host);   
  79.             Session session = Session.getDefaultInstance(prop);   
  80.             Store store = session.getStore("pop3");   
  81.             store.connect(host, username, password);   
  82.   
  83.             Folder inbox = store.getDefaultFolder().getFolder("INBOX");   
  84.             //设置inbox对象属性为可读写,这样可以控制在读完邮件后直接删除该附件   
  85.             inbox.open(Folder.READ_WRITE);   
  86.   
  87.             Message[] msg = inbox.getMessages();   
  88.   
  89.             FetchProfile profile = new FetchProfile();   
  90.             profile.add(FetchProfile.Item.ENVELOPE);   
  91.             inbox.fetch(msg, profile);   
  92.   
  93.             for (int i = 0; i < msg.length; i++) ...{   
  94.                 //标记此邮件的flag标志对象的DELETED位为true,可以在读完邮件后直接删除该附件,具体执行时间是在调用   
  95.                 //inbox.close()方法的时候   
  96.                 msg[i].setFlag(Flags.Flag.DELETED, true);   
  97.                 handleMultipart(msg[i]);   
  98.                 System.out.println("****************************");   
  99.             }   
  100.             if (inbox != null) ...{   
  101.                 //参数为true表明阅读完此邮件后将其删除,更多的属性请参考mail.jar的API   
  102.                 inbox.close(true);   
  103.             }   
  104.             if (store != null) ...{   
  105.                 store.close();   
  106.             }   
  107.         } catch (Exception e) ...{   
  108.             e.printStackTrace();   
  109.         }   
  110.     }   
  111. }  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多