1,邮箱协议设置
1,邮箱的读取需要先配置邮箱协议,主要有两种,第一个是pop3协议,第二个是imap协议,两者之间的区别在于imap是可以区分邮件是否已读取,而pop可以通过SearchTerm查询条件过滤邮件,关于两者的配置QQ邮箱可以直接点下方QQ官方链接设置,
https://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256
2,腾讯企业邮箱到不需要配置,因为他默认是已经开启了pop3、imap协议的,可以直接通过账号以及密码登录连接的,但是你也可以配置专用密码进行连接,方法如下图
1,开启前

2,开启后

2,java代码实现
1,两者之前的代码实际上都差不多,区别在于邮箱服务器的配置
imap
1,QQ邮箱服务器:imap.qq.com
2,腾讯企业邮箱服务器:imap.exmail.qq.com
pop
1,QQ邮箱服务器:pop.qq.com
2,腾讯企业邮箱服务器:pop.exmail.qq.com
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
package com.example.demo.utils;
import org.apache.commons.lang3.StringUtils;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
public class EmailUtils {
public static void readEmail() {
Properties props = new Properties();
props.put("mail.imap.host", "imap.exmail.qq.com");
props.put("mail.imap.auth", "true");
props.setProperty("mail.store.protocol", "imap");
props.put("mail.imap.starttls.enable", "true");
Session session = Session.getInstance(props);
try {
Store store = session.getStore();
store.connect("imap.exmail.qq.com", "xxx@xx.com", "xxxxx");
Folder folder = store.getFolder("Inbox");
folder.open(Folder.READ_WRITE);
Message[] messages = folder.getMessages(folder.getMessageCount() - folder.getUnreadMessageCount() + 1, folder.getMessageCount());
System.out.println("邮件总数: " + folder.getMessageCount());
parseFileMessage(messages);
folder.setFlags(messages, new Flags(Flags.Flag.SEEN), true);
}catch (Exception e){
System.out.println("异常: " + e);
}
}
public static void readEmailPop() throws Exception {
Properties props = new Properties();
props.put("mail.pop3.host", "pop.exmail.qq.com");
props.put("mail.pop3.auth", "true");
props.setProperty("mail.store.protocol", "pop3");
props.put("mail.pop3.starttls.enable", "true");
Session session = Session.getInstance(props);
Store store = session.getStore("pop3");
store.connect("pop.exmail.qq.com", "xxx@xxx.net", "xxxx");
Folder folder = store.getFolder("Inbox");
folder.open(Folder.READ_WRITE);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Date mondayDate = cal.getTime();
SearchTerm comparisonTermGe = new SentDateTerm(ComparisonTerm.GE, mondayDate);
SearchTerm comparisonTermLe = new SentDateTerm(ComparisonTerm.LE, new Date());
SearchTerm comparisonAndTerm = new AndTerm(comparisonTermGe, comparisonTermLe);
Message[] messages = folder.search(comparisonAndTerm);
System.out.println("读取的邮件总数: " + messages.length);
parseFileMessage(messages);
System.out.println("邮件解析任务执行完毕");
}
public static void parseFileMessage(Message... messages) throws Exception {
if (messages == null || messages.length < 1){
System.out.println("没有可读取邮件");
return;
}
for (Message message : messages) {
MimeMessage msg = (MimeMessage) message;
System.out.println("------------------解析第" + msg.getMessageNumber() + "封邮件-------------------- ");
System.out.println("主题: " + MimeUtility.decodeText(msg.getSubject()));
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");
StringBuffer content = new StringBuffer(30);
getMailTextContent(msg, content);
System.out.println("邮件正文:" + (content.length() > 100 ? content.substring(0,100) + "..." : content));
System.out.println();
boolean isContainerAttachment = isContainAttachment(msg);
System.out.println("是否包含附件:" + isContainerAttachment);
if (isContainerAttachment) {
saveAttachment(msg, "D:\data\emailFile\", msg.getFileName());
}
System.out.println("------------------第" + msg.getMessageNumber() + "封邮件解析结束-------------------- ");
}
}
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;
}
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);
}
public static boolean isSeen(MimeMessage msg) throws MessagingException {
return msg.getFlags().contains(Flags.Flag.SEEN);
}
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;
}
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.contains("1") || headerPriority.contains("High"))
priority = "紧急";
else if (headerPriority.contains("5") || headerPriority.contains("Low"))
priority = "低";
else
priority = "普通";
}
return priority;
}
public static String getReceiveAddress(MimeMessage msg, Message.RecipientType type) throws MessagingException {
StringBuilder receiveAddress = new StringBuilder();
Address[] addresss;
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();
}
public static boolean isContainAttachment(Part part) throws Exception {
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.contains("application")) {
flag = true;
}
if (contentType.contains("name")) {
flag = true;
}
}
if (flag) break;
}
} else if (part.isMimeType("message/rfc822")) {
flag = isContainAttachment((Part) part.getContent());
}
return flag;
}
public static void saveAttachment(Part part, String destDir, String fileName) throws Exception {
if (part.isMimeType("multipart/*")) {
Multipart multipart = (Multipart) part.getContent();
//复杂体邮件包含多个邮件体
int partCount = multipart.getCount();
for (int i = 0; i < partCount; i++
|
阅读:448 次 日期:2021-04-24
|
【 打印 】 【 关闭 】
【 字体:大 中
小 】 |