Java实现读取163邮箱,qq邮箱的邮件内容通过使⽤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 at.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.*;
ParseException;
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[]) From();
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 = UpperCase();
if (!addType.equals("TO") && !addType.equals("CC") && !addType.equals("BCC")) {
return "";
}
InternetAddress[] address;
if (addType.equals("TO")) {
address = (InternetAddress[]) Recipients(Message.RecipientType.TO);
} else if (addType.equals("CC")) {
address = (InternetAddress[]) Recipients(Message.RecipientType.CC);
} else {
address = (InternetAddress[]) Recipients(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(">");
}
String().substring(1);
}
/**
* 获得邮件主题
*
* @return
* @throws MessagingException
* @throws UnsupportedEncodingException
*/
public String getSubject() throws MessagingException, UnsupportedEncodingException {
String subject = MimeUtility.Subject());
if (subject == null) {
subject = "";
}
return subject;
}
/**
* 获得邮件发送⽇期
*
* @return
* @throws MessagingException
*/
public String getSentDate() throws MessagingException {
Date sentDate = SentDate();
SimpleDateFormat format = new SimpleDateFormat(NORM_DATETIME_PATTERN);
return format.format(sentDate);
}
/**
* 获得邮件正⽂内容
*
* @return
*/
public String getBodyText() {
String();
}
/**
* 解析邮件,把得到的邮件内容保存到⼀个StringBuffer对象中,解析邮件
* 主要是根据MimeType类型的不同执⾏不同的操作,⼀步⼀步的解析
* @param part
* @throws MessagingException
* @throws IOException
*/
public void getMailContent(Part part) throws MessagingException, IOException {
String contentType = ContentType();
int nameIndex = contentType.indexOf("name");
boolean conName = false;
if (nameIndex != -1) {
conName = true;
}
if (part.isMimeType("text/plain") && conName == false) {
bodyText.append((String) Content());
} else if (part.isMimeType("text/html") && conName == false) {
bodyText.append((String) Content());
} else if (part.isMimeType("multipart/*")) {
Multipart multipart = (Multipart) Content();
int counts = Count();
for (int i = 0; i < counts; i++) {
}
} else if (part.isMimeType("message/rfc822")) {
}
}
/**
* 判断此邮件是否需要回执,如果需要回执返回"true",否则返回"false"
*
* @return
* @throws MessagingException
*/
public boolean getReplySign() throws MessagingException {
boolean replySign = false;
String needReply[] = Header("Disposition-Notification-To");
if (needReply != null) {
replySign = true;
}
return replySign;
}
/**
* 判断此邮件是否已读,如果未读返回false,反之返回true
*
* @return
* @throws MessagingException
*/
public boolean isNew() throws MessagingException {
boolean isNew = false;
Flags flags = Flags();
Flags.Flag[] flag = SystemFlags();
for (int i = 0; i < flag.length; i++) {
if (flag[i] == Flags.Flag.SEEN) {
isNew = true;
}
}
return isNew;
}
/**
* 判断此邮件是否包含附件
*
* @param part
* @return
* @throws MessagingException
* @throws IOException
*/
public boolean isContainAttach(Part part) throws MessagingException, IOException {        boolean attachFlag = false;
if (part.isMimeType("multipart/*")) {
Multipart mp = (Multipart) Content();
BodyPart mPart;
String conType;
for (int i = 0; i < mp.getCount(); i++) {
mPart = mp.getBodyPart(i);
String disposition = Disposition();
if (Part.ATTACHMENT.equals(disposition) || Part.INLINE.equals(disposition)) {
} else if (mPart.isMimeType("multipart/*")) {
attachFlag = this.isContainAttach(mPart);
} else {
conType = ContentType();
if (LowerCase().indexOf("application") != -1 || LowerCase().indexOf("name") != -1){                        attachFlag = true;
}
}
}
} else if (part.isMimeType("message/rfc822")) {
attachFlag = isContainAttach((Part) Content());
}
return attachFlag;
}
/**
* 保存附件
*
* @param part
* @throws MessagingException
* @throws IOException
*/
public void saveAttachMent(Part part) throws MessagingException, IOException {
String fileName;
if (part.isMimeType("multipart/*")) {
Multipart mp = (Multipart) Content();
BodyPart mPart;
for (int i = 0; i < mp.getCount(); i++) {
mPart = mp.getBodyPart(i);
String disposition = Disposition();
if (Part.ATTACHMENT.equals(disposition) || Part.INLINE.equals(disposition)) {
fileName = FileName();
if (null != fileName && LowerCase().indexOf("gb2312") != -1) {
fileName = MimeUtility.decodeText(fileName);
}
this.saveFile(fileName, InputStream());
} else if (mPart.isMimeType("multipart/*")) {
this.saveAttachMent(mPart);
} else {
fileName = FileName();
if ((fileName != null) && (LowerCase().indexOf("GB2312") != -1)) {
fileName = MimeUtility.decodeText(fileName);
this.saveFile(fileName, InputStream());
}
}
}
} else if (part.isMimeType("message/rfc822")) {
this.saveAttachMent((Part) Content());
}
}
/**
* 设置附件存放路径
*
* @param attachPath
*/
public void setAttachPath(String attachPath) {
this.saveAttachPath = attachPath;
}
/**
* 获得附件存放路径
*
* @return
*/
public String getAttachPath() {
return saveAttachPath;
}
/**
* 真正的保存附件到指定⽬录⾥
*
* @param fileName
* @param in
* @throws IOException
*/
private void saveFile(String fileName, InputStream in) throws IOException {
String osName = Property("os.name");
String storeDir = AttachPath();
if (null == osName) {
osName = "";
}
if (LowerCase().indexOf("win") != -1) {
if (ObjectUtils.isEmpty(storeDir))
} else {
storeDir = "/tmp";
getsavefilename}
//        place("=?", "");
//        place("?=", "");
//        fileName = fileName.substring(fileName.length() - 6, fileName.length());
FileOutputStream fos = new FileOutputStream(new File(storeDir + File.separator + fileName));
IOUtils.closeQuietly(fos);
IOUtils.closeQuietly(in);
}
/**
* 获取163邮箱信息
*
* @param host
* @param username
* @param password
* @param protocol
* @return
* @throws MessagingException
*/
public static Message[] getWEMessage(String host, String username, String password, String protocol) throws MessagingException {        //创建属性对象
Properties props = Properties();
props.setProperty("mail.store.protocol", protocol);
//创建会话
Session session = DefaultInstance(props, null);
//存储对象
Store store = Store(protocol);
//连接
//创建⽬录对象
Folder folder = Folder("INBOX");
if (folder instanceof IMAPFolder) {
IMAPFolder imapFolder = (IMAPFolder)folder;
/
/javamail中使⽤id命令有校验checkOpened, 所以要去掉id⽅法中的checkOpened();
imapFolder.doCommand(new IMAPFolder.ProtocolCommand() {
public Object doCommand(IMAPProtocol p) throws com.sun.mail.iap.ProtocolException {
p.id("FUTONG");
return null;
}
});
}
if(folder != null) {
folder.open(Folder.READ_WRITE);
}
Messages();
}
/**
* 获取qq邮箱信息
*
* @param host
* @param username
* @param password
* @param protocol
* @return
* @throws MessagingException
*/
public static Message[] getQQMessage(String host, String username, String password, String protocol) throws MessagingException {        //创建属性对象
Properties props = new Properties();
props.put("mail.store.protocol", protocol);
//创建会话
Session session = DefaultInstance(props, null);
//存储对象
Store store = Store(protocol);
//连接
//创建⽬录对象
Folder folder = Folder("Inbox");
if(folder != null) {
folder.open(Folder.READ_WRITE);
}
Messages();
}
/**
* 过滤邮箱信息
*
* @param messages
* @param fromMail 只读取该邮箱发来的邮件,如果为空则不过滤
* @param startDate 只读取该⽇期以后的邮件,如果为空则不过滤

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。