一、第一种 使用SMTP协议发送电子邮件
第一步:加入mail.jar包
(1)简单类型
package com.souvc.mail;import java.util.Date;import java.util.Properties;import java.util.UUID;import javax.mail.Message;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;/** * souvc.com */public class SendMail { private static SendMail instance = null; private SendMail() { } public static SendMail getInstance() { if (instance == null) { instance = new SendMail(); } return instance; } public void send() { try { // 接收者的邮箱 String to[] = { "XX@qq.com" }; // 配置发送邮箱的配置-- Properties p = new Properties(); p.put("mail.smtp.auth", "true"); p.put("mail.transport.protocol", "smtp"); p.put("mail.smtp.host", "smtp.163.com"); p.put("mail.smtp.port", "25"); // 建立会话 Session session = Session.getInstance(p); // 建立信息 Message msg = new MimeMessage(session); // 发件人 msg.setFrom(new InternetAddress("XX@163.com")); // 收件人 String toList = getMailList(to); InternetAddress[] iaToList = new InternetAddress().parse(toList); msg.setRecipients(Message.RecipientType.TO, iaToList); // 发送日期 msg.setSentDate(new Date()); // 主题 msg.setSubject("测试邮件"); // 内容 msg.setText("注意,这是测试程序发的,请不要回复!"); // 邮件服务器进行验证 Transport tran = session.getTransport("smtp"); // *配置发送者的邮箱账户名和密码 tran.connect("smtp.163.com", "XX@163.com", "mima"); // 发送 tran.sendMessage(msg, msg.getAllRecipients()); System.out.println("邮件发送成功"); } catch (Exception e) { e.printStackTrace(); } } private String getMailList(String[] mailArray) { StringBuffer toList = new StringBuffer(); int length = mailArray.length; if (mailArray != null && length < 2) { toList.append(mailArray[0]); } else { for (int i = 0; i < length; i++) { toList.append(mailArray[i]); if (i != (length - 1)) { toList.append(","); } } } return toList.toString(); } public static void main(String[] args) { SendMail sendMail = SendMail.getInstance(); sendMail.send(); // System.out.println(System.nanoTime()); // UUID uuid = UUID.randomUUID(); // System.out.println(uuid); }}
修改其中的配置文件。
邮箱配置,用户名和密码的配置等等。
邮件源码下载:http://yunpan.cn/cwr2xAhNd28ZF 访问密码 879e
(2)复合类型
package com.souvc.controller;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;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;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;/** * 使用SMTP协议发送电子邮件 */public class SendMailTest { // 邮件发送协议 private final static String PROTOCOL = "smtp"; // SMTP邮件服务器 private final static String HOST = "smtp.sina.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 = "XXX@sina.com"; // 收件人 private static String to = "XXX@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); } public static void main(String[] args) throws Exception { // 发送文本邮件 sendTextEmail(); // 发送简单的html邮件 sendHtmlEmail(); // 发送带内嵌图片的HTML邮件 sendHtmlWithInnerImageEmail(); // 发送混合组合邮件 sendMultipleEmail(); // 发送已经生成的eml邮件 //sendMailForEml(); } /** * 发送简单的文本邮件 */ public static 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(null,"xyang0917", "123456abc"); // 将message对象传递给transport对象,将邮件发送出去 transport.sendMessage(message, message.getAllRecipients()); // 关闭连接 transport.close(); } /** * 发送简单的html邮件 */ public static void sendHtmlEmail() throws Exception { // 创建Session实例对象 Session session = Session.getInstance(props, new MyAuthenticator()); // 创建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("html邮件测试...","text/html;charset=gbk"); // 保存并生成最终的邮件内容 message.saveChanges(); // 发送邮件 Transport.send(message); } /** * 发送带内嵌图片的HTML邮件 */ public static void sendHtmlWithInnerImageEmail() throws MessagingException { // 创建Session实例对象 Session session = Session.getDefaultInstance(props, new MyAuthenticator()); // 创建邮件内容 MimeMessage message = new MimeMessage(session); // 邮件主题,并指定编码格式 message.setSubject("带内嵌图片的HTML邮件", "utf-8"); // 发件人 message.setFrom(new InternetAddress(from)); // 收件人 message.setRecipients(RecipientType.TO, InternetAddress.parse(to)); // 抄送 message.setRecipient(RecipientType.CC, new InternetAddress("java_test@sohu.com")); // 密送 (不会在邮件收件人名单中显示出来) message.setRecipient(RecipientType.BCC, new InternetAddress("417067629@qq.com")); // 发送时间 message.setSentDate(new Date()); // 创建一个MIME子类型为“related”的MimeMultipart对象 MimeMultipart mp = new MimeMultipart("related"); // 创建一个表示正文的MimeBodyPart对象,并将它加入到前面创建的MimeMultipart对象中 MimeBodyPart htmlPart = new MimeBodyPart(); mp.addBodyPart(htmlPart); // 创建一个表示图片资源的MimeBodyPart对象,将将它加入到前面创建的MimeMultipart对象中 MimeBodyPart imagePart = new MimeBodyPart(); mp.addBodyPart(imagePart); // 将MimeMultipart对象设置为整个邮件的内容 message.setContent(mp); // 设置内嵌图片邮件体 DataSource ds = new FileDataSource(new File("resource/firefoxlogo.png")); DataHandler dh = new DataHandler(ds); imagePart.setDataHandler(dh); imagePart.setContentID("firefoxlogo.png"); // 设置内容编号,用于其它邮件体引用 // 创建一个MIME子类型为"alternative"的MimeMultipart对象,并作为前面创建的htmlPart对象的邮件内容 MimeMultipart htmlMultipart = new MimeMultipart("alternative"); // 创建一个表示html正文的MimeBodyPart对象 MimeBodyPart htmlBodypart = new MimeBodyPart(); // 其中cid=androidlogo.gif是引用邮件内部的图片,即imagePart.setContentID("androidlogo.gif");方法所保存的图片 htmlBodypart.setContent("这是带内嵌图片的HTML邮件哦!!!","text/html;charset=utf-8"); htmlMultipart.addBodyPart(htmlBodypart); htmlPart.setContent(htmlMultipart); // 保存并生成最终的邮件内容 message.saveChanges(); // 发送邮件 Transport.send(message); } /** * 发送带内嵌图片、附件、多收件人(显示邮箱姓名)、邮件优先级、阅读回执的完整的HTML邮件 */ public static void sendMultipleEmail() throws Exception { String charset = "utf-8"; // 指定中文编码格式 // 创建Session实例对象 Session session = Session.getInstance(props,new MyAuthenticator()); // 创建MimeMessage实例对象 MimeMessage message = new MimeMessage(session); // 设置主题 message.setSubject("使用JavaMail发送混合组合类型的邮件测试"); // 设置发送人 message.setFrom(new InternetAddress(from,"新浪测试邮箱",charset)); // 设置收件人 message.setRecipients(RecipientType.TO, new Address[] { // 参数1:邮箱地址,参数2:姓名(在客户端收件只显示姓名,而不显示邮件地址),参数3:姓名中文字符串编码 new InternetAddress("java_test@sohu.com", "张三_sohu", charset), new InternetAddress("xyang0917@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("田七") + "\" <417067629@qq.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("resource/Earth.bmp"); DataHandler dh1 = new DataHandler(ds1); attach1.setFileName(MimeUtility.encodeText("Earth.bmp")); attach1.setDataHandler(dh1); // 附件2 DataSource ds2 = new FileDataSource("resource/如何学好C语言.txt"); DataHandler dh2 = new DataHandler(ds2); attach2.setDataHandler(dh2); attach2.setFileName(MimeUtility.encodeText("如何学好C语言.txt")); // 邮件正文(内嵌图片+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("resource/firefoxlogo.png"); DataHandler dh3 = new DataHandler(ds3); imgPart.setDataHandler(dh3); imgPart.setContentID("firefoxlogo.png"); // html邮件内容 MimeMultipart htmlMultipart = new MimeMultipart("alternative"); htmlPart.setContent(htmlMultipart); MimeBodyPart htmlContent = new MimeBodyPart(); htmlContent.setContent( "这是我自己用java mail发送的邮件哦!" + "" , "text/html;charset=gbk"); htmlMultipart.addBodyPart(htmlContent); // 保存邮件内容修改 message.saveChanges(); /*File eml = buildEmlFile(message); sendMailForEml(eml);*/ // 发送邮件 Transport.send(message); } /** * 将邮件内容生成eml文件 * @param message 邮件内容 */ public static File buildEmlFile(Message message) throws MessagingException, FileNotFoundException, IOException { File file = new File("c:\\" + MimeUtility.decodeText(message.getSubject())+".eml"); message.writeTo(new FileOutputStream(file)); return file; } /** * 发送本地已经生成好的email文件 */ public static void sendMailForEml(File eml) throws Exception { // 获得邮件会话 Session session = Session.getInstance(props,new MyAuthenticator()); // 获得邮件内容,即发生前生成的eml文件 InputStream is = new FileInputStream(eml); MimeMessage message = new MimeMessage(session,is); //发送邮件 Transport.send(message); } /** * 向邮件服务器提交认证信息 */ static class MyAuthenticator extends Authenticator { private String username = "xyang0917"; private String password = "123456abc"; 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); } }}
第二种:使用POP3协议接收并解析电子邮件(全)
package com.souvc.controller;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;/** * 使用POP3协议接收邮件 */public class POP3ReceiveMailTest { public static void main(String[] args) throws Exception { receive(); } /** * 接收邮件 */ public static void receive() throws Exception { // 准备连接服务器的会话信息 Properties props = new Properties(); props.setProperty("mail.store.protocol", "pop3"); // 协议 props.setProperty("mail.pop3.port", "110"); // 端口 props.setProperty("mail.pop3.host", "pop3.163.com"); // pop3服务器 // 创建Session实例对象 Session session = Session.getInstance(props); Store store = session.getStore("pop3"); store.connect(null,"XXXX@163.com", "XXXXX"); // 获得收件箱 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 static 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, "c:\\mailtmp\\"+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 姓名* @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; } /** * 根据收件人类型,获取邮件收件人、抄送和密送地址。如果收件人类型为空,则获得所有的收件人 * Message.RecipientType.TO 收件人
*Message.RecipientType.CC 抄送
*Message.RecipientType.BCC 密送
* @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 static 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 static 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 static 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 static 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 static String decodeText(String encodeText) throws UnsupportedEncodingException { if (encodeText == null || "".equals(encodeText)) { return ""; } else { return MimeUtility.decodeText(encodeText); } }} 邮件地址2> 邮件地址1>
注意修改为自己的账号和密码。
第三种:使用IMAP协议接收并解析电子邮件
package com.souvc.controller;import java.io.BufferedReader;import java.io.InputStreamReader;import java.util.Properties;import javax.mail.Flags.Flag;import javax.mail.Folder;import javax.mail.Message;import javax.mail.Session;import javax.mail.Store;import javax.mail.internet.MimeUtility;import com.sun.mail.imap.IMAPMessage;/** * 使用IMAP协议接收邮件 *POP3和IMAP协议的区别:
* POP3协议允许电子邮件客户端下载服务器上的邮件,但是在客户端的操作(如移动邮件、标记已读等),不会反馈到服务器上, * 比如通过客户端收取了邮箱中的3封邮件并移动到其它文件夹,邮箱服务器上的这些邮件是没有同时被移动的。 *IMAP协议提供webmail与电子邮件客户端之间的双向通信,客户端的操作都会同步反应到服务器上,对邮件进行的操作,服务 * 上的邮件也会做相应的动作。比如在客户端收取了邮箱中的3封邮件,并将其中一封标记为已读,将另外两封标记为删除,这些操作会 * 即时反馈到服务器上。
*两种协议相比,IMAP 整体上为用户带来更为便捷和可靠的体验。POP3更易丢失邮件或多次下载相同的邮件,但IMAP通过邮件客户端 * 与webmail之间的双向同步功能很好地避免了这些问题。
*/public class IMAPReceiveMailTest { public static void main(String[] args) throws Exception { // 准备连接服务器的会话信息 Properties props = new Properties(); props.setProperty("mail.store.protocol", "imap"); props.setProperty("mail.imap.host", "imap.163.com"); props.setProperty("mail.imap.port", "143"); // 创建Session实例对象 Session session = Session.getInstance(props); // 创建IMAP协议的Store对象 Store store = session.getStore("imap"); // 连接邮件服务器 store.connect(null,"XXX@163.com", "xxxx"); // 获得收件箱 Folder folder = store.getFolder("INBOX"); // 以读写模式打开收件箱 folder.open(Folder.READ_WRITE); // 获得收件箱的邮件列表 Message[] messages = folder.getMessages(); // 打印不同状态的邮件数量 System.out.println("收件箱中共" + messages.length + "封邮件!"); System.out.println("收件箱中共" + folder.getUnreadMessageCount() + "封未读邮件!"); System.out.println("收件箱中共" + folder.getNewMessageCount() + "封新邮件!"); System.out.println("收件箱中共" + folder.getDeletedMessageCount() + "封已删除邮件!"); System.out.println("------------------------开始解析邮件----------------------------------"); // 解析邮件 for (Message message : messages) { IMAPMessage msg = (IMAPMessage) message; String subject = MimeUtility.decodeText(msg.getSubject()); System.out.println("[" + subject + "]未读,是否需要阅读此邮件(yes/no)?"); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String answer = reader.readLine(); if ("yes".equalsIgnoreCase(answer)) { POP3ReceiveMailTest.parseMessage(msg); // 解析邮件 // 第二个参数如果设置为true,则将修改反馈给服务器。false则不反馈给服务器 msg.setFlag(Flag.SEEN, true); //设置已读标志 } } // 关闭资源 folder.close(false); store.close(); }}
其他参考: