添加依赖

org.springframework.boot

spring-boot-starter-mail

获取邮件附件代码

package com.example.emaildemo.email;

import javax.mail.*;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeUtility;

import javax.mail.search.*;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.time.LocalDateTime;

import java.time.ZoneId;

import java.time.ZonedDateTime;

import java.util.*;

public class Pop3Mails {

public static void main(String[] args) {

Pop3Mails mail = new Pop3Mails();

mail.read();

}

public void read() {

Properties props = new Properties();

try {

final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);

props.setProperty("mail.pop3.socketFactory.fallback", "false");

props.setProperty("mail.pop3.port", "995");

props.setProperty("mail.pop3.socketFactory.port", "995");

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

Store store = session.getStore("pop3");

String user = "xxxx@gmail.com";

// 如果为gmail需开通二次验证密码

String password = "xxxxxx";

store.connect("pop.gmail.com", user, password);

Folder inbox = store.getFolder("inbox");

inbox.open(Folder.READ_ONLY);

LocalDateTime localDateTime = LocalDateTime.now().minusYears(1);

ZoneId zoneId = ZoneId.systemDefault();

ZonedDateTime zdt = localDateTime.atZone(zoneId);//Combines this date-time with a time-zone to create a ZonedDateTime.

Date start = Date.from(zdt.toInstant());

Date now = new Date();

SearchTerm comparisonTermGe = new SentDateTerm(ComparisonTerm.GE, start);

SearchTerm comparisonTermLe = new SentDateTerm(ComparisonTerm.LE, now);

//需要查询的邮件名

String fromEmail = "xxxxxxxxxx@gmail.com";

FromStringTerm fromStringTerm = new FromStringTerm(fromEmail);

SearchTerm andTerm = new AndTerm(new SearchTerm[]{comparisonTermGe, comparisonTermLe});

Message[] messages = inbox.search(andTerm); //根据设置好的条件获取message

Message[] search = inbox.search(fromStringTerm, messages);

for (int i = search.length - 1; i >= 0; i--) {

Message message = search[i];

Date date = message.getSentDate();

System.out.println("Mail Subject:- " + message.getSubject());

System.out.println("Mail Content Type:- " + message.getContentType());

System.out.println("Mail Sent Date:- " + date);

if (message.getContentType().startsWith("multipart/")) {

needProcessEmail(message);

}

}

inbox.close(true);

store.close();

} catch (Exception e) {

e.printStackTrace();

}

}

/**

* 文件拷贝,在用户进行附件下载的时候,可以把附件的InputStream传给用户进行下载

*

* @param is

* @param os

* @throws IOException

*/

public static void copy(InputStream is, OutputStream os) throws IOException {

byte[] bytes = new byte[1024];

int len = 0;

while ((len = is.read(bytes)) != -1) {

os.write(bytes, 0, len);

}

if (os != null)

os.close();

if (is != null)

is.close();

}

private boolean needProcessEmail(Message msg) throws Exception {

System.out.println("needProcessEmail > 当前邮件的标题" + msg.getSubject());

// 1. 检查发件人邮箱是否包含在我们监控的邮箱列表里面

String from = getFrom(msg);

if (!isContainAttach((Part) msg)) {

System.out.println("发件人满足要求但是附件为空,不满足我们监控的需求!");

return false;

}

Map fileMap = new HashMap<>();

getFileInputStream(msg, fileMap);

if (fileMap.isEmpty()) {

System.out.println("尽管邮件中有附件但是邮件中的附件却无一个满足要求!");

return false;

}

System.out.println(fileMap);

for (String s : fileMap.keySet()) {

InputStream inputStream = fileMap.get(s);

copy(inputStream, new FileOutputStream("D:\\" + s));

}

return true;

}

private String getFrom(Message msg) throws MessagingException {

String from = "";

InternetAddress[] addresses = (InternetAddress[]) msg.getFrom();

if (null == addresses || addresses.length == 0) {

System.out.println("无法获取发送人地址信息");

return from;

}

Address address = addresses[0];

System.out.println("件人地址json:" + address);

String form = ((InternetAddress) address).getAddress();

return form;

}

private void getFileInputStream(Part part, Map inputStreamMap) 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.toLowerCase().contains("gb2312")) {

fileName = MimeUtility.decodeText(fileName);

}

if (checkFileName(fileName)) {

inputStreamMap.put(fileName, mPart.getInputStream());

}

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

System.out.println("子邮件里面的附件");

getFileInputStream(mPart, inputStreamMap);

} else {

fileName = mPart.getFileName();

if ((fileName != null)

&& (fileName.toLowerCase().contains("GB2312"))) {

fileName = MimeUtility.decodeText(fileName);

if (checkFileName(fileName)) {

inputStreamMap.put(fileName, mPart.getInputStream());

}

}

}

}

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

getFileInputStream((Part) part.getContent(), inputStreamMap);

}

}

private boolean checkFileName(String fileName) {

return true;

}

private boolean isContainAttach(Part part) throws Exception {

boolean attachFlag = false;

// String contentType = part.getContentType();

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((Part) mPart);

} else {

String conType = mPart.getContentType();

if (conType.toLowerCase().contains("application")) {

attachFlag = true;

}

if (conType.toLowerCase().contains("name")) {

attachFlag = true;

}

}

}

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

attachFlag = isContainAttach((Part) part.getContent());

}

return attachFlag;

}

}

php pop3 gmail,通过POP3协议读取gmail中的附件相关推荐

  1. spring boot 中使用 POP3协议读取并解析邮件

    spring boot 中使用 POP3协议读取并解析邮件 1.邮箱授权 QQ邮箱授权,打开 "设置" 切换到 "账户" 找到下图中设置,开启 "PO ...

  2. javamail使用IMAP协议收取gmail邮件

    年底了,绩效是逃不开的话题,为总结这一年来的工作情况,查看邮件是非常必要的.但是,邮件太多,如何筛选和保留成为一个问题,因此想到实现个自动统计邮件内容的工具,今天分享使用IMAP协议收取gmail邮件 ...

  3. python 读取gmail 邮箱消息

    一个读取gmail 消息的小代码. import poplib from email import parserpop_conn = poplib.POP3_SSL('pop.gmail.com') ...

  4. qq邮箱 pop3smtp服务 php,QQ邮箱开启POP3/SMTP服务 POP3/SMTP服务什么意思

    QQ邮箱开启POP3/SMTP服务 POP3/SMTP服务什么意思.想打开邮箱POP3/SMTP服务,可就是不知道在那里打开,想用QQ邮箱来代收其他邮箱的邮件.下文就让小编跟大家介绍怎么开启QQ邮箱P ...

  5. rtsp 协议读取视频进行分析并返回结果到websocket server

    一.rtsp 协议读取视频 1.1读取方法ffmpeg 这种方法和opencv是一样的,因为opencv使用的就是ffmpeg,结果不是很好,断线重连不是很好做,有一个好处是不用引入其他库,ffmpe ...

  6. iphone中怎么添加邮箱_如何在iPhone的Gmail中添加附件

    iphone中怎么添加邮箱 While email is still an incredibly popular form of communication, it's not always a pa ...

  7. BACnet协议读取与发送

    BACnet协议读取与发送 注意 我的提问: 更新 开发环境 BACnet相关基础知识 BACnet格式 BACnet代码 BACnet设备查找 BACnet设备读取 BACnet写入操作 AND其他 ...

  8. CK-S640系列半导体专用RFID读写器如何通过RS232通讯SECS协议读取TI低频玻璃管标签数据?

    CK-S640系列半导体专用RFID读写器是一款工业级低频RFID读写卡器,读卡器工作频率134.2kHz,HDX工作模式,支持ISO11784/85射频标准标签,支持Profinet以及工业半导体S ...

  9. 服务器和交换机之间网络协议,网络协议是计算机网络中服务器,计算机,交换机.doc...

    网络协议是计算机网络中服务器,计算机,交换机 篇一:计算机网络-参考答案 (1)不能保证所有题目都在里面,但能保证大部分题目都在这里. (2)建议用快捷方式ctrl+f 进行答案的查找,关键字只需复制 ...

最新文章

  1. 推荐一款 Nginx 可视化配置神器
  2. ​2021年机器学习什么风向?把注意力放在MLP上
  3. 450g吐司烘烤温度_美晨烘焙丨会吐蛋黄的黄金吐司
  4. c语言画图 钟表模拟程序,图形模拟时钟C语言课程设计
  5. Dubbo错误排查:com.alibaba.dubbo.rpc.RpcException: Invoke remote method timeout
  6. js aop 拦载实现
  7. mySql存储过程,简单实现实例
  8. python电脑推荐_6款Python必备的可视化工具推荐
  9. 信息学奥赛一本通 2006:【20CSPJ普及组】表达式 | 洛谷 P7073 [CSP-J2020] 表达式
  10. 文本的表示-词嵌入(word embedding)
  11. Servlet、Struts2以及SpringMvc中的线程安全
  12. 计算机二级access通过技巧,计算机二级Access考试技巧:筛选记录
  13. java中的加加++的疑惑?
  14. 10个妙招 在线视频下载方法大全
  15. AJAX和CGI 技术的应用
  16. Final Cut Pro X无法导入自家的MOV格式,解决方法。
  17. Multi-armed Bandits(多臂老虎机问题)
  18. 战地2服务器2地图修改,战地2地图修改
  19. PI数据库开发-java(读写pi中的时序数据和关系数据)
  20. HTML font 标签的 size 属性

热门文章

  1. 2022 07 17 第九组 韩文清 职业人生规划
  2. ROM制作教程 如何创建一个刷机包
  3. C#中如何使ComboBox禁止粘帖
  4. 厉害了,二本大学生这样拿下阿里 Offer!| 程序员有话说
  5. 亿方云全国营销中心落户上海,各届大咖挤爆现场!
  6. oracle 数据类型的变更无效 clob,ORA-22858数据类型的变更无效 varchar2类型转换为clob类型...
  7. MySQL 查看表结构相关的几个命令
  8. invalid authentication data.Connection refused :connect
  9. 解密:2012世界末日其实是个大骗局
  10. 朋友圈“锦鲤”盛行,如何抽取“锦鲤”?Python放大招了~