/**
* 版权所有 2022 涂聚文有限公司
* 许可信息查看:
* 描述:
*
* 数据库:Ms SQL server 2019
* IDE: Eclipse IDE for Enterprise Java and Web Developers - 2021-09
* OS: Windows 10 x64
* IDE: Eclipse IDE for Enterprise Java and Web Developers - 2021-09
* 历史版本: JDK 19
* 2022-1-12 创建者 geovindu
* 2022-1-15 添加 Lambda
* 2022-1-15 修改:date
* 接口类 mssql-jdbc-9.4.1.jre16.jar.
* 数据库:MSSQL Server 2019
* 2022-1-25 修改者:Geovin Du
* 生成API帮助文档的指令:
*javadoc - -encoding Utf-8 -d apidoc DuMailPopHelper.java
*
*
*https://github.com/eclipse-ee4j/mail
*https://eclipse-ee4j.github.io/mail/docs/api/index.html
*https://mvnrepository.com/artifact/com.sun.mail/jakarta.mail/2.0.1 Jakarta Mail
*https://javaee.github.io/javamail/#Samples
*https://github.com/javaee/javamail/releases/tag/JAVAMAIL-1_6_2
*https://mvnrepository.com/artifact/javax.activation/activation/1.1.1
*https://www.thymeleaf.org/download.html
https://github.com/thymeleaf
https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf
*https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf
https://mvnrepository.com/artifact/org.springframework/spring-core
http://www.java2s.com/Code/Jar/s/Downloadspringframework515jar.htm
https://github.com/apache/tomcat/blob/main/java/org/apache/tomcat/Jar.java
https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-util
*https://tomcat.apache.org/download-10.cgi
*
*
* **/
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import com.sun.mail.pop3.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.*;
import javax.mail.Flags.Flag;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
import com.sun.mail.imap.*;
//.IMAPFolder
import com.sun.mail.imap.IMAPMessage;
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.protocol.IMAPProtocol;
import org.apache.tomcat.util.http.fileupload.IOUtils;
//import org.apache.tomcat.util.*;
import org.springframework.util.ObjectUtils;
/**
* 接收邮件
* @author geovindu
* @version 1.0
*
*
* ***/
/**
*
*
*
* **/
public static void DuReceiveEmailImap(String pop3Host,String port,String storeType, String user, String password)throws MessagingException, IOException
{
// 准备连接服务器的会话信息
Properties props = new Properties();
props.put("mail.store.protocol", storeType); //imap
props.put("mail.pop3.starttls.enable", "false");
props.put("mail.imap.host",pop3Host );//"imap.163.com"
props.put("mail.imap.port", port); //"143" imap.163.com
// 创建Session实例对象
//Session session = Session.getInstance(props);
Session session =Session.getDefaultInstance(props,null);//
// 创建IMAP协议的Store对象
Store store = session.getStore("imap");
// 连接邮件服务器
store.connect(pop3Host,user, password); //"geovindu@163.com"
Folder folder = store.getFolder("Inbox");
// folder.open(Folder.READ_ONLY);
//Message messages[] = folder.getMessages();
// FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
// Message messages[] = folder.search(ft);
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;
}
});
}
// 获得收件箱
//Folder folder = store.getFolder("whatever");//INBOX
//Folder folder = store.getFolder("whatever");
// IMAPFolder ifolder = (IMAPFolder)folder;
// List<MailEvent> events = ifolder.open(Folder.READ_WRITE,
// new ResyncData(prevUidValidity, prevModSeq));
// 以读写模式打开收件箱
//folder.open(Folder.READ_ONLY);
//ifolder.open(ifolder.READ_WRITE);
if(folder != null) {
folder.open(Folder.READ_WRITE);
}
// 获得收件箱的邮件列表
//Message[] messages = folder.getMessages();
Message[] messages =getWEMessage(pop3Host,user,password,storeType);// folder.getMessages();
// 打印不同状态的邮件数量
String str = new String(("收件箱中共" + Integer.toString(messages.length) + "封邮件!").getBytes(),"utf-8");
System.out.println("收件箱中共" + Integer.toString(messages.length) + "封邮件!");
String str1="收件箱中共" + Integer.toString(folder.getUnreadMessageCount()) + "封未读邮件!";
System.out.println(str1);
System.out.println("收件箱中共" + Integer.toString(folder.getNewMessageCount()) + "封新邮件!");
System.out.println("收件箱中共" + Integer.toString(folder.getDeletedMessageCount()) + "封已删除邮件!");
System.out.println("------------------------开始解析邮件----------------------------------");
DuMailHelper helper=new DuMailHelper();
// 解析邮件
for (Message message : messages) {
IMAPMessage msg = (IMAPMessage) message;
String subject = MimeUtility.decodeText(msg.getSubject());
System.out.println("[" + subject + "]未读,是否需要阅读此邮件(yes/no)?");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String answer = reader.readLine();
if ("yes".equalsIgnoreCase(answer)) {
parseImapMessage(msg); // 解析邮件
// 第二个参数如果设置为true,则将修改反馈给服务器。false则不反馈给服务器
msg.setFlag(Flag.SEEN, true); //设置已读标志
}
}
// 关闭资源
folder.close(false);
store.close();
}
/**
* 获取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 = System.getProperties();
props.setProperty("mail.store.protocol", protocol);
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore(protocol);
store.connect(host, username, password);
Folder folder = store.getFolder("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);
}
return folder.getMessages();
}
/**
*
*
*
* **/
public static void parseImapMessage(IMAPMessage... messages) throws MessagingException, IOException {
//判断邮件是否为空
if (messages == null || messages.length < 1) {
throw new MessagingException("未找到要解析的邮件!");
}
// 解析所有邮件
for (int i = 0, count = messages.length; i < count; i++) {
MimeMessage msg = (MimeMessage) messages[i];
System.out.println("-----------解析第" + msg.getMessageNumber() + "封邮件---------------");
System.out.println("主题: " + DuMailHelper.getSubject(msg));
System.out.println("发件人: " + DuMailHelper.getFrom(msg));
System.out.println("收件人:" + DuMailHelper.getReceiveAddress(msg, Message.RecipientType.TO));
System.out.println("发送时间:" + DuMailHelper.getSentDate(msg, null));
System.out.println("是否已读:" + DuMailHelper.isSeen(msg));
System.out.println("邮件优先级:" + DuMailHelper.getPriority(msg));
System.out.println("是否需要回执:" + DuMailHelper.isReplySign(msg));
System.out.println("邮件大小:" + msg.getSize() * 1024 + "kb");
boolean isContainerAttachment = DuMailHelper.isContainAttachment(msg);
System.out.println("是否包含附件:" + isContainerAttachment);
if (isContainerAttachment) {
//获取文件的存储目录
String path = JavaxJavaMailClient.class.getClassLoader().getResource("").getPath();
//获取文件的前缀
String strFile = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
DuMailHelper.saveAttachment(msg, path + strFile + "_"); //保存附件
}
//用来存储正文的对象
StringBuffer content = new StringBuffer();
//处理邮件正文
DuMailHelper.getMailTextContent(msg, content);
System.out.println("邮件正文:" + content);
System.out.println("-----------第" + msg.getMessageNumber() + "封邮件解析结束------------");
System.out.println();
}
}
/**
* 接收邮件
* 中文是乱码 未解决
* @param pop3Host pop.163.com
* @param storeType pop3
* @param user geovindu@163.com
* @param password geovindu
* @author geovindu
* @serialData@
*
*
* **/
public static void DuReceiveEmail(String pop3Host,String storeType, String user, String password){
Properties props = new Properties();
props.put("mail.pop3.host", pop3Host);
props.put("mail.pop3.port", "110");
props.put("mail.pop3.starttls.enable", "false");
props.put("mail.store.protocol", "pop3");
Session session = Session.getInstance(props);
try {
Store mailStore = session.getStore(storeType);
mailStore.connect(pop3Host, user, password);
Folder folder = mailStore.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
Message[] emailMessages = folder.getMessages();
System.out.println("Total Message - "
+ emailMessages.length);
//Iterate the messages
for (int i = 0; i < emailMessages.length; i++) {
Message message = emailMessages[i];
Address[] toAddress =
message.getRecipients(Message.RecipientType.TO);
System.out.println();
System.out.println("Email " + (i+1) + "-");
System.out.println("Subject - " + message.getSubject());
System.out.println("From - " + message.getFrom()[0]);
System.out.println("To - ");
for(int j = 0; j < toAddress.length; j++){
System.out.println(toAddress[j].toString());
}
System.out.println("Text - " +
message.getContent().toString());
}
folder.close(false);
mailStore.close();
} catch (Exception e) {
e.printStackTrace();
System.err.println("Error in receiving email.");
}
}
java: imap Receive Email
原创
©著作权归作者所有:来自51CTO博客作者geovindu的原创作品,请联系作者获取转载授权,否则将追究法律责任
上一篇:我的友情链接
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
outlook邮箱(office365)使用java进行收取(IMAP)和发送(SMTP)
outlook邮箱用imap收取和smtp发送,应用配置和java实现
outlook邮箱 office365邮箱 SMTP IMAP -
Building an IMAP Email Client with PHP
IMAP
PHP IMAP Email Client php sed