javaMail实现收发邮件2(完善版,此版本已投入客户使用)

package com.skysz.app.km.audit.utils;

 

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.UnsupportedEncodingException;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Properties;

 

import javax.mail.BodyPart;

import javax.mail.Flags;

import javax.mail.Folder;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.Multipart;

import javax.mail.Part;

import javax.mail.Session;

import javax.mail.Store;

import javax.mail.URLName;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeUtility;

 

import org.apache.log4j.Logger;

 

import com.skysz.framework.exception.ExceptionUtils;

import com.skysz.framework.file.FileUtils;

import com.skysz.framework.utils.StringUtils;

import com.sun.mail.pop3.POP3Message;

 

public class EmailUtils {

protected final Logger log = Logger.getLogger(getClass());

private MimeMessage msg = null;

private String saveAttchPath = "C:\\temp\\";

private StringBuffer bodytext = new StringBuffer();

private String dateformate = "yyyy-MM-dd";

 

public EmailUtils(MimeMessage msg) {

this.msg = msg;

}

 

public void setMsg(MimeMessage msg) {

this.msg = msg;

}

 

public EmailUtils() {

 

}

 

/**

* 获取发送邮件者信息

* @return

* @throws MessagingException

*/

public String getFrom() throws MessagingException {

InternetAddress[] address = (InternetAddress[]) msg.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;

}

 

/**

* 获取邮件收件人,抄送,密送的地址和信息。根据所传递的参数不同 "to"-->收件人,"cc"-->抄送人地址,"bcc"-->密送地址

* @param type

* @return

* @throws MessagingException

* @throws UnsupportedEncodingException

*/

public String getMailAddress(String type) throws MessagingException,

UnsupportedEncodingException {

String mailaddr = "";

String addrType = type.toUpperCase();

InternetAddress[] address = null;

 

if (addrType.equals("TO") || addrType.equals("CC")

|| addrType.equals("BCC")) {

if (addrType.equals("TO")) {

address = (InternetAddress[]) msg

.getRecipients(Message.RecipientType.TO);

}

if (addrType.equals("CC")) {

address = (InternetAddress[]) msg

.getRecipients(Message.RecipientType.CC);

}

if (addrType.equals("BCC")) {

address = (InternetAddress[]) msg

.getRecipients(Message.RecipientType.BCC);

}

 

if (address != null) {

for (int i = 0; i < address.length; i++) {

String mail = address[i].getAddress();

if (mail == null) {

mail = "";

} else {

mail = MimeUtility.decodeText(mail);

}

String personal = address[i].getPersonal();

if (personal == null) {

personal = "";

} else {

personal = MimeUtility.decodeText(personal);

}

String compositeto = personal + "<" + mail + ">";

mailaddr += "," + compositeto;

}

mailaddr = mailaddr.substring(1);

}

} else {

throw new RuntimeException("Error email Type!");

}

return mailaddr;

}

 

/**

* 获取邮件主题

* @return

* @throws UnsupportedEncodingException

* @throws MessagingException

*/

public String getSubject() throws UnsupportedEncodingException,

MessagingException {

String subject = "";

subject = MimeUtility.decodeText(msg.getSubject());

if (subject == null) {

subject = "";

}

return subject;

}

 

/**

* 获取邮件发送日期

* @return

* @throws MessagingException

*/

public String getSendDate() throws MessagingException {

Date sendDate = msg.getSentDate();

SimpleDateFormat smd = new SimpleDateFormat(dateformate);

return smd.format(sendDate);

}

 

/**

* 获取邮件正文内容

* @return

*/

public String getBodyText() {

 

return bodytext.toString();

}

 

/**

* 解析邮件,将得到的邮件内容保存到一个stringBuffer对象中,解析邮件 主要根据MimeType的不同执行不同的操作,一步一步的解析

* @param part

* @throws MessagingException

* @throws IOException

*/

public void getMailContent(Part part) throws MessagingException,

IOException {

 

String contentType = part.getContentType();

int nameindex = contentType.indexOf("name");

boolean conname = false;

if (nameindex != -1) {

conname = true;

}

// System.out.println("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 count = multipart.getCount();

for (int i = 0; i < count; 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[] = msg.getHeader("Disposition-Notification-TO");

if (needreply != null) {

replySign = true;

}

return replySign;

}

 

/**

* 获取此邮件的message-id

* @return

* @throws MessagingException

*/

public String getMessageId() throws MessagingException {

return msg.getMessageID();

}

 

/**

* 判断此邮件是否已读,如果未读则返回false,已读返回true

* @return

* @throws MessagingException

*/

public boolean isNew() throws MessagingException {

boolean isnew = false;

Flags flags = ((Message) msg).getFlags();

Flags.Flag[] flag = flags.getSystemFlags();

System.out.println("flags's length:" + flag.length);

for (int i = 0; i < flag.length; i++) {

if (flag[i] == Flags.Flag.SEEN) {

isnew = true;

System.out.println("seen message .......");

break;

}

}

 

return isnew;

}

 

/**

* 判断是是否包含附件

* @param part

* @return

* @throws MessagingException

* @throws IOException

*/

public boolean isContainAttch(Part part) throws MessagingException,

IOException {

boolean flag = false;

 

if (part.isMimeType("multipart/*")) {

Multipart multipart = (Multipart) part.getContent();

int count = multipart.getCount();

for (int i = 0; i < count; i++) {

BodyPart bodypart = multipart.getBodyPart(i);

String dispostion = bodypart.getDisposition();

if ((dispostion != null)

&& (dispostion.equals(Part.ATTACHMENT) || dispostion

.equals(Part.INLINE))) {

flag = true;

} else if (bodypart.isMimeType("multipart/*")) {

flag = isContainAttch(bodypart);

} else {

String conType = bodypart.getContentType();

if (conType.toLowerCase().indexOf("appliaction") != -1) {

flag = true;

}

if (conType.toLowerCase().indexOf("name") != -1) {

flag = true;

}

}

}

} else if (part.isMimeType("message/rfc822")) {

flag = isContainAttch((Part) part.getContent());

}

 

return flag;

}

 

/**

* 保存附件

* @param part

* @throws MessagingException

* @throws IOException

*/

public void saveAttchMent(Part part) throws MessagingException, IOException {

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 dispostion = mpart.getDisposition();

if ((dispostion != null)

&& (dispostion.equals(Part.ATTACHMENT) || dispostion

.equals(Part.INLINE))) {

filename = mpart.getFileName();

if (!StringUtils.isNullOrBlank(filename)

&& (filename.toLowerCase().indexOf("gb18030") != -1 || filename

.toLowerCase().indexOf("gbk") != -1)) {

filename = MimeUtility.decodeText(filename);

}

 

saveFile(filename, mpart.getInputStream());

} else if (mpart.isMimeType("multipart/*")) {

saveAttchMent(mpart);

} else {

filename = mpart.getFileName();

if (filename != null

&& (filename.toLowerCase().indexOf("gbk") != -1)) {

filename = MimeUtility.decodeText(filename);

}

saveFile(filename, mpart.getInputStream());

}

}

 

} else if (part.isMimeType("message/rfc822")) {

saveAttchMent((Part) part.getContent());

}

}

 

/**

* 获得保存附件的地址

* @return

*/

public String getSaveAttchPath() {

return saveAttchPath;

}

 

/**

* 设置保存附件地址

* @param saveAttchPath

*/

public void setSaveAttchPath(String saveAttchPath) {

this.saveAttchPath = saveAttchPath;

}

 

/**

* 设置日期格式

* @param dateformate

*/

public void setDateformate(String dateformate) {

this.dateformate = dateformate;

}

 

/**

* 保存文件内容

* @param filename

* @param inputStream

* @throws IOException

*/

private void saveFile(String filename, InputStream inputStream)

throws IOException {

 

// 过滤:如果不是txt文件 不保存

if (StringUtils.isNullOrBlank(filename) || !filename.contains(".txt")) {

log.info("文件名为:" + filename + ",不是txt格式不保存.");

return;

}

String osname = System.getProperty("os.name");

String storedir = getSaveAttchPath();

String sepatror = "";

if (osname == null) {

osname = "";

}

 

if (osname.toLowerCase().indexOf("win") != -1) {

sepatror = "//";

if (storedir == null || "".equals(storedir)) {

storedir = "C://temp";

}

} else {

sepatror = "/";

storedir = "/temp";

}

 

File storefile = new File(storedir + sepatror + filename);

System.out.println("storefile's path:" + storefile.toString());

 

BufferedOutputStream bos = null;

BufferedInputStream bis = null;

 

try {

bos = new BufferedOutputStream(new FileOutputStream(storefile));

bis = new BufferedInputStream(inputStream);

int c;

while ((c = bis.read()) != -1) {

bos.write(c);

bos.flush();

}

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} finally {

bos.close();

bis.close();

}

 

}

 

public void receive(Part part, String filePath, int i, String date)

throws MessagingException, IOException {

log.info("------------------receive Email START-----------------------");

log.info("Message" + i + " subject:" + getSubject());

log.info("Message" + i + " from:" + getFrom());

log.info("Message" + i + " isNew:" + isNew());

String sendDate = getSendDate();

if (!sendDate.equals(date)) {

log.info("Email SendDate :" + sendDate + ",we get date:" + date

+ ",----receive Email END-----------------------");

return;

}

boolean flag = isContainAttch(part);

log.info("Message" + i + " isContainAttch:" + flag);

getMailContent(part);

log.info("Message" + i + " content:" + getBodyText());

setSaveAttchPath(filePath);

if (flag) {

saveAttchMent(part);

}

log.info("------------------receive Email END-----------------------");

}

 

/**

* 判断文件夹是否存在,不存在则创建,存在则删除文件夹里面的文件

* @param filePath

*/

private void dealFile(String filePath) {

File file = new File(filePath);

if (!file.exists()) {

file.mkdirs();

} else {

String[] str = file.list();

for (String s : str) {

File f = new File(filePath + FileUtils.getFileSeparator() + s);

f.delete();

}

}

}

 

/***

* 下载附件

* @param smtp

* @param pop

* @param userName

* @param pwd

* @param date

*            (yyyy-MM-dd)

*/

public void downLoadAttchMent(String smtp, String pop, String userName,

String pwd, String date) {

Properties props = new Properties();

props.setProperty("mail.smtp.host", smtp);

props.setProperty("mail.smtp.auth", "true");

Session session = Session.getDefaultInstance(props, null);

// 这里使用的是sina的邮件服务器,输入邮箱用户名和密码直接运行就可以收邮件

URLName urlname = new URLName("pop3", pop, 110, null, userName, pwd);

String filePath = saveAttchPath + date;

 

// 文件夹不存在则创建,存在则删除里面数据

dealFile(filePath);

try {

Store store = session.getStore(urlname);

store.connect();

Folder folder = store.getFolder("INBOX");

folder.open(Folder.READ_ONLY);

Message msgs[] = folder.getMessages();

int count = msgs.length;

EmailUtils rm = null;

for (int i = 0; i < count; i++) {

if (!msgs[i].getFolder().isOpen()) // 判断是否open

msgs[i].getFolder().open(Folder.READ_ONLY); // 如果close,就重新open

rm = new EmailUtils((MimeMessage) msgs[i]);

try {

rm.receive(msgs[i], filePath, i, date);

((POP3Message) msgs[i]).invalidate(true);// 每封邮件读取完后,设置不往cache中添加

} catch (Exception e) {

log.info("收件异常:" + ExceptionUtils.getFullStackTrace(e));

continue;

}

}

} catch (Exception e) {

log.info("邮件属性配置错误:" + ExceptionUtils.getFullStackTrace(e));

}

}

 

public static void main(String[] args) {

// 这里使用的是sina的邮件服务器,输入邮箱用户名和密码直接运行就可以收邮件

// new

// EmailUtils().downLoadAttchMent("smtp.sina.com","pop.sina.com","zzjicdi@sina.com",

// "","2013-09-04");

// new

// EmailUtils().downLoadAttchMent("mail.jade388.com","mail.jade388.com","zijinbu@jade388.com",

// "123456","2013-09-02");

// new

// EmailUtils().downLoadAttchMent("smtp.qq.com","pop.qq.com","214203258@qq.com",

// "","2013-09-02");

 

}

 

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值