转自:https://blog.csdn.net/star_fly4/article/details/52037587
一、RFC882文档简单说明
RFC882文档规定了如何编写一封简单的邮件(纯文本邮件),一封简单的邮件包含邮件头和邮件体两个部分,邮件头和邮件体之间使用空行分隔。
邮件头包含的内容有:
- from字段 --用于指明发件人
- to字段 --用于指明收件人
- subject字段 --用于说明邮件主题
- cc字段 -- 抄送,将邮件发送给收件人的同时抄送给另一个收件人,收件人可以看到邮件抄送给了谁
- bcc字段 -- 密送,将邮件发送给收件人的同时将邮件秘密发送给另一个收件人,收件人无法看到邮件密送给了
二、MIME协议简单介绍
在我们的实际开发当中,一封邮件既可能包含图片,又可能包含有附件,在这样的情况下,RFC882文档规定的邮件格式就无法满足要求了。
MIME协议是对RFC822文档的升级和补充,它描述了如何生产一封复杂的邮件。通常我们把MIME协议描述的邮件称之为MIME邮件。MIME协议描述的数据称之为MIME消息。
对于一封复杂邮件,如果包含了多个不同的数据,MIME协议规定了要使用分隔线对多段数据进行分隔,并使用Content-Type头字段对数据的类型、以及多个数据之间的关系进行描述。
三、使用JavaMail创建邮件和发送邮件图解
JavaMail创建的邮件是基于MIME协议的。因此可以使用JavaMail创建出包含图片,包含附件的复杂邮件。
四、邮件发送代码
1 导入开发包mail.jar 下载地址
package cjr.javamail; import java.io.File; import java.util.Date; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.Address; import javax.mail.Authenticator; import javax.mail.Message.RecipientType; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; 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; import org.junit.Test; public class SendEmail { // 邮件发送协议 private final static String PROTOCOL = "smtp"; // SMTP邮件服务器 private final static String HOST = "smtp.163.com"; // SMTP邮件服务器默认端口 private final static String PORT = "25"; // 是否要求身份认证 private final static String IS_AUTH = "true"; // 是否启用调试模式(启用调试模式可打印客户端与服务器交互过程时一问一答的响应消息) private final static String IS_ENABLED_DEBUG_MOD = "true"; // 发件人 private static String from = "chenxingxing745@163.com"; private static String verification_code = "cx*******29"; // 收件人 private static String to = "chenjiaren745@163.com"; // 初始化连接邮件服务器的会话信息 private static Properties props = null; static { props = new Properties(); props.setProperty("mail.transport.protocol", PROTOCOL); props.setProperty("mail.smtp.host", HOST); props.setProperty("mail.smtp.port", PORT); props.setProperty("mail.smtp.auth", IS_AUTH); props.setProperty("mail.debug",IS_ENABLED_DEBUG_MOD); } /** * 发送简单的文本邮件 */ @Test public void sendTextEmail() throws Exception { // 创建Session实例对象 Session session = Session.getDefaultInstance(props); // 创建MimeMessage实例对象 MimeMessage message = new MimeMessage(session); // 设置发件人 message.setFrom(new InternetAddress(from)); // 设置邮件主题 message.setSubject("使用javamail发送简单文本邮件"); // 设置收件人 message.setRecipient(RecipientType.TO, new InternetAddress(to)); // 设置发送时间 message.setSentDate(new Date()); // 设置纯文本内容为邮件正文 message.setText("使用POP3协议发送文本邮件测试!!!"); // 保存并生成最终的邮件内容 message.saveChanges(); // 获得Transport实例对象 Transport transport = session.getTransport(); // 打开连接 transport.connect("chenxingxing745", "cx*******9"); // 将message对象传递给transport对象,将邮件发送出去 transport.sendMessage(message, message.getAllRecipients()); // 关闭连接 transport.close(); } /** * 发送简单的html邮件 */ @Test public void sendHtmlEmail() throws Exception { // 创建Session实例对象 Session session = Session.getInstance(props, new MyAuthenticator(from,verification_code)); // 创建MimeMessage实例对象 MimeMessage message = new MimeMessage(session); // 设置邮件主题 message.setSubject("html邮件主题"); // 设置发送人 message.setFrom(new InternetAddress(from)); // 设置发送时间 message.setSentDate(new Date()); // 设置收件人 message.setRecipients(RecipientType.TO, InternetAddress.parse(to)); // 设置html内容为邮件正文,指定MIME类型为text/html类型,并指定字符编码为gbk message.setContent("<span style='color:red;'>html邮件测试...</span>","text/html;charset=gbk"); // 保存并生成最终的邮件内容 message.saveChanges(); // 发送邮件 Transport.send(message); } /** * 发送带内嵌图片的HTML邮件 */ @Test public void sendHtmlWithInnerImageEmail() throws MessagingException { // 创建Session实例对象 Session session = Session.getDefaultInstance(props, new MyAuthenticator(from,verification_code)); // 创建邮件内容 MimeMessage message = new MimeMessage(session); // 邮件主题,并指定编码格式 message.setSubject("带内嵌图片的HTML邮件", "utf-8"); // 发件人 message.setFrom(new InternetAddress(from)); // 收件人 message.setRecipients(RecipientType.TO, InternetAddress.parse(to)); message.setSentDate(new Date()); // 创建一个MIME子类型为“related”的MimeMultipart对象 MimeMultipart mp = new MimeMultipart("related"); // 创建一个表示正文的MimeBodyPart对象,并将它加入到前面创建的MimeMultipart对象中 MimeBodyPart htmlPart = new MimeBodyPart(); mp.addBodyPart(htmlPart); // 将MimeMultipart对象设置为整个邮件的内容 message.setContent(mp); // 创建一个表示图片资源的MimeBodyPart对象,将将它加入到前面创建的MimeMultipart对象中 MimeBodyPart imagePart = new MimeBodyPart(); MimeBodyPart imagePart1 = new MimeBodyPart(); mp.addBodyPart(imagePart); mp.addBodyPart(imagePart1); // 设置内嵌图片邮件体 DataSource ds = new FileDataSource(new File("src/psb.jpg")); DataHandler dh = new DataHandler(ds); imagePart.setDataHandler(dh); imagePart.setContentID("psb.jpg"); // 设置内容编号,用于其它邮件体引用 DataSource ds1 = new FileDataSource(new File("src/loading.gif")); DataHandler dh1 = new DataHandler(ds1); imagePart1.setDataHandler(dh1); imagePart1.setContentID("loading.gif"); // 设置内容编号,用于其它邮件体引用 // 创建一个MIME子类型为"alternative"的MimeMultipart对象,并作为前面创建的htmlPart对象的邮件内容 MimeMultipart htmlMultipart = new MimeMultipart("alternative"); // 创建一个表示html正文的MimeBodyPart对象 MimeBodyPart htmlBodypart = new MimeBodyPart(); // 其中cid=androidlogo.gif是引用邮件内部的图片,即imagePart.setContentID("androidlogo.gif");方法所保存的图片 htmlBodypart.setContent("<span style='color:red;'>这是带内嵌图片的HTML邮件哦!!!<img src="cid:psb.jpg" /></span>多张图片<img src="cid:psb.jpg" />侧认<img src="cid:loading.gif" />识","text/html;charset=utf-8"); htmlMultipart.addBodyPart(htmlBodypart); htmlPart.setContent(htmlMultipart); // 保存并生成最终的邮件内容 message.saveChanges(); // 发送邮件 Transport.send(message); } /** * 发送带内嵌图片、附件、多收件人(显示邮箱姓名)、邮件优先级、阅读回执的完整的HTML邮件 */ @Test public void sendMultipleEmail() throws Exception { String charset = "utf-8"; // 指定中文编码格式 // 创建Session实例对象 Session session = Session.getInstance(props,new MyAuthenticator(from,verification_code)); // 创建MimeMessage实例对象 MimeMessage message = new MimeMessage(session); // 设置主题 message.setSubject("使用JavaMail发送混合组合类型的邮件测试"); // 设置发送人 message.setFrom(new InternetAddress(from,"163测试邮箱",charset)); // 设置收件人 message.setRecipients(RecipientType.TO, new Address[] { // 参数1:邮箱地址,参数2:姓名(在客户端收件只显示姓名,而不显示邮件地址),参数3:姓名中文字符串编码 new InternetAddress("517697206@qq.com", "张三_qq", charset), new InternetAddress("chenjiaren745@163.com", "李四_163", charset), } ); // 设置抄送 //message.setRecipient(RecipientType.CC, new InternetAddress("xyang0917@gmail.com","王五_gmail",charset)); // 设置密送 //message.setRecipient(RecipientType.BCC, new InternetAddress("xyang0917@qq.com", "赵六_QQ", charset)); // 设置发送时间 message.setSentDate(new Date()); // 设置回复人(收件人回复此邮件时,默认收件人) message.setReplyTo(InternetAddress.parse(""" + MimeUtility.encodeText("田七") + "" <chenxingxing745@163.com>")); // 设置优先级(1:紧急 3:普通 5:低) message.setHeader("X-Priority", "1"); // 要求阅读回执(收件人阅读邮件时会提示回复发件人,表明邮件已收到,并已阅读) message.setHeader("Disposition-Notification-To", from); // 创建一个MIME子类型为"mixed"的MimeMultipart对象,表示这是一封混合组合类型的邮件 MimeMultipart mailContent = new MimeMultipart("mixed"); message.setContent(mailContent); // 附件 MimeBodyPart attach1 = new MimeBodyPart(); MimeBodyPart attach2 = new MimeBodyPart(); // 内容 MimeBodyPart mailBody = new MimeBodyPart(); // 将附件和内容添加到邮件当中 mailContent.addBodyPart(attach1); mailContent.addBodyPart(attach2); mailContent.addBodyPart(mailBody); // 附件1(利用jaf框架读取数据源生成邮件体) DataSource ds1 = new FileDataSource("src/loading.gif"); DataHandler dh1 = new DataHandler(ds1); attach1.setFileName(MimeUtility.encodeText("loading.gif")); attach1.setDataHandler(dh1); // 附件2 DataSource ds2 = new FileDataSource("src/车.png"); DataHandler dh2 = new DataHandler(ds2); System.out.println("======================"+dh2.getName()+"===================="); attach2.setDataHandler(dh2); attach2.setFileName(MimeUtility.encodeText(dh2.getName())); // 邮件正文(内嵌图片+html文本) MimeMultipart body = new MimeMultipart("related"); //邮件正文也是一个组合体,需要指明组合关系 mailBody.setContent(body); // 邮件正文由html和图片构成 MimeBodyPart imgPart = new MimeBodyPart(); MimeBodyPart htmlPart = new MimeBodyPart(); body.addBodyPart(imgPart); body.addBodyPart(htmlPart); // 正文图片 DataSource ds3 = new FileDataSource("src/psb.jpg"); DataHandler dh3 = new DataHandler(ds3); imgPart.setDataHandler(dh3); imgPart.setContentID("psb.jpg"); // html邮件内容 MimeMultipart htmlMultipart = new MimeMultipart("alternative"); htmlPart.setContent(htmlMultipart); MimeBodyPart htmlContent = new MimeBodyPart(); htmlContent.setContent( "<span style='color:red'>这是我自己用java mail发送的邮件哦!" + "<img src='cid:psb.jpg' /></span> 复杂邮件" , "text/html;charset=gbk"); htmlMultipart.addBodyPart(htmlContent); // 保存邮件内容修改 message.saveChanges(); // 发送邮件 Transport.send(message); } } /** * 向邮件服务器提交认证信息 */ class MyAuthenticator extends Authenticator { private String username = "chenxingxing745"; private String password = "<span style="line-height: 20.8px; font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;">cx*******29</span>"; public MyAuthenticator() { super(); } public MyAuthenticator(String username, String password) { super(); this.username = username; this.password = password; } @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }
五、邮件接收解析
package cjr.javamail; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Properties; import javax.mail.Address; import javax.mail.BodyPart; import javax.mail.Flags; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Part; import javax.mail.Session; import javax.mail.Store; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; import org.junit.Test; public class ReceiveMail { private static final String PROTOCOL = "pop3"; private static final String USERNAME = "chenjiaren745@163.com"; private static final String LOGINPASS = "<span style="line-height: 20.8px; font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;">cx*******29</span><span style="line-height: 20.8px; font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;">"; </span> private static final String DIR = "D:\mailTemp\"; // 初始化连接邮件服务器的会话信息 private static Properties props = null; static{ props = new Properties(); props.setProperty("mail.store.protocol", "pop3"); // 协议 props.setProperty("mail.pop3.port", "110"); // 端口 props.setProperty("mail.pop3.host", "pop3.163.com"); // pop3服务器 File dir = new File(DIR); System.out.println(!dir.exists()); if(!dir.exists()) dir.mkdirs(); System.out.println(dir.isDirectory()); } @Test public void receive() throws Exception { // 创建Session实例对象 Session session = Session.getInstance(props); Store store = session.getStore(PROTOCOL); store.connect(USERNAME, LOGINPASS); // 获得收件箱 Folder folder = store.getFolder("INBOX"); /* Folder.READ_ONLY:只读权限 * Folder.READ_WRITE:可读可写(可以修改邮件的状态) */ folder.open(Folder.READ_WRITE); //打开收件箱 // 由于POP3协议无法获知邮件的状态,所以getUnreadMessageCount得到的是收件箱的邮件总数 System.out.println("未读邮件数: " + folder.getUnreadMessageCount()); // 由于POP3协议无法获知邮件的状态,所以下面得到的结果始终都是为0 System.out.println("删除邮件数: " + folder.getDeletedMessageCount()); System.out.println("新邮件: " + folder.getNewMessageCount()); // 获得收件箱中的邮件总数 System.out.println("邮件总数: " + folder.getMessageCount()); // 得到收件箱中的所有邮件,并解析 Message[] messages = folder.getMessages(); parseMessage(messages); //释放资源 folder.close(true); store.close(); } /** * 解析邮件 * @param messages 要解析的邮件列表 */ public void parseMessage(Message ...messages) throws MessagingException, IOException { if (messages == null || messages.length < 1) throw new MessagingException("未找到要解析的邮件!"); // 解析所有邮件 for (int i = 0, count = messages.length; i < count; i++) { MimeMessage msg = (MimeMessage) messages[i]; System.out.println("------------------解析第" + msg.getMessageNumber() + "封邮件-------------------- "); System.out.println("主题: " + getSubject(msg)); System.out.println("发件人: " + getFrom(msg)); System.out.println("收件人:" + getReceiveAddress(msg, null)); System.out.println("发送时间:" + getSentDate(msg, null)); System.out.println("是否已读:" + isSeen(msg)); System.out.println("邮件优先级:" + getPriority(msg)); System.out.println("是否需要回执:" + isReplySign(msg)); System.out.println("邮件大小:" + msg.getSize() * 1024 + "kb"); boolean isContainerAttachment = isContainAttachment(msg); System.out.println("是否包含附件:" + isContainerAttachment); if (isContainerAttachment) { saveAttachment(msg, DIR + msg.getSubject() + "_"); //保存附件 } StringBuffer content = new StringBuffer(30); getMailTextContent(msg, content); System.out.println("邮件正文:" + (content.length() > 100 ? content.substring(0,100) + "..." : content)); System.out.println("------------------第" + msg.getMessageNumber() + "封邮件解析结束-------------------- "); System.out.println(); } } /** * 获得邮件主题 * @param msg 邮件内容 * @return 解码后的邮件主题 */ public static String getSubject(MimeMessage msg) throws UnsupportedEncodingException, MessagingException { return MimeUtility.decodeText(msg.getSubject()); } /** * 获得邮件发件人 * @param msg 邮件内容 * @return 姓名 <Email地址> * @throws MessagingException * @throws UnsupportedEncodingException */ public static String getFrom(MimeMessage msg) throws MessagingException, UnsupportedEncodingException { String from = ""; Address[] froms = msg.getFrom(); if (froms.length < 1) throw new MessagingException("没有发件人!"); InternetAddress address = (InternetAddress) froms[0]; String person = address.getPersonal(); if (person != null) { person = MimeUtility.decodeText(person) + " "; } else { person = ""; } from = person + "<" + address.getAddress() + ">"; return from; } /** * 根据收件人类型,获取邮件收件人、抄送和密送地址。如果收件人类型为空,则获得所有的收件人 * <p>Message.RecipientType.TO 收件人</p> * <p>Message.RecipientType.CC 抄送</p> * <p>Message.RecipientType.BCC 密送</p> * @param msg 邮件内容 * @param type 收件人类型 * @return 收件人1 <邮件地址1>, 收件人2 <邮件地址2>, ... * @throws MessagingException */ public static String getReceiveAddress(MimeMessage msg, Message.RecipientType type) throws MessagingException { StringBuffer receiveAddress = new StringBuffer(); Address[] addresss = null; if (type == null) { addresss = msg.getAllRecipients(); } else { addresss = msg.getRecipients(type); } if (addresss == null || addresss.length < 1) throw new MessagingException("没有收件人!"); for (Address address : addresss) { InternetAddress internetAddress = (InternetAddress)address; receiveAddress.append(internetAddress.toUnicodeString()).append(","); } receiveAddress.deleteCharAt(receiveAddress.length()-1); //删除最后一个逗号 return receiveAddress.toString(); } /** * 获得邮件发送时间 * @param msg 邮件内容 * @return yyyy年mm月dd日 星期X HH:mm * @throws MessagingException */ public static String getSentDate(MimeMessage msg, String pattern) throws MessagingException { Date receivedDate = msg.getSentDate(); if (receivedDate == null) return ""; if (pattern == null || "".equals(pattern)) pattern = "yyyy年MM月dd日 E HH:mm "; return new SimpleDateFormat(pattern).format(receivedDate); } /** * 判断邮件中是否包含附件 * @param msg 邮件内容 * @return 邮件中存在附件返回true,不存在返回false * @throws MessagingException * @throws IOException */ public static boolean isContainAttachment(Part part) throws MessagingException, IOException { boolean flag = false; if (part.isMimeType("multipart/*")) { MimeMultipart multipart = (MimeMultipart) part.getContent(); int partCount = multipart.getCount(); for (int i = 0; i < partCount; i++) { BodyPart bodyPart = multipart.getBodyPart(i); String disp = bodyPart.getDisposition(); if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) { flag = true; } else if (bodyPart.isMimeType("multipart/*")) { flag = isContainAttachment(bodyPart); } else { String contentType = bodyPart.getContentType(); if (contentType.indexOf("application") != -1) { flag = true; } if (contentType.indexOf("name") != -1) { flag = true; } } if (flag) break; } } else if (part.isMimeType("message/rfc822")) { flag = isContainAttachment((Part)part.getContent()); } return flag; } /** * 判断邮件是否已读 * @param msg 邮件内容 * @return 如果邮件已读返回true,否则返回false * @throws MessagingException */ public static boolean isSeen(MimeMessage msg) throws MessagingException { return msg.getFlags().contains(Flags.Flag.SEEN); } /** * 判断邮件是否需要阅读回执 * @param msg 邮件内容 * @return 需要回执返回true,否则返回false * @throws MessagingException */ public static boolean isReplySign(MimeMessage msg) throws MessagingException { boolean replySign = false; String[] headers = msg.getHeader("Disposition-Notification-To"); if (headers != null) replySign = true; return replySign; } /** * 获得邮件的优先级 * @param msg 邮件内容 * @return 1(High):紧急 3:普通(Normal) 5:低(Low) * @throws MessagingException */ public String getPriority(MimeMessage msg) throws MessagingException { String priority = "普通"; String[] headers = msg.getHeader("X-Priority"); if (headers != null) { String headerPriority = headers[0]; if (headerPriority.indexOf("1") != -1 || headerPriority.indexOf("High") != -1) priority = "紧急"; else if (headerPriority.indexOf("5") != -1 || headerPriority.indexOf("Low") != -1) priority = "低"; else priority = "普通"; } return priority; } /** * 获得邮件文本内容 * @param part 邮件体 * @param content 存储邮件文本内容的字符串 * @throws MessagingException * @throws IOException */ public void getMailTextContent(Part part, StringBuffer content) throws MessagingException, IOException { //如果是文本类型的附件,通过getContent方法可以取到文本内容,但这不是我们需要的结果,所以在这里要做判断 boolean isContainTextAttach = part.getContentType().indexOf("name") > 0; if (part.isMimeType("text/*") && !isContainTextAttach) { content.append(part.getContent().toString()); } else if (part.isMimeType("message/rfc822")) { getMailTextContent((Part)part.getContent(),content); } else if (part.isMimeType("multipart/*")) { Multipart multipart = (Multipart) part.getContent(); int partCount = multipart.getCount(); for (int i = 0; i < partCount; i++) { BodyPart bodyPart = multipart.getBodyPart(i); getMailTextContent(bodyPart,content); } } } /** * 保存附件 * @param part 邮件中多个组合体中的其中一个组合体 * @param destDir 附件保存目录 * @throws UnsupportedEncodingException * @throws MessagingException * @throws FileNotFoundException * @throws IOException */ public void saveAttachment(Part part, String destDir) throws UnsupportedEncodingException, MessagingException, FileNotFoundException, IOException { if (part.isMimeType("multipart/*")) { Multipart multipart = (Multipart) part.getContent(); //复杂体邮件 //复杂体邮件包含多个邮件体 int partCount = multipart.getCount(); for (int i = 0; i < partCount; i++) { //获得复杂体邮件中其中一个邮件体 BodyPart bodyPart = multipart.getBodyPart(i); //某一个邮件体也有可能是由多个邮件体组成的复杂体 String disp = bodyPart.getDisposition(); if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) { InputStream is = bodyPart.getInputStream(); saveFile(is, destDir, decodeText(bodyPart.getFileName())); } else if (bodyPart.isMimeType("multipart/*")) { saveAttachment(bodyPart,destDir); } else { String contentType = bodyPart.getContentType(); if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) { saveFile(bodyPart.getInputStream(), destDir, decodeText(bodyPart.getFileName())); } } } } else if (part.isMimeType("message/rfc822")) { saveAttachment((Part) part.getContent(),destDir); } } /** * 读取输入流中的数据保存至指定目录 * @param is 输入流 * @param fileName 文件名 * @param destDir 文件存储目录 * @throws FileNotFoundException * @throws IOException */ private void saveFile(InputStream is, String destDir, String fileName) throws FileNotFoundException, IOException { BufferedInputStream bis = new BufferedInputStream(is); BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(new File(destDir + fileName))); int len = -1; while ((len = bis.read()) != -1) { bos.write(len); bos.flush(); } bos.close(); bis.close(); } /** * 文本解码 * @param encodeText 解码MimeUtility.encodeText(String text)方法编码后的文本 * @return 解码后的文本 * @throws UnsupportedEncodingException */ public String decodeText(String encodeText) throws UnsupportedEncodingException { if (encodeText == null || "".equals(encodeText)) { return ""; } else { return MimeUtility.decodeText(encodeText); } } }
注意:
1 getUnreadMessageCount 获取未读邮件数量,getNewMessageCount 获取新邮件数量 获取值和实际值不一致。 目前测试时未读邮件数量等于总邮件数量,新邮件数量等于0 ,实际是有已读邮件,未读邮件, 产生原因待查。