通过使用java mail来实现读取163邮箱,qq邮箱的邮件内容。
1.代码实现:
创建springboot项目,引入依赖包
<!--mail-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
实现类
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.protocol.IMAPProtocol;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.util.ObjectUtils;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class ShowMail {
public static String NORM_DATETIME_PATTERN = "yyyy-MM-dd hh:mm:ss";
private MimeMessage mimeMessage;
/**
* 附件下载后的存放目录
*/
private String saveAttachPath = "";
/**
* 存放邮件内容的StringBuffer对象
*/
private StringBuffer bodyText = new StringBuffer();
/**
* 构造函数,初始化一个MimeMessage对象
*
* @param mimeMessage
*/
public ShowMail(MimeMessage mimeMessage) {
this.mimeMessage = mimeMessage;
}
/**
* 获得发件人的地址和姓名
*
* @return
* @throws MessagingException
*/
public String getFrom() throws MessagingException {
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;
}
/**
* 获得邮件的收件人,抄送,和密送的地址和姓名,根据所传递的参数的不同
*
* @param type "to"----收件人 "cc"---抄送人地址 "bcc"---密送人地址
* @return
* @throws MessagingException
* @throws UnsupportedEncodingException
*/
public String getMailAddress(String type) throws MessagingException, UnsupportedEncodingException {
if (ObjectUtils.isEmpty(type)) {
return "";
}
String addType = type.toUpperCase();
if (!addType.equals("TO") && !addType.equals("CC") && !addType.equals("BCC")) {
return "";
}
InternetAddress[] address;
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 (ObjectUtils.isEmpty(address)) {
return "";
}
StringBuilder mailAddr = new StringBuilder();
String emailAddr;
String personal;
for (int i = 0; i < address.length; i++) {
emailAddr = address[i].getAddress();
if (emailAddr == null) {
emailAddr = "";
} else {
emailAddr = MimeUtility.decodeText(emailAddr);
}
personal = address[i].getPersonal();
if (personal == null) {
personal = "";
} else {
personal = MimeUtility.decodeText(personal);
}
mailAddr.append(",").append(personal).append("<").append(emailAddr).append(">");
}
return mailAddr.toString().substring(1);
}
/**
* 获得邮件主题
*
* @return
* @throws MessagingException
* @throws Unsupported