JMail收取邮件
import org.apache.commons.lang3.StringUtils;
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.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
public class CheckEmail {
private MimeMessage mimeMessage = null;
private String saveAttachPath = "";
private StringBuffer bodytext = new StringBuffer();
private String dateformat = "yyyy-MM-dd HH:mm";
public static void main(String args[]) throws Exception {
String host = "pop.exmail.qq.com";
String port = "110";
String email = "****@bis.com.cn";
String emailPWD = "*******";
Message message[] = CheckEmail.checkEmail(host, port, email, emailPWD);
System.out.println("Messages's length: " + message.length);
CheckEmail ce;
for (int i = 0; i < message.length; i++) {
System.out.println("--------------------------------------------------------");
ce = new CheckEmail((MimeMessage) message[i]);
if (ce.isNew()) {
continue;
} else {
System.out.println("Message " + i + " 邮件主题: " + ce.getSubject());
System.out.println("Message " + i + " 邮件发送日期: " + ce.getSentDate());
System.out.println("Message " + i + " 是否需要回执: " + ce.getReplySign());
System.out.println("Message " + i + " 是否包含附件: " + ce.isContainAttach(message[i]));
System.out.println("Message " + i + " 发件人: " + ce.getFrom());
System.out.println("Message " + i + " 收件人: " + ce.getMailAddress("to"));
System.out.println("Message " + i + " 抄送: " + ce.getMailAddress("cc"));
System.out.println("Message " + i + " 密送: " + ce.getMailAddress("bcc"));
System.out.println("Message " + i + " Message-ID: " + ce.getMessageId());
System.out.println("Message " + i + " MessageNumber: " + message[i].getMessageNumber());
}
}
}
public static Message[] checkEmail(String host, String port, String email, String emailPWD) throws MessagingException {
Properties props = new Properties();
props.setProperty("mail.store.protocol", "pop3");
props.setProperty("mail.pop3.port", port);
props.setProperty("mail.pop3.host", host);
Session session = Session.getInstance(props);
Store store = session.getStore("pop3");
store.connect(email, emailPWD);
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
System.setProperty("mail.mime.multipart.ignoreexistingboundaryparameter", "true");
System.out.println("-----getUnreadMessageCount----" + folder.getMessageCount());
Message message[] = folder.getMessages();
return message;
}
public CheckEmail(MimeMessage mimeMessage) {
this.mimeMessage = mimeMessage;
}
public void setAttachPath(String attachpath) {
this.saveAttachPath = attachpath;
}
public void setDateFormat(String format) {
this.dateformat = format;
}
public String getAttachPath() {
return saveAttachPath;
}
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 = personal + "<" + from + ">";
return fromaddr;
}
private InternetAddress[] getAddress(String[] num) {
InternetAddress[] address;
List<InternetAddress> addresses = new ArrayList<InternetAddress>();
for (String s : num) {
String[] to2 = s.split(",");
for (String s2 : to2) {
InternetAddress internetAddress = new InternetAddress();
String[] mail = s2.split("<");
if (StringUtils.isNotBlank(mail[0])) {
try {
internetAddress.setPersonal(mail[0]);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
try {
internetAddress.setPersonal("");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
internetAddress.setAddress(mail[1]);
addresses.add(internetAddress);
}
}
InternetAddress[] ia = new InternetAddress[addresses.size()];
address = addresses.toArray(ia);
return address;
}
public String getMailAddress(String type) throws Exception {
StringBuilder mailaddr = new StringBuilder();
String addtype = type.toUpperCase();
InternetAddress[] address;
if (addtype.equals("TO") || addtype.equals("CC") || addtype.equals("BCC")) {
if (addtype.equals("TO")) {
try {
address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.TO);
} catch (MessagingException e) {
String[] to = mimeMessage.getHeader(Message.RecipientType.TO.toString());
address = getAddress(to);
}
} else if (addtype.equals("CC")) {
try {
address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.CC);
} catch (MessagingException e) {
String[] cc = mimeMessage.getHeader(Message.RecipientType.CC.toString());
address = getAddress(cc);
}
} else {
try {
address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.BCC);
} catch (MessagingException e) {
String[] bcc = mimeMessage.getHeader(Message.RecipientType.BCC.toString());
address = getAddress(bcc);
}
}
if (address != null) {
for (int i = 0; i < address.length; i++) {
String email = address[i].getAddress();
if (email == null)
email = "";
else {
email = MimeUtility.decodeText(email).replaceAll(">>", "").replaceAll(">", "").replaceAll("\r\n\t", "").trim();
}
String personal = address[i].getPersonal();
if (personal == null)
personal = "";
else {
personal = MimeUtility.decodeText(personal).replaceAll("'", "").replaceAll("'", "").replaceAll("\"", "").trim();
}
String compositeto = personal + "<" + email + ">";
mailaddr.append(",").append(compositeto);
}
mailaddr = new StringBuilder(mailaddr.substring(1));
}
} else {
throw new Exception("getMailAddress 没有此类型收件人!");
}
return mailaddr.toString();
}
public String getSubject() throws MessagingException, UnsupportedEncodingException {
String subject = MimeUtility.decodeText(mimeMessage.getSubject());
return subject == null ? "" : subject;
}
public String getSentDate() throws MessagingException {
Date sentdate = mimeMessage.getSentDate();
SimpleDateFormat format = new SimpleDateFormat(dateformat);
return format.format(sentdate);
}
public String getBodyText() {
return bodytext.toString();
}
public void getMailContent(Part part) throws Exception {
String contenttype = part.getContentType();
int nameindex = contenttype.indexOf("name");
boolean conname = false;
if (nameindex != -1)
conname = true;
System.out.println("--getMailContent--ContentType: " + contenttype);
if (part.isMimeType("text/plain") && !conname) {
bodytext.append((String) part.getContent());
} else if (part.isMimeType("text/html") && !conname) {
bodytext.append((String) part.getContent());
} 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());
}
}
/**
* 判断此邮件是否需要回执,如果需要回执返回"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;
}
return replysign;
}
public String getMessageId() throws MessagingException {
return mimeMessage.getMessageID();
}
public boolean isNew() throws MessagingException {
boolean isnew = false;
Flags flags = (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;
}
public boolean isContainAttach(Part part) throws Exception {
boolean attachflag = false;
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;
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 (fileName == null) continue;
// if (fileName.toLowerCase().indexOf("gb2312") != -1) {
fileName = MimeUtility.decodeText(fileName);
// }
saveFile(fileName, mpart.getInputStream());
} else if (mpart.isMimeType("multipart/*")) {
saveAttachMent(mpart);
} else {
fileName = mpart.getFileName();
if ((fileName != null)
&& ((fileName.toLowerCase().indexOf("GB2312") != -1) || (fileName.toLowerCase().indexOf("gb18030") != -1))) {
fileName = MimeUtility.decodeText(fileName);
saveFile(fileName, mpart.getInputStream());
}
}
}
} else if (part.isMimeType("message/rfc822")) {
saveAttachMent((Part) part.getContent());
}
}
/**
* 真正的保存附件到指定目录里
*
* @param fileName 文件名
* @param in 附件InputStream对象
* @throws Exception 附件保存错误
*/
private void saveFile(String fileName, InputStream in) throws Exception {
String osName = System.getProperty("os.name");
String storedir = getAttachPath();
if (osName == null)
osName = "";
if (osName.toLowerCase().contains("win")) {
if (storedir == null || storedir.equals(""))
storedir = "d:\\tmp";
} else {
storedir = "/tmp";
}
File storefile = new File(storedir + System.getProperty("file.separator") + fileName);
System.out.println("--saveFile--附件保存路径: " + storefile.toString());
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();
throw new Exception("文件保存失败!");
} finally {
assert bos != null;
bos.close();
assert bis != null;
bis.close();
}
}
}