java邮件接收_Javamail邮件接收程序(pop3)

该博客介绍了如何使用Java的Javamail API来连接POP3服务器,打开INBOX,接收邮件,并根据指定的条件过滤邮件。如果邮件包含附件,程序会将它们保存到特定目录。此外,还提供了邮件过滤接口和邮件处理实用类的辅助方法。
摘要由CSDN通过智能技术生成

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.util.ArrayList;

import java.util.List;

import java.util.Properties;

import javax.mail.BodyPart;

import javax.mail.FetchProfile;

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.UIDFolder;

import org.springframework.util.Assert;

import org.springframework.util.FileCopyUtils;

import org.springframework.util.StringUtils;

import com.sun.mail.pop3.POP3Folder;

/**

* 邮件接收器,方法调用顺序:open->receive->close

*/

public class MailReceiver {

public static final String POP3 = "pop3";

public static final String INBOX = "INBOX";

private String pop;

private String serverName;

private String serverPasswd;

private MessageFilter msgFilter;

/**

* 附件下载后的存放目录

*/

private String attachSavePath;

private Store store;

private POP3Folder inbox;

private FetchProfile profile;

/**

* 构造器(不保存附件,不对接收邮件进行过滤处理)

*

* @param pop

* POP Server URL

* @param serverName

* 用户名

* @param serverPasswd

* 密码

* @param msgFilter

* 邮件过滤器,null表示不过滤

*/

public MailReceiver(String pop, String serverName, String serverPasswd) {

this(pop, serverName, serverPasswd, null, null);

}

/**

* 构造器(不保存附件)

*

* @param pop

* POP Server URL

* @param serverName

* 用户名

* @param serverPasswd

* 密码

* @param msgFilter

* 邮件过滤器,null表示不过滤

*/

public MailReceiver(String pop, String serverName, String serverPasswd,

MessageFilter msgFilter) {

this(pop, serverName, serverPasswd, msgFilter, null);

}

/**

* 构造器(不对接收邮件进行过滤处理)

*

* @param pop

* POP Server URL

* @param serverName

* 用户名

* @param serverPasswd

* 密码

* @param attachSavePath

* 附件存放路径,null表示不保存附件

*/

public MailReceiver(String pop, String serverName, String serverPasswd,

String attachSavePath) {

this(pop, serverName, serverPasswd, null, attachSavePath);

}

/**

* 构造器

*

* @param pop

* POP Server URL

* @param serverName

* 用户名

* @param serverPasswd

* 密码

* @param msgFilter

* 邮件过滤器,null表示不过滤

* @param attachSavePath

* 附件存放路径,null表示不保存附件

*/

public MailReceiver(String pop, String serverName, String serverPasswd,

MessageFilter msgFilter, String attachSavePath) {

super();

Assert.hasLength(pop, "Pop");

Assert.hasLength(serverName, "ServerName");

Assert.hasLength(serverPasswd, "ServerPasswd");

this.pop = pop;

this.serverName = serverName;

this.serverPasswd = serverPasswd;

this.msgFilter = msgFilter;

this.attachSavePath = attachSavePath;

}

/**

* 连接邮件服务器,打开INBOX

*/

public void open() throws MessagingException {

Properties props = new Properties();

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

this.store = session.getStore(POP3);

store.connect(pop, serverName, serverPasswd);

this.inbox = (POP3Folder) store.getFolder(INBOX);

inbox.open(Folder.READ_ONLY);

this.profile = new FetchProfile();

profile.add(UIDFolder.FetchProfileItem.UID);

profile.add(FetchProfile.Item.ENVELOPE);

}

/**

* 收取邮件,自动保存附件至指定目录,该方法不会关闭INOBX及连接。

* 调用 {@link #close()}方法关闭INBOX及连接。

*

* @throws UnsupportedEncodingException

* @throws IOException

* @throws MessagingException

*/

public List receive() throws UnsupportedEncodingException,

IOException, MessagingException {

// 获取邮件及UID

Message[] messages = inbox.getMessages();

inbox.fetch(messages, profile);

// 过滤处理

List msgList = new ArrayList();

for (Message msg : messages) {

if (msgFilter == null || msgFilter.filte(inbox, msg)) {

// 保存附件

if (StringUtils.hasLength(attachSavePath)

&& MailUtils.containsAttach(msg)) {

saveAttachment(msg);

}

msgList.add(msg);

}

}

return msgList;

}

/**

* 关闭INBOX及连接。

*/

public void close() {

try {

inbox.close(false);

store.close();

} catch (MessagingException e) {

throw new MailException("关闭INBOX及连接出错", e);

}

}

public POP3Folder getInbox() {

return inbox;

}

/**

* 保存附件

*

* @throws Exception

* @throws IOException

* @throws MessagingException

* @throws UnsupportedEncodingException

*/

private void saveAttachment(Part part) throws UnsupportedEncodingException,

MessagingException, IOException {

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

String filename = "";

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 = MailUtils.decodeText(mpart.getFileName());

saveFile(filename, mpart.getInputStream());

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

saveAttachment(mpart);

} else {

filename = MailUtils.decodeText(mpart.getFileName());

if (filename != mpart.getFileName()) {

saveFile(filename, mpart.getInputStream());

}

}

}

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

saveAttachment((Part) part.getContent());

}

}

/**

* 保存附件到指定目录

*

* @throws IOException

* @throws FileNotFoundException

*/

private void saveFile(String filename, InputStream in)

throws FileNotFoundException, IOException {

File file = new File(attachSavePath + File.separator + filename);

FileCopyUtils.copy(in, new FileOutputStream(file));

}

}

import javax.mail.Message;

import javax.mail.MessagingException;

import com.sun.mail.pop3.POP3Folder;

/**

* 邮件过滤接口,用于实现只收取未读邮件这样的功能。

*/

public interface MessageFilter {

/**

* 过滤邮件

*

* @param box

* 邮件文件夹

* @param message

* 邮件消息

* @return 如何需要读取此邮件,返回true,否则返回false

*/

boolean filte(POP3Folder box, Message message) throws MessagingException;

}

import java.io.IOException;

import java.io.UnsupportedEncodingException;

import javax.mail.BodyPart;

import javax.mail.MessagingException;

import javax.mail.Multipart;

import javax.mail.Part;

import javax.mail.internet.MimeUtility;

import org.springframework.util.Assert;

/**

* 邮件处理实用类

*/

public class MailUtils {

private MailUtils() {

}

/**

* MimeUtility.decodeText(text)

*/

public static String decodeText(String text)

throws UnsupportedEncodingException {

if (text == null)

return null;

String s = text.toLowerCase();

if (s.contains("gb2312") || s.contains("gbk")) {

return MimeUtility.decodeText(text);

}

return text;

}

/**

* 判断邮件是否包含附件

*

* @throws IOException

* @throws MessagingException

*/

public static boolean containsAttach(Part part) throws MessagingException,

IOException {

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 = containsAttach((Part) 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 = containsAttach((Part) part.getContent());

}

return attachflag;

}

/**

* 解析邮件,把得到的邮件内容保存到bodyText对象中.

* 根据MimeType类型的不同执行不同的解析操作.

*

* @throws IOException

* @throws MessagingException

*/

public static void getMailContent(Part part, StringBuffer bodyText)

throws MessagingException, IOException {

Assert.notNull(bodyText, "bodyText");

String contenttype = part.getContentType();

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

boolean conname = false;

if (nameindex != -1)

conname = true;

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), bodyText);

}

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

getMailContent((Part) part.getContent(), bodyText);

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值