直接上代码:
解码收取的邮件
package com.springbootemaildemo.decode; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeUtility; import java.io.*; import java.text.SimpleDateFormat; import java.util.Date; /** * @Description 解码收取的邮件 */ public class DecodeMail { private Logger logger = LoggerFactory.getLogger(this.getClass()); private MimeMessage mimeMessage = null; // 附件下载后的存放目录 private String saveAttachPath = "E:\mail\"; /** * 存放邮件内容的StringBuffer对象 */ private StringBuffer bodyText = new StringBuffer(); private String dateFormat = "yy-MM-dd HH:mm:ss"; public DecodeMail() { } public DecodeMail(MimeMessage mimeMessage) { this.mimeMessage = mimeMessage; } public void setMimeMessage(MimeMessage mimeMessage) { this.mimeMessage = mimeMessage; } /** * 设置附件存放路径 * * @param attachPath */ public void setAttachPath(String attachPath) { this.saveAttachPath = attachPath; } /** * 设置日期显示格式 * * @param format * @throws Exception */ public void setDateFormat(String format) throws Exception { this.dateFormat = format; } /** * 获得附件存放路径 * * @return */ public String getAttachPath() { return saveAttachPath; } /** * * 获得发件人的地址和姓名 */ public String getFrom() throws Exception { InternetAddress address[] = (InternetAddress[]) mimeMessage.getFrom(); String from = address[0].getAddress(); if (from == null) { from = ""; } String personal = address[0].getPersonal(); if (personal == null) { personal = ""; } String fromAddr = null; if (personal != null || from != null) { fromAddr = personal + "<" + from + ">"; } return fromAddr; } /** * 获得邮件的收件人,抄送,和密送的地址和姓名,根据所传递的参数的不同 * "to"----收件人 "cc"---抄送人地址 "bcc"---密送人地址 */ public String getMailAddress(String type) throws Exception { String mailAddr = ""; String addType = type.toUpperCase(); InternetAddress[] address = null; if (addType.equals("TO") || addType.equals("CC") || addType.equals("BCC")) { if (addType.equals("TO")) { address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.TO); } else if (addType.equals("CC")) { address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.CC); } else { address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.BCC); } if (address != null) { for (int i = 0; i < address.length; i++) { String emailAddr = address[i].getAddress(); if (emailAddr == null) { emailAddr = ""; } else { emailAddr = MimeUtility.decodeText(emailAddr); } String personal = address[i].getPersonal(); if (personal == null) { personal = ""; } else { personal = MimeUtility.decodeText(personal); } String compositeto = personal + "<" + emailAddr + ">"; mailAddr += "," + compositeto; } mailAddr = mailAddr.substring(1); } } else { throw new Exception("错误的电子邮件类型!"); } return mailAddr; } /** * * 获得邮件主题 */ public String getSubject() { String subject = ""; try { if (StringUtils.isNotEmpty(mimeMessage.getSubject())) { subject = MimeUtility.decodeText(mimeMessage.getSubject()); } else { subject = ""; } } catch (Exception exce) { logger.error("获取邮件出错.."); exce.printStackTrace(); } return subject; } /** * 获得邮件发送日期 * * @return * @throws Exception */ public String getSentDate() throws Exception { Date sentDate = mimeMessage.getSentDate(); SimpleDateFormat format = new SimpleDateFormat(dateFormat); String strSentDate = format.format(sentDate); return strSentDate; } /** * 获得邮件正文内容 * * @return */ public String getBodyText() { return bodyText.toString(); } /** * 解析邮件,把得到的邮件内容保存到一个StringBuffer对象中,解析邮件 * 主要是根据MimeType类型的不同执行不同的操作,一步一步的解析 * * @param part * @throws Exception */ public void getMailContent(Part part) throws Exception { try { String contentType = part.getContentType(); // 获得邮件的MimeType类型 int nameIndex = contentType.indexOf("name"); boolean conName = false; if (nameIndex != -1) { conName = true; } if (part.isMimeType("text/plain") && conName == false) { bodyText.append((String) part.getContent()); } else if (part.isMimeType("text/html") && conName == false) { String content = (String) part.getContent(); bodyText.append(content); } else if (part.isMimeType("multipart/*")) { Multipart multipart = (Multipart) part.getContent(); int counts = multipart.getCount(); for (int i = 0; i < counts; i++) { getMailContent(multipart.getBodyPart(i)); } } else if (part.isMimeType("message/rfc822")) { getMailContent((Part) part.getContent()); } else { } } catch (Exception e) { logger.error("获取邮件内容出错...:NO Content"); } } /** * 判断此邮件是否需要回执,如果需要回执返回"true",否则返回"false" * * @return * @throws MessagingException */ public boolean getReplySign() throws MessagingException { boolean replySign = false; String needReply[] = mimeMessage.getHeader("Disposition-Notification-To"); if (needReply != null) { replySign = true; } if (replySign) { } else { } return replySign; } /** * 获得此邮件的Message-ID * * @return * @throws MessagingException */ public String getMessageId() throws MessagingException { String messageID = mimeMessage.getMessageID(); return messageID; } /** * 判断此邮件是否已读,如果未读返回false,反之返回true * * @return * @throws MessagingException */ public boolean isNew() throws MessagingException { boolean isNew = false; Flags flags = ((Message) mimeMessage).getFlags(); Flags.Flag[] flag = flags.getSystemFlags(); for (int i = 0; i < flag.length; i++) { if (flag[i] == Flags.Flag.SEEN) { isNew = true; // break; } } return isNew; } /** * 判断此邮件是否包含附件 * * @param part * @return * @throws Exception */ public boolean isContainAttach(Part part) throws Exception { boolean attachFlag = false; // String contentType = part.getContentType(); if (part.isMimeType("multipart/*")) { Multipart mp = (Multipart) part.getContent(); for (int i = 0; i < mp.getCount(); i++) { BodyPart mPart = mp.getBodyPart(i); String disposition = mPart.getDisposition(); if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT)) || (disposition.equals(Part.INLINE)))) attachFlag = true; else if (mPart.isMimeType("multipart/*")) { attachFlag = isContainAttach(mPart); } else { String conType = mPart.getContentType(); if (conType.toLowerCase().indexOf("application") != -1) attachFlag = true; if (conType.toLowerCase().indexOf("name") != -1) attachFlag = true; } } } else if (part.isMimeType("message/rfc822")) { attachFlag = isContainAttach((Part) part.getContent()); } return attachFlag; } /** * 保存附件 * * @param part * @throws Exception */ public void saveAttachMent(Part part) throws Exception { String fileName; logger.info(part.isMimeType("multipart/*") + ""); if (part.isMimeType("multipart/*")) { Multipart mp = (Multipart) part.getContent(); for (int i = 0; i < mp.getCount(); i++) { BodyPart mPart = mp.getBodyPart(i); String disposition = mPart.getDisposition(); if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT)) || (disposition.equals(Part.INLINE)))) { fileName = mPart.getFileName(); if (null != fileName) { fileName = MimeUtility.decodeText(fileName); saveFile(fileName, mPart.getInputStream()); } } else if (mPart.isMimeType("multipart/*")) { saveAttachMent(mPart); } else { fileName = mPart.getFileName(); if (null != fileName) { fileName = MimeUtility.decodeText(fileName); saveFile(fileName, mPart.getInputStream()); } } } } else if (part.isMimeType("message/rfc822")) { saveAttachMent((Part) part.getContent()); } } /** * 获取附件信息 * * @param part * @throws Exception */ public String getAttachMent(Part part) throws Exception { String fileName = null; logger.info(part.isMimeType("multipart/*") + ""); if (part.isMimeType("multipart/*")) { Multipart mp = (Multipart) part.getContent(); for (int i = 0; i < mp.getCount(); i++) { BodyPart mPart = mp.getBodyPart(i); String disposition = mPart.getDisposition(); if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT)) || (disposition.equals(Part.INLINE)))) { fileName = mPart.getFileName(); if (null != fileName) { fileName = MimeUtility.decodeText(fileName); saveFile(fileName, mPart.getInputStream()); } } else if (mPart.isMimeType("multipart/*")) { saveAttachMent(mPart); } else { fileName = mPart.getFileName(); if (null != fileName) { fileName = MimeUtility.decodeText(fileName); saveFile(fileName, mPart.getInputStream()); } } } } else if (part.isMimeType("message/rfc822")) { saveAttachMent((Part) part.getContent()); } return fileName; } /** * 真正的保存附件到指定目录里 * * @param fileName * @param in * @throws Exception */ private void saveFile(String fileName, InputStream in) throws Exception { String osName = System.getProperty("os.name"); String storeDir = getAttachPath(); String separator = ""; if (osName == null) { osName = ""; } if (osName.toLowerCase().indexOf("win") != -1) { separator = "\"; if (storeDir == null || storeDir.equals("")) storeDir = "E:\mail"; } else { separator = "/"; storeDir = "/mail"; } File storeFile = new File(storeDir + separator + fileName); logger.info("附件的保存地址: " + storeFile.toString()); // for(int i=0;storefile.exists();i++){ // storefile = new File(storedir+separator+fileName+i); // } BufferedOutputStream bos = null; BufferedInputStream bis = null; try { // 注:写入本地文件很慢,待解决 bos = new BufferedOutputStream(new FileOutputStream(storeFile)); bis = new BufferedInputStream(in); int c; while ((c = bis.read()) != -1) { bos.write(c); bos.flush(); } } catch (Exception exception) { exception.printStackTrace(); logger.error("保存附件失败..."); } finally { bos.close(); bis.close(); } } }
获取邮箱中邮件信息
package com.springbootemaildemo.decode; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; /** * @Description 用于获取邮箱中邮件信息 */ @Component public class MailThread { private Logger logger = LoggerFactory.getLogger(this.getClass()); DecodeMail re = null; public void run(Message message[]) { if (null != message) { for (int i = 0; i < message.length; i++) { try { re = new DecodeMail((MimeMessage) message[i]); logger.info("邮件 " + i + " 主题: " + re.getSubject()); logger.info("邮件 " + i + " 是否需要回复: " + re.getReplySign()); logger.info("邮件 " + i + " 是否已读: " + re.isNew()); logger.info("邮件 " + i + " 是否包含附件: " + re.isContainAttach(message[i])); logger.info("邮件" + i + "附件信息:" + re.getAttachMent(message[i])); logger.info("邮件 " + i + " 发送时间: " + re.getSentDate()); logger.info("邮件 " + i + " 发送人地址: " + re.getFrom()); logger.info("邮件 " + i + " 收信人地址: " + re.getMailAddress("to")); logger.info("邮件 " + i + " 抄送: " + re.getMailAddress("cc")); logger.info("邮件 " + i + " 暗抄: " + re.getMailAddress("bcc")); re.setDateFormat("yyyy年MM月dd日"); logger.info("邮件 " + i + " 发送时间: " + re.getSentDate()); logger.info("邮件 " + i + " 邮件ID: " + re.getMessageId()); re.getMailContent(message[i]); String bodyText = re.getBodyText(); logger.info("邮件 " + i + " 正文内容: " + bodyText); Document doc = Jsoup.parse(bodyText); String text = doc.text(); logger.info("邮件 " + i + " 处理后正文内容: " + text); logger.info("保存附件..."); re.saveAttachMent(message[i]); } catch (MessagingException e) { logger.error("获取邮件内容出错..."); e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } } }
链接邮件服务器,过滤邮件,读取邮件
package com.springbootemaildemo.decode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.mail.*; import javax.mail.search.FlagTerm; import javax.mail.search.IntegerComparisonTerm; import javax.mail.search.SearchTerm; import javax.mail.search.SizeTerm; import java.util.Properties; /** * @Description 链接邮件服务器,过滤邮件,读取邮件 */ @Component public class MailMain { private static Logger logger = LoggerFactory.getLogger(MailMain.class); @Autowired MailThread mailThread; public void run() { try { String imapServer = "imap.qq.com"; String protocol = "imap";
//读取qq邮箱收到的邮件,这里是你自己的qq邮箱账号 String username = "xxxxx@qq.com"; //如果你用qq或163邮箱,这里授权码不是你登录的密码 //如果你是企业邮箱,就看你们的公司了 String password = "ipeiquufachheefg"; Properties p = new Properties(); p.setProperty("mail.transport.protocol", protocol); p.setProperty("mail.smtp.host", imapServer); Session session = Session.getDefaultInstance(p, null); Store store = session.getStore(protocol); store.connect(imapServer, username, password); Folder folder = store.getFolder("INBOX"); FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), true); //如果需要在取得邮件数后将邮件置为已读则这里需要使用READ_WRITE,否则READ_ONLY就可以 folder.open(Folder.READ_ONLY); Message message[] = folder.search(ft); logger.info("邮件数量: " + message.length); mailThread.run(message); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } } }
定时任务
package com.springbootemaildemo.decode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component @EnableScheduling public class MailTask { private static final Logger logger = LoggerFactory.getLogger(MailTask.class); @Autowired MailMain mailMain; //直接指定时间间隔,例如:100秒 @Scheduled(fixedRate = 100000) public void sendJob() { logger.info("定时任务开始.........................."); mailMain.run(); logger.info("定时任务结束.........................."); } }
Main方法:
package com.springbootemaildemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * 引入了一个注解@EnableSwagger2来启动swagger注解。 * (启动该注解使得用在controller中的swagger注解生效,覆盖的范围由@ComponentScan的配置来指定,
* 这里默认指定为根路径”com.springboot”下的所有controller) * 也可以单独写swaggerConfigura */ @EnableScheduling //启动定时任务 @EnableSwagger2 //启动swagger注解 @SpringBootApplication public class MailApplication { public static void main(String[] args) { SpringApplication.run(MailApplication.class, args); } }