Java收取邮件示例
程序员文章站
2022-05-29 07:56:58
...
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPStore;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import java.util.Properties;
/**
* @Author: machi
* @Date: 2020-05-29
* @Time: 17:47
* @ClassName: test
* @Description:
*/
public class test {
public static void main(String[] args) throws Exception {
String user = "[email protected]";// 邮箱的用户名
String password = "ERYLSOUDFQMQLWJA"; // 邮箱的密码 或者相应授权码*/
//String password = "XYGYRLDRUGXRSLAZ"; // 邮箱的密码*/
//String password = "mXrBqjoFWuzVPUe7"; // 邮箱的密码*/
Properties prop = System.getProperties();
prop.put("mail.store.protocol", "imap");
prop.put("mail.imap.host", "imap.163.com");
// prop.put("mail.imap.host", "imap.exmail.qq.com");
//开启ssl
prop.setProperty("mail.smtp.auth", "true");//开启认证
prop.setProperty("mail.debug", "true");//启用调试
prop.setProperty("mail.smtp.timeout", "200000");//设置链接超时
prop.setProperty("mail.smtp.port", Integer.toString(25));//设置端口
prop.setProperty("mail.smtp.socketFactory.port", Integer.toString(465));//设置ssl端口
prop.setProperty("mail.smtp.socketFactory.fallback", "false");
prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
Session session = Session.getInstance(prop);
int total = 0;
IMAPStore store = (IMAPStore) session.getStore("imap"); // 使用imap会话机制,连接服务器
store.connect(user, password);
IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX"); // 收件箱
folder.open(Folder.READ_WRITE);
// 获取总邮件数
total = folder.getMessageCount();
System.out.println("-----------------共有邮件:" + total
+ " 封--------------");
// 得到收件箱文件夹信息,获取邮件列表
System.out.println("未读邮件数:" + folder.getUnreadMessageCount());
Message[] messages = folder.getMessages();
int messageNumber = 0;
for (Message message : messages) {
System.out.println("发送时间:" + message.getSentDate());
System.out.println("主题:" + message.getSubject());
System.out.println("内容:" + message.getContent());
Flags flags = message.getFlags();
if (flags.contains(Flags.Flag.SEEN))
System.out.println("这是一封已读邮件");
else {
System.out.println("未读邮件");
}
System.out
.println("========================================================");
System.out
.println("========================================================");
//每封邮件都有一个MessageNumber,可以通过邮件的MessageNumber在收件箱里面取得该邮件
messageNumber = message.getMessageNumber();
}
Message message = folder.getMessage(messageNumber);
System.out.println(message.getContent() + message.getContentType());
// 释放资源
if (folder != null)
folder.close(true);
if (store != null)
store.close();
}
}
上一篇: maven下载及环境配置