java 邮件

    使用java语言实现邮件的简单的发送和接受。

说明使用Java应用程序发送E-mail比较简单,在使用下列程序之前,你需要将mail.jar和activation.jar 添加到你的CLASSPATH中。

 

1、这是一个简单的发送邮件的java程序,它可以向任何邮箱发送邮件,在使用过程中一定要注意,自己使用的发送邮件的邮箱需要开通SMTP服务,一般邮箱默认是不开通的。

(注意这个程序暂时还不能使用qq邮箱发送邮件,网上查阅说是因为qq邮箱使用了ssl加密)

 1  /**
 2      * java 发送邮件
 3      * 2016/5/19
 4      */
 5 package cn.mail;
 6 import java.util.Properties;
 7 import javax.mail.Message;
 8 import javax.mail.Session;
 9 import javax.mail.Transport;
10 import javax.mail.internet.InternetAddress;
11 import javax.mail.internet.MimeMessage;
12 public class mail_163 {
13    
14     public static void main(String[] args) throws Exception {
15          
16         Properties prop = new Properties();
17         prop.setProperty("mail.host", "smtp.sina.com");
18         prop.setProperty("mail.transport.protocol", "smtp");
19         prop.setProperty("mail.smtp.auth", "true");
20         //使用JavaMail发送邮件的5个步骤
21         //1、创建session
22         Session session = Session.getInstance(prop);
23         //开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
24         session.setDebug(true);
25         //2、通过session得到transport对象
26         Transport ts = session.getTransport();
27         //3、使用邮箱的用户名和密码连上邮件服务器,发送邮件时,发件人需要提交邮箱的用户名和密码给smtp服务器,用户名和密码都通过验证之后才能够正常发送邮件给收件人。
28         ts.connect("smtp.sina.com",25, "lvbiao_1995@sina.com", "1234567");
29         //4、创建邮件
30         Message message = createSimpleMail(session);
31         //5、发送邮件
32         ts.sendMessage(message, message.getAllRecipients());
33         System.out.println("发送成功");
34         ts.close();
35     }
36     //设置邮件内容
37     public static MimeMessage createSimpleMail(Session session)
38             throws Exception {
39         //创建邮件对象
40         MimeMessage message = new MimeMessage(session);
41         //指明邮件的发件人
42         message.setFrom(new InternetAddress("lvbiao_1995@sina.com"));
43         //指明邮件的收件人,现在发件人和收件人是一样的,那就是自己给自己发
44         message.setRecipient(Message.RecipientType.TO, new InternetAddress("lvbiao_1995@163.com"));
45         //邮件的标题
46         message.setSubject("snail发送 这是标题");
47         //邮件的文本内容
48         message.setContent("你好啊!这是我用java给qq邮箱发送的邮件,请您不用回复,这是文本内容", "text/html;charset=UTF-8");
49         //返回创建好的邮件对象
50         return message;
51     }
52 }
View Code

 

2、邮件发送改进版,可以使用qq邮箱发送,qq邮箱开启了ssl加密,必须在程序中使用qq邮箱自己生成的密码,而且要开启ssl加密。

下面这段代码开启了ssl加密

1 //如果使用qq邮箱,需要加上下列代码,因为qq邮箱使用了ssl加密,下面代码是用来开启ssl加密的,而且密码也必须是qq邮箱生成的安全密码
2         MailSSLSocketFactory sf = new MailSSLSocketFactory();
3         sf.setTrustAllHosts(true);
4         prop.put("mail.smtp.ssl.enable", "true");
5         prop.put("mail.smtp.ssl.socketFactory", sf);
View Code

其他的代码和1是一样的,只需要改动密码部分。

 

3、使用qq邮箱同时给多人发送邮件

 1  /**
 2      * java 发送邮件  同时给多人发送邮件
 3      * 2016/5/19
 4      */
 5 package cn.mail;
 6 import java.util.Properties;
 7 
 8 import javax.mail.Address;
 9 import javax.mail.Message;
10 import javax.mail.MessagingException;
11 import javax.mail.Session;
12 import javax.mail.Transport;
13 import javax.mail.internet.InternetAddress;
14 import javax.mail.internet.MimeMessage;
15 
16 import com.sun.mail.util.MailSSLSocketFactory;
17 public class mail_qq_m {
18    
19     public static void main(String[] args) throws Exception {
20          
21         Properties prop = new Properties();
22         prop.setProperty("mail.host", "smtp.sina.com");
23         prop.setProperty("mail.transport.protocol", "smtp");
24         prop.setProperty("mail.smtp.auth", "true");
25         //如果使用qq邮箱,需要加上下列代码,因为qq邮箱使用了ssl加密,下面代码是用来开启ssl加密的,而且密码也必须是qq邮箱生成的安全密码
26         MailSSLSocketFactory sf = new MailSSLSocketFactory();
27         sf.setTrustAllHosts(true);
28         prop.put("mail.smtp.ssl.enable", "true");
29         prop.put("mail.smtp.ssl.socketFactory", sf);
30         
31         //使用JavaMail发送邮件的5个步骤
32         //1、创建session
33         Session session = Session.getInstance(prop);
34         //开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
35         session.setDebug(true);
36         //2、通过session得到transport对象
37         Transport ts = session.getTransport();
38         //3、使用邮箱的用户名和密码连上邮件服务器,发送邮件时,发件人需要提交邮箱的用户名和密码给smtp服务器,用户名和密码都通过验证之后才能够正常发送邮件给收件人。
39         ts.connect("smtp.qq.com",465, "1396799517@qq.com", "12345");
40         //4、创建邮件
41         Message message = createSimpleMail(session);
42         //5、发送邮件
43         ts.sendMessage(message, message.getAllRecipients());
44         System.out.println("发送成功");
45         ts.close();
46     }
47     //设置邮件内容
48     public static MimeMessage createSimpleMail(Session session)
49             throws Exception {
50         //创建邮件对象
51         MimeMessage message = new MimeMessage(session);
52         //指明邮件的发件人
53         message.setFrom(new InternetAddress("1396799517@qq.com"));
54         //指明邮件的收件人,同时给多人发送
55         String to[] = {"lvbiao_1995@sina.com","lvbiao_1995@163.com","lvbiao_1995@qq.com"};
56         String toList = getMailList(to);  
57         InternetAddress[] iaToList = new InternetAddress().parse(toList);  
58         message.setRecipients(Message.RecipientType.TO,iaToList); 
59         
60         //邮件的标题
61         message.setSubject("snail发送 这是标题");
62         //邮件的文本内容
63         message.setContent("你好啊!这是我用java给qq邮箱发送的邮件,请您不用回复,这是文本内容,同时给多人发送的邮件~~~", "text/html;charset=UTF-8");
64         //返回创建好的邮件对象
65         return message;
66     }
67     //给多人发送邮件
68     private static String getMailList(String[] mailArray){  
69         
70         StringBuffer toList = new StringBuffer();  
71     int length = mailArray.length;  
72         if(mailArray!=null && length <2){  
73              toList.append(mailArray[0]);  
74         }else{  
75              for(int i=0;i<length;i++){  
76                      toList.append(mailArray[i]);  
77                      if(i!=(length-1)){  
78                          toList.append(",");  
79                      }  
80   
81              }  
82          }  
83      return toList.toString();  
84   
85 }  
86 }
View Code

 

4、使用POP3协议收取邮件

  1 package cn.mail;
  2 
  3 import java.io.BufferedInputStream;
  4 import java.io.BufferedOutputStream;
  5 import java.io.File;
  6 import java.io.FileNotFoundException;
  7 import java.io.FileOutputStream;
  8 import java.io.IOException;
  9 import java.io.InputStream;
 10 import java.io.UnsupportedEncodingException;
 11 import java.text.SimpleDateFormat;
 12 import java.util.Date;
 13 import java.util.Properties;
 14 
 15 import javax.mail.Address;
 16 import javax.mail.BodyPart;
 17 import javax.mail.Flags;
 18 import javax.mail.Folder;
 19 import javax.mail.Message;
 20 import javax.mail.MessagingException;
 21 import javax.mail.Multipart;
 22 import javax.mail.Part;
 23 import javax.mail.Session;
 24 import javax.mail.Store;
 25 import javax.mail.internet.InternetAddress;
 26 import javax.mail.internet.MimeMessage;
 27 import javax.mail.internet.MimeMultipart;
 28 import javax.mail.internet.MimeUtility;
 29 
 30 import com.sun.mail.util.MailSSLSocketFactory;
 31 
 32 /**
 33  * 使用POP3协议接收邮件
 34  */
 35 public class POP3mail {
 36     
 37     public static void main(String[] args) throws Exception {
 38         receive();
 39     }
 40     
 41     /**
 42      * 接收邮件
 43      */
 44     public static void receive() throws Exception {
 45         // 准备连接服务器的会话信息
 46         Properties props = new Properties();
 47         props.setProperty("mail.store.protocol", "pop3");        // 协议
 48         props.setProperty("mail.pop3.port", "995");                // 端口
 49         props.setProperty("mail.pop3.host", "pop.qq.com");    // pop3服务器
 50         //如果使用qq邮箱,需要加上下列代码,因为qq邮箱使用了ssl加密,下面代码是用来开启ssl加密的,而且密码也必须是qq邮箱生成的安全密码
 51         MailSSLSocketFactory sf = new MailSSLSocketFactory();
 52         sf.setTrustAllHosts(true);
 53         props.put("mail.pop3.ssl.enable", "true");
 54         props.put("mail.pop3.ssl.socketFactory", sf);
 55         
 56         // 创建Session实例对象
 57         Session session = Session.getInstance(props);
 58         session.setDebug(true);
 59         Store store = session.getStore("pop3");
 60         store.connect("1396799517@qq.com", "12345");
 61         
 62         // 获得收件箱
 63         Folder folder = store.getFolder("INBOX");
 64         /* Folder.READ_ONLY:只读权限
 65          * Folder.READ_WRITE:可读可写(可以修改邮件的状态)
 66          */
 67         folder.open(Folder.READ_WRITE);    //打开收件箱
 68         
 69         // 由于POP3协议无法获知邮件的状态,所以getUnreadMessageCount得到的是收件箱的邮件总数
 70         System.out.println("未读邮件数: " + folder.getUnreadMessageCount());
 71         
 72         // 由于POP3协议无法获知邮件的状态,所以下面得到的结果始终都是为0
 73         System.out.println("删除邮件数: " + folder.getDeletedMessageCount());
 74         System.out.println("新邮件: " + folder.getNewMessageCount());
 75         
 76         // 获得收件箱中的邮件总数
 77         System.out.println("邮件总数: " + folder.getMessageCount());
 78         
 79         // 得到收件箱中的所有邮件,并解析
 80         Message[] messages = folder.getMessages();
 81         parseMessage(messages);
 82         
 83         //释放资源
 84         folder.close(true);
 85         store.close();
 86     }
 87     
 88     /**
 89      * 解析邮件
 90      * @param messages 要解析的邮件列表
 91      */
 92     public static void parseMessage(Message... messages) throws MessagingException, IOException {
 93         if (messages == null || messages.length < 1) 
 94             throw new MessagingException("未找到要解析的邮件!");
 95         
 96         // 解析所有邮件
 97         for (int i = 0, count = messages.length; i < count; i++) {
 98             MimeMessage msg = (MimeMessage) messages[i];
 99             System.out.println("------------------解析第" + msg.getMessageNumber() + "封邮件-------------------- ");
100             System.out.println("主题: " + getSubject(msg));
101             System.out.println("发件人: " + getFrom(msg));
102             System.out.println("收件人:" + getReceiveAddress(msg, null));
103             System.out.println("发送时间:" + getSentDate(msg, null));
104             System.out.println("是否已读:" + isSeen(msg));
105             System.out.println("邮件优先级:" + getPriority(msg));
106             System.out.println("是否需要回执:" + isReplySign(msg));
107             System.out.println("邮件大小:" + msg.getSize() * 1024 + "kb");
108             boolean isContainerAttachment = isContainAttachment(msg);
109             System.out.println("是否包含附件:" + isContainerAttachment);
110             if (isContainerAttachment) {
111                 saveAttachment(msg, "/home/lvbiao/java/mail"+msg.getSubject() + "_"); //保存附件
112             } 
113             StringBuffer content = new StringBuffer(30);
114             getMailTextContent(msg, content);
115             System.out.println("邮件正文:" + (content.length() > 100 ? content.substring(0,100) + "..." : content));
116             System.out.println("------------------第" + msg.getMessageNumber() + "封邮件解析结束-------------------- ");
117             System.out.println();
118         }
119     }
120     
121     /**
122      * 获得邮件主题
123      * @param msg 邮件内容
124      * @return 解码后的邮件主题
125      */
126     public static String getSubject(MimeMessage msg) throws UnsupportedEncodingException, MessagingException {
127         return MimeUtility.decodeText(msg.getSubject());
128     }
129     
130     /**
131      * 获得邮件发件人
132      * @param msg 邮件内容
133      * @return 姓名 <Email地址>
134      * @throws MessagingException
135      * @throws UnsupportedEncodingException 
136      */
137     public static String getFrom(MimeMessage msg) throws MessagingException, UnsupportedEncodingException {
138         String from = "";
139         Address[] froms = msg.getFrom();
140         if (froms.length < 1)
141             throw new MessagingException("没有发件人!");
142         
143         InternetAddress address = (InternetAddress) froms[0];
144         String person = address.getPersonal();
145         if (person != null) {
146             person = MimeUtility.decodeText(person) + " ";
147         } else {
148             person = "";
149         }
150         from = person + "<" + address.getAddress() + ">";
151         
152         return from;
153     }
154     
155     /**
156      * 根据收件人类型,获取邮件收件人、抄送和密送地址。如果收件人类型为空,则获得所有的收件人
157      * <p>Message.RecipientType.TO  收件人</p>
158      * <p>Message.RecipientType.CC  抄送</p>
159      * <p>Message.RecipientType.BCC 密送</p>
160      * @param msg 邮件内容
161      * @param type 收件人类型
162      * @return 收件人1 <邮件地址1>, 收件人2 <邮件地址2>, ...
163      * @throws MessagingException
164      */
165     public static String getReceiveAddress(MimeMessage msg, Message.RecipientType type) throws MessagingException {
166         StringBuffer receiveAddress = new StringBuffer();
167         Address[] addresss = null;
168         if (type == null) {
169             addresss = msg.getAllRecipients();
170         } else {
171             addresss = msg.getRecipients(type);
172         }
173         
174         if (addresss == null || addresss.length < 1)
175             throw new MessagingException("没有收件人!");
176         for (Address address : addresss) {
177             InternetAddress internetAddress = (InternetAddress)address;
178             receiveAddress.append(internetAddress.toUnicodeString()).append(",");
179         }
180         
181         receiveAddress.deleteCharAt(receiveAddress.length()-1);    //删除最后一个逗号
182         
183         return receiveAddress.toString();
184     }
185     
186     /**
187      * 获得邮件发送时间
188      * @param msg 邮件内容
189      * @return yyyy年mm月dd日 星期X HH:mm
190      * @throws MessagingException
191      */
192     public static String getSentDate(MimeMessage msg, String pattern) throws MessagingException {
193         Date receivedDate = msg.getSentDate();
194         if (receivedDate == null)
195             return "";
196         
197         if (pattern == null || "".equals(pattern))
198             pattern = "yyyy年MM月dd日 E HH:mm ";
199         
200         return new SimpleDateFormat(pattern).format(receivedDate);
201     }
202     
203     /**
204      * 判断邮件中是否包含附件
205      * @param msg 邮件内容
206      * @return 邮件中存在附件返回true,不存在返回false
207      * @throws MessagingException
208      * @throws IOException
209      */
210     public static boolean isContainAttachment(Part part) throws MessagingException, IOException {
211         boolean flag = false;
212         if (part.isMimeType("multipart/*")) {
213             MimeMultipart multipart = (MimeMultipart) part.getContent();
214             int partCount = multipart.getCount();
215             for (int i = 0; i < partCount; i++) {
216                 BodyPart bodyPart = multipart.getBodyPart(i);
217                 String disp = bodyPart.getDisposition();
218                 if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
219                     flag = true;
220                 } else if (bodyPart.isMimeType("multipart/*")) {
221                     flag = isContainAttachment(bodyPart);
222                 } else {
223                     String contentType = bodyPart.getContentType();
224                     if (contentType.indexOf("application") != -1) {
225                         flag = true;
226                     }  
227                     
228                     if (contentType.indexOf("name") != -1) {
229                         flag = true;
230                     } 
231                 }
232                 
233                 if (flag) break;
234             }
235         } else if (part.isMimeType("message/rfc822")) {
236             flag = isContainAttachment((Part)part.getContent());
237         }
238         return flag;
239     }
240     
241     /**
242      * 判断邮件是否已读
243      * @param msg 邮件内容
244      * @return 如果邮件已读返回true,否则返回false
245      * @throws MessagingException 
246      */
247     public static boolean isSeen(MimeMessage msg) throws MessagingException {
248         return msg.getFlags().contains(Flags.Flag.SEEN);
249     }
250     
251     /**
252      * 判断邮件是否需要阅读回执
253      * @param msg 邮件内容
254      * @return 需要回执返回true,否则返回false
255      * @throws MessagingException
256      */
257     public static boolean isReplySign(MimeMessage msg) throws MessagingException {
258         boolean replySign = false;
259         String[] headers = msg.getHeader("Disposition-Notification-To");
260         if (headers != null)
261             replySign = true;
262         return replySign;
263     }
264     
265     /**
266      * 获得邮件的优先级
267      * @param msg 邮件内容
268      * @return 1(High):紧急  3:普通(Normal)  5:低(Low)
269      * @throws MessagingException 
270      */
271     public static String getPriority(MimeMessage msg) throws MessagingException {
272         String priority = "普通";
273         String[] headers = msg.getHeader("X-Priority");
274         if (headers != null) {
275             String headerPriority = headers[0];
276             if (headerPriority.indexOf("1") != -1 || headerPriority.indexOf("High") != -1)
277                 priority = "紧急";
278             else if (headerPriority.indexOf("5") != -1 || headerPriority.indexOf("Low") != -1)
279                 priority = "低";
280             else
281                 priority = "普通";
282         }
283         return priority;
284     } 
285     
286     /**
287      * 获得邮件文本内容
288      * @param part 邮件体
289      * @param content 存储邮件文本内容的字符串
290      * @throws MessagingException
291      * @throws IOException
292      */
293     public static void getMailTextContent(Part part, StringBuffer content) throws MessagingException, IOException {
294         //如果是文本类型的附件,通过getContent方法可以取到文本内容,但这不是我们需要的结果,所以在这里要做判断
295         boolean isContainTextAttach = part.getContentType().indexOf("name") > 0;    
296         if (part.isMimeType("text/*") && !isContainTextAttach) {
297             content.append(part.getContent().toString());
298         } else if (part.isMimeType("message/rfc822")) {    
299             getMailTextContent((Part)part.getContent(),content);
300         } else if (part.isMimeType("multipart/*")) {
301             Multipart multipart = (Multipart) part.getContent();
302             int partCount = multipart.getCount();
303             for (int i = 0; i < partCount; i++) {
304                 BodyPart bodyPart = multipart.getBodyPart(i);
305                 getMailTextContent(bodyPart,content);
306             }
307         }
308     }
309     
310     /**
311      * 保存附件
312      * @param part 邮件中多个组合体中的其中一个组合体
313      * @param destDir  附件保存目录
314      * @throws UnsupportedEncodingException
315      * @throws MessagingException
316      * @throws FileNotFoundException
317      * @throws IOException
318      */
319     public static void saveAttachment(Part part, String destDir) throws UnsupportedEncodingException, MessagingException,
320             FileNotFoundException, IOException {
321         if (part.isMimeType("multipart/*")) {
322             Multipart multipart = (Multipart) part.getContent();    //复杂体邮件
323             //复杂体邮件包含多个邮件体
324             int partCount = multipart.getCount();
325             for (int i = 0; i < partCount; i++) {
326                 //获得复杂体邮件中其中一个邮件体
327                 BodyPart bodyPart = multipart.getBodyPart(i);
328                 //某一个邮件体也有可能是由多个邮件体组成的复杂体
329                 String disp = bodyPart.getDisposition();
330                 if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
331                     InputStream is = bodyPart.getInputStream();
332                     saveFile(is, destDir, decodeText(bodyPart.getFileName()));
333                 } else if (bodyPart.isMimeType("multipart/*")) {
334                     saveAttachment(bodyPart,destDir);
335                 } else {
336                     String contentType = bodyPart.getContentType();
337                     if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) {
338                         saveFile(bodyPart.getInputStream(), destDir, decodeText(bodyPart.getFileName()));
339                     }
340                 }
341             }
342         } else if (part.isMimeType("message/rfc822")) {
343             saveAttachment((Part) part.getContent(),destDir);
344         }
345     }
346     
347     /**
348      * 读取输入流中的数据保存至指定目录
349      * @param is 输入流
350      * @param fileName 文件名
351      * @param destDir 文件存储目录
352      * @throws FileNotFoundException
353      * @throws IOException
354      */
355     private static void saveFile(InputStream is, String destDir, String fileName)
356             throws FileNotFoundException, IOException {
357         BufferedInputStream bis = new BufferedInputStream(is);
358         BufferedOutputStream bos = new BufferedOutputStream(
359                 new FileOutputStream(new File(destDir + fileName)));
360         int len = -1;
361         while ((len = bis.read()) != -1) {
362             bos.write(len);
363             bos.flush();
364         }
365         bos.close();
366         bis.close();
367     }
368     
369     /**
370      * 文本解码
371      * @param encodeText 解码MimeUtility.encodeText(String text)方法编码后的文本
372      * @return 解码后的文本
373      * @throws UnsupportedEncodingException
374      */
375     public static String decodeText(String encodeText) throws UnsupportedEncodingException {
376         if (encodeText == null || "".equals(encodeText)) {
377             return "";
378         } else {
379             return MimeUtility.decodeText(encodeText);
380         }
381     }
382 }
View Code

 

5、使用IMAP协议收取邮件

 1 package cn.mail;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.InputStreamReader;
 5 import java.util.Properties;
 6 
 7 import javax.mail.Flags.Flag;
 8 import javax.mail.Folder;
 9 import javax.mail.Message;
10 import javax.mail.Session;
11 import javax.mail.Store;
12 import javax.mail.internet.MimeUtility;
13 
14 import com.sun.mail.imap.IMAPMessage;
15 import com.sun.mail.util.MailSSLSocketFactory;
16 
17 /**
18  * <b>使用IMAP协议接收邮件</b><br/>
19  * <p>POP3和IMAP协议的区别:</p>
20  * <b>POP3</b>协议允许电子邮件客户端下载服务器上的邮件,但是在客户端的操作(如移动邮件、标记已读等),不会反馈到服务器上,<br/>
21  * 比如通过客户端收取了邮箱中的3封邮件并移动到其它文件夹,邮箱服务器上的这些邮件是没有同时被移动的。<br/>
22  * <p><b>IMAP</b>协议提供webmail与电子邮件客户端之间的双向通信,客户端的操作都会同步反应到服务器上,对邮件进行的操作,服务
23  * 上的邮件也会做相应的动作。比如在客户端收取了邮箱中的3封邮件,并将其中一封标记为已读,将另外两封标记为删除,这些操作会
24  * 即时反馈到服务器上。</p>
25  * <p>两种协议相比,IMAP 整体上为用户带来更为便捷和可靠的体验。POP3更易丢失邮件或多次下载相同的邮件,但IMAP通过邮件客户端
26  * 与webmail之间的双向同步功能很好地避免了这些问题。</p>
27  */
28 public class IMAPmail {
29 
30     public static void main(String[] args) throws Exception {
31         // 准备连接服务器的会话信息
32         Properties props = new Properties();
33         props.setProperty("mail.store.protocol", "imap");
34         props.setProperty("mail.imap.host", "imap.qq.com");
35         props.setProperty("mail.imap.port", "993");
36       //如果使用qq邮箱,需要加上下列代码,因为qq邮箱使用了ssl加密,下面代码是用来开启ssl加密的,而且密码也必须是qq邮箱生成的安全密码
37         MailSSLSocketFactory sf = new MailSSLSocketFactory();
38         sf.setTrustAllHosts(true);
39         props.put("mail.imap.ssl.enable", "true");
40         props.put("mail.imap.ssl.socketFactory", sf);
41         
42         // 创建Session实例对象
43         Session session = Session.getInstance(props);
44         
45         //开启session的debug模式,这样就可以查看到程序发送Email的运行状态
46         session.setDebug(true);
47         
48         // 创建IMAP协议的Store对象
49         Store store = session.getStore("imap");
50         
51         // 连接邮件服务器
52         store.connect(null,"1396799517@qq.com", "123456");
53         
54         // 获得收件箱
55         Folder folder = store.getFolder("INBOX");
56         // 以读写模式打开收件箱
57         folder.open(Folder.READ_WRITE);
58         
59         // 获得收件箱的邮件列表
60         Message[] messages = folder.getMessages();
61         
62         // 打印不同状态的邮件数量
63         System.out.println("收件箱中共" + messages.length + "封邮件!");
64         System.out.println("收件箱中共" + folder.getUnreadMessageCount() + "封未读邮件!");
65         System.out.println("收件箱中共" + folder.getNewMessageCount() + "封新邮件!");
66         System.out.println("收件箱中共" + folder.getDeletedMessageCount() + "封已删除邮件!");
67         
68         System.out.println("------------------------开始解析邮件----------------------------------");
69         
70         // 解析邮件
71         for (Message message : messages) {
72             IMAPMessage msg = (IMAPMessage) message;
73             String subject = MimeUtility.decodeText(msg.getSubject());
74             System.out.println("[" + subject + "]未读,是否需要阅读此邮件(yes/no)?");
75             BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
76             String answer = reader.readLine();
77             if ("yes".equalsIgnoreCase(answer)) {
78                 POP3mail.parseMessage(msg);    // 解析邮件,使用的是POP3中的解析函数。
79                 // 第二个参数如果设置为true,则将修改反馈给服务器。false则不反馈给服务器
80                 msg.setFlag(Flag.SEEN, true);    //设置已读标志
81             }
82         }
83         System.out.println("------------------------邮件解析结束----------------------------------");
84         // 关闭资源
85         folder.close(false);
86         store.close();
87     }
88 }
View Code

 

6、发送带有附件的邮件

  要发送带有附件的邮件,只需要在发送邮件的内容中加上下面的语句。

 1 // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
 2     Multipart multipart = new MimeMultipart();
 3     // 添加邮件正文
 4     MimeBodyPart contentPart = new MimeBodyPart();
 5     contentPart.setContent("hi,This is  my Email .i am LvBiao.", "text/html;charset=UTF-8");
 6     multipart.addBodyPart(contentPart);
 7     File attachment = new File("/home/lvbiao/java/j.txt");
 8     // 添加附件的内容
 9     if (attachment != null) {
10         MimeBodyPart attachmentBodyPart = new MimeBodyPart();
11         FileDataSource source = new FileDataSource(attachment);
12         attachmentBodyPart.setDataHandler(new DataHandler(source));
13         //MimeUtility.encodeWord可以避免文件名乱码
14         attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
15         multipart.addBodyPart(attachmentBodyPart);
16     }
17     // 将multipart对象放到message中
18     message.setContent(multipart);
19     // 保存邮件
20     message.saveChanges();
View Code

 

posted on 2016-05-19 16:37  snail-lb  阅读(422)  评论(0编辑  收藏  举报