javaMail 发送 复杂 邮件 附件
使用javaMail收邮件主要有两种协议,一种是pop3,一种是imap。这两种协议都可以用来收邮件,但是在其中的处理上是有区别的。pop3是不支持判断邮件是否为已读的,也就是说你不能直接从收件箱里面取到未读邮件,这需要自己进行判断,然而imap就提供了这样的功能,使用imap时可以很轻松的判断该邮件是否为已读或未读或其他。
此外收件箱中的每一封邮件都对应着一个MessageNumber,所以可以通过一个MessageNumber拿到对应的那封邮件。如:Message message = folder.getMessage(messageNumber);
pop3和imap主要区别就是能否判断邮件状态的问题,其他的操作都差不多.
pop3收邮件和解析邮件:
- package com.clxx.test;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.util.Enumeration;
- import java.util.Properties;
- import javax.mail.BodyPart;
- import javax.mail.Folder;
- import javax.mail.Message;
- import javax.mail.MessagingException;
- import javax.mail.Multipart;
- import javax.mail.Session;
- import javax.mail.Store;
- import javax.mail.internet.MimeMultipart;
- public class Email2 {
- public static void main(String args[]) throws MessagingException,
- IOException {
- Properties props = new Properties();
- props.setProperty("mail.store.protocol", "pop3");
- props.setProperty("mail.pop3.host", "pop3.sohu.com");
- Session session = Session.getDefaultInstance(props);
- Store store = session.getStore("pop3");
- store.connect("username@sohu.com", "password");
- Folder folder = store.getFolder("INBOX");
- folder.open(Folder.READ_WRITE);
- // 全部邮件数
- int messageCount = folder.getMessageCount();
- System.out.println(messageCount);
- Message[] messages = folder.getMessages();
- for (int i = 0; i < messages.length; i++) {
- Message message = messages[i];
- System.out.println(message.getSubject());
- // 删除邮件
- // message.setFlag(Flags.Flag.DELETED, true);
- // 标记为已读
- // message.setFlag(Flags.Flag.SEEN, true);
- //pop3没有判断邮件是否为已读的功能,要使用Imap才可以
- /*Flags flags = message.getFlags();
- if (flags.contains(Flags.Flag.SEEN))
- System.out.println("这是一封已读邮件");
- else {
- System.out.println("未读邮件");
- message.setFlag(Flags.Flag.SEEN, true);
- }*/
- System.out.println("发送时间:" + message.getSentDate());
- System.out.println("主题:" + message.getSubject());
- System.out.println("内容:" + message.getContent());
- //获取所有的Header,头信息
- Enumeration headers = message.getAllHeaders();
- System.out.println("----------------------allHeaders-----------------------------");
- /* while (headers.hasMoreElements()) {
- Header header = (Header)headers.nextElement();
- System.out.println(header.getName()+" ======= "+header.getValue());
- }*/
- //解析邮件内容
- Object content = message.getContent();
- if (content instanceof MimeMultipart) {
- MimeMultipart multipart = (MimeMultipart) content;
- parseMultipart(multipart);
- }
- System.out
- .println("========================================================");
- System.out
- .println("========================================================");
- }
- folder.close(true);
- store.close();
- }
- /**
- * 对复杂邮件的解析
- * @param multipart
- * @throws MessagingException
- * @throws IOException
- */
- public static void parseMultipart(Multipart multipart) throws MessagingException, IOException {
- int count = multipart.getCount();
- System.out.println("couont = "+count);
- for (int idx=0;idx<count;idx++) {
- BodyPart bodyPart = multipart.getBodyPart(idx);
- System.out.println(bodyPart.getContentType());
- if (bodyPart.isMimeType("text/plain")) {
- System.out.println("plain................."+bodyPart.getContent());
- } else if(bodyPart.isMimeType("text/html")) {
- System.out.println("html..................."+bodyPart.getContent());
- } else if(bodyPart.isMimeType("multipart/*")) {
- Multipart mpart = (Multipart)bodyPart.getContent();
- parseMultipart(mpart);
- } else if (bodyPart.isMimeType("application/octet-stream")) {
- String disposition = bodyPart.getDisposition();
- System.out.println(disposition);
- if (disposition.equalsIgnoreCase(BodyPart.ATTACHMENT)) {
- String fileName = bodyPart.getFileName();
- InputStream is = bodyPart.getInputStream();
- copy(is, new FileOutputStream("D:\\"+fileName));
- }
- }
- }
- }
- /**
- * 文件拷贝,在用户进行附件下载的时候,可以把附件的InputStream传给用户进行下载
- * @param is
- * @param os
- * @throws IOException
- */
- public static void copy(InputStream is, OutputStream os) throws IOException {
- byte[] bytes = new byte[1024];
- int len = 0;
- while ((len=is.read(bytes)) != -1 ) {
- os.write(bytes, 0, len);
- }
- if (os != null)
- os.close();
- if (is != null)
- is.close();
- }
- }
package com.clxx.test;import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Properties;import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeMultipart;public class Email2 {public static void main(String args[]) throws MessagingException,IOException {Properties props = new Properties();props.setProperty("mail.store.protocol", "pop3");props.setProperty("mail.pop3.host", "pop3.sohu.com");Session session = Session.getDefaultInstance(props);Store store = session.getStore("pop3");store.connect("username@sohu.com", "password");Folder folder = store.getFolder("INBOX");folder.open(Folder.READ_WRITE);// 全部邮件数int messageCount = folder.getMessageCount();System.out.println(messageCount);Message[] messages = folder.getMessages();for (int i = 0; i < messages.length; i++) {Message message = messages[i];System.out.println(message.getSubject());// 删除邮件// message.setFlag(Flags.Flag.DELETED, true);// 标记为已读// message.setFlag(Flags.Flag.SEEN, true);//pop3没有判断邮件是否为已读的功能,要使用Imap才可以/*Flags flags = message.getFlags();if (flags.contains(Flags.Flag.SEEN))System.out.println("这是一封已读邮件");else {System.out.println("未读邮件");message.setFlag(Flags.Flag.SEEN, true);}*/System.out.println("发送时间:" + message.getSentDate());System.out.println("主题:" + message.getSubject());System.out.println("内容:" + message.getContent());//获取所有的Header,头信息Enumeration headers = message.getAllHeaders();System.out.println("----------------------allHeaders-----------------------------");/* while (headers.hasMoreElements()) {Header header = (Header)headers.nextElement();System.out.println(header.getName()+" ======= "+header.getValue());}*///解析邮件内容Object content = message.getContent();if (content instanceof MimeMultipart) {MimeMultipart multipart = (MimeMultipart) content;parseMultipart(multipart);}System.out.println("========================================================");System.out.println("========================================================");}folder.close(true);store.close();}/*** 对复杂邮件的解析* @param multipart* @throws MessagingException* @throws IOException*/public static void parseMultipart(Multipart multipart) throws MessagingException, IOException {int count = multipart.getCount();System.out.println("couont = "+count);for (int idx=0;idx<count;idx++) {BodyPart bodyPart = multipart.getBodyPart(idx);System.out.println(bodyPart.getContentType());if (bodyPart.isMimeType("text/plain")) {System.out.println("plain................."+bodyPart.getContent());} else if(bodyPart.isMimeType("text/html")) {System.out.println("html..................."+bodyPart.getContent());} else if(bodyPart.isMimeType("multipart/*")) {Multipart mpart = (Multipart)bodyPart.getContent();parseMultipart(mpart);} else if (bodyPart.isMimeType("application/octet-stream")) {String disposition = bodyPart.getDisposition();System.out.println(disposition);if (disposition.equalsIgnoreCase(BodyPart.ATTACHMENT)) {String fileName = bodyPart.getFileName();InputStream is = bodyPart.getInputStream();copy(is, new FileOutputStream("D:\\"+fileName));}}}}/*** 文件拷贝,在用户进行附件下载的时候,可以把附件的InputStream传给用户进行下载* @param is* @param os* @throws IOException*/public static void copy(InputStream is, OutputStream os) throws IOException {byte[] bytes = new byte[1024];int len = 0;while ((len=is.read(bytes)) != -1 ) {os.write(bytes, 0, len);}if (os != null)os.close();if (is != null)is.close();}}
使用imap协议接收邮件:
- package com.clxx.test;
- import java.util.Properties;
- import javax.mail.Flags;
- import javax.mail.Folder;
- import javax.mail.Message;
- import javax.mail.Session;
- import com.sun.mail.imap.IMAPFolder;
- import com.sun.mail.imap.IMAPStore;
- /**
- * 使用imap协议获取未读邮件数
- *
- * @author w
- *
- */
- public class Email3 {
- public static void main(String[] args) throws Exception {
- String user = "username@sohu.com";// 邮箱的用户名
- String password = "password"; // 邮箱的密码
- Properties prop = System.getProperties();
- prop.put("mail.store.protocol", "imap");
- prop.put("mail.imap.host", "imap.sohu.com");
- Session session = Session.getInstance(prop);
- int total = 0;
- IMAPStore store = (IMAPStore) session.getStore("imap"); // 使用imap会话机制,连接服务器
- store.connect(user, password);
- IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX"); // 收件箱
- folder.open(Folder.READ_WRITE);
- // 获取总邮件数
- total = folder.getMessageCount();
- System.out.println("-----------------共有邮件:" + total
- + " 封--------------");
- // 得到收件箱文件夹信息,获取邮件列表
- System.out.println("未读邮件数:" + folder.getUnreadMessageCount());
- Message[] messages = folder.getMessages();
- int messageNumber = 0;
- for (Message message : messages) {
- System.out.println("发送时间:" + message.getSentDate());
- System.out.println("主题:" + message.getSubject());
- System.out.println("内容:" + message.getContent());
- Flags flags = message.getFlags();
- if (flags.contains(Flags.Flag.SEEN))
- System.out.println("这是一封已读邮件");
- else {
- System.out.println("未读邮件");
- }
- System.out
- .println("========================================================");
- System.out
- .println("========================================================");
- //每封邮件都有一个MessageNumber,可以通过邮件的MessageNumber在收件箱里面取得该邮件
- messageNumber = message.getMessageNumber();
- }
- Message message = folder.getMessage(messageNumber);
- System.out.println(message.getContent()+message.getContentType());
- // 释放资源
- if (folder != null)
- folder.close(true);
- if (store != null)
- store.close();
- }
- }