1.引包
2.读取最新邮件
public static InputStream readEmailAttachments(String host, String username, String password) throws MessagingException, IOException {
// 设置连接属性
Properties properties = new Properties();
properties.put("mail.store.protocol", "pop3"); // 或者 "pop3",取决于你的邮件服务器
properties.put("mail.pop3.host", host);
// properties.put("mail.pop3.port", port);
properties.put("mail.pop3.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);
// 连接到邮件服务器
Store store = emailSession.getStore("pop3"); // smtp imap
store.connect(host, username, password);
// 打开文件夹
Folder emailFolder = store.getFolder("INBOX");//INBOX Inbox
emailFolder.open(Folder.READ_ONLY);
// 取到文件夹中所有信息
// 获取邮件消息
Message[] messages = emailFolder.getMessages();
// Message[] messages = emailFolder.search(searchTerm);
//获取最新邮件
Message message1 = emailFolder.getMessage(messages.length);
// 检查是否有附件
if (message1.isMimeType("multipart/*")) {
Multipart multipart = (Multipart) message1.getContent();
for (int i = 0; i < multipart.getCount(); i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
// 检查是否为附件
if (Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
// 保存附件
//String fileName = bodyPart.getFileName();
String strFileName = MimeUtility.decodeText(bodyPart.getFileName()); //MimeUtility.decodeText解决附件名乱码问题
//String filePath = "D:\\" + strFileName;
// ((MimeBodyPart) bodyPart).saveFile(filePath);
if(strFileName.endsWith(".xlsx")||strFileName.endsWith(".xls")){
System.out.println("附件读取成功,附件名: " + strFileName);
InputStream is1 = bodyPart.getInputStream();
// 关闭资源
emailFolder.close(false);
store.close();
return is1;
}
}
}
return null;
}
3.调用 注意@Value必须在service层才有效
@Value("${spring.mail.host}")
private String host;
@Value("${spring.mail.username}")
private String uname;
@Value("${spring.mail.password}")
private String psd;
@Transactional
public List<ExcelInfoNewsVo> insertNegativeNewsListToExcel() {
List<ExcelInfoNewsVo> resultExcelInfoNews=new ArrayList<>();
try {
log.info("读取邮件附件开始,邮箱:{}{}",uname,host);
InputStream is = MailUtil.readEmailAttachments(host,uname,psd);