java接收邮件
安装依赖
前三个是接收邮件用的,其他的酌情安装(java世界坑太多了,本以为装第一个依赖就够了,结果给你各种出错)
implementation 'jakarta.mail:jakarta.mail-api:2.1.2'
implementation 'jakarta.activation:jakarta.activation-api:2.1.2'
implementation 'org.eclipse.angus:jakarta.mail:1.0.0'
implementation 'org.yaml:snakeyaml:2.0'
annotationProcessor 'org.projectlombok:lombok'
配置文件
resources目录下,config/mail-config.yml
recive:
protocol: "pop3"
host: "pop3.163.com"
port: "110"
username: "abc@163.com"
password: "ASDFSFSDFSDFDSF"
baseDir: "C:\\Users\\{user}\\Desktop"
这里用了网易邮箱,使用pop3协议, baseDir是存放附件的目录
示例代码
import jakarta.mail.*;
import jakarta.mail.internet.*;
import jakarta.activation.*;
import lombok.extern.slf4j.Slf4j;
import org.yaml.snakeyaml.Yaml;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
import java.util.Properties;
/**
* @param
* @param null
* @author aloha
* @description TODO
* @createTime
* @return
* @return null
*/
@Slf4j
public class MailRecive {
private String protocol;
private String host;
private String port;
private String username;
private String password;
private String baseDir; //存储附件的目录
public void mailRecive() throws Exception {
Yaml yaml = new Yaml();
try (InputStream in = MailRecive.class.getClassLoader().getResourceAsStream("config/mail-config.yml")) {
Map config = (Map<String, Object>) yaml.load(in);
Map<String, String> recive = (Map<String, String>) config.get("recive");
protocol = recive.get("protocol");
host = recive.get("host");
port = recive.get("port");
username = recive.get("username");
password = recive.get("password");
baseDir = recive.get("baseDir");
} catch (Exception e) {
log.error("读取邮件配置文件{}", e);
}
// 准备连接服务器的会话信息
Properties props = new Properties();
props.setProperty("mail.store.protocol", protocol); //协议 ,如"imap"
props.setProperty("mail.host", host); //主机 ,如 imap.163.com
props.setProperty("mail.port", port); //端口 ,如 143
// 创建Session实例对象
Session session = Session.getInstance(props);
// 创建IMAP协议的Store对象
Store store = session.getStore(protocol);
// 连接邮件服务器
store.connect(username, password);
// 获得收件箱
Folder folder = store.getFolder("INBOX");
// 打开收件箱
folder.open(Folder.READ_ONLY); //打开方式,只读:Folder.READ_ONLY 或1. 读写:Folder.READ_WRITE 或2
// folder.open(1); //打开方式,只读: 1. 读写: 2
//邮件数
// folder.getMessageCount(); //邮件总数,等同于msgs.length
// folder.getUnreadMessageCount() //未读邮件数
// folder.getNewMessageCount() //新邮件数
// folder.getDeletedMessageCount() //已删除邮件数
// 获得收件箱的邮件列表,遍历每封邮件,并下载附件到指定目录,测试邮箱只有一封邮件
Message[] msgs = folder.getMessages();
for (Message msg : msgs) {
// log.debug("标题:{}", msg.getSubject());
// log.debug("内容:{}", msg.getContent()); //内容目前没拿到,官网上不去,后面需要再说jakarta.mail.internet.MimeMultipart@3bbc39f8
// log.debug("邮件类型:{}", msg.getContentType().toString()); //multipart/mixed
// log.debug("文件名:{}", msg.getFileName()); //null
// log.debug("对方发送时间:{}", msg.getSentDate().toString());
//// log.debug("接收时间:{}", msg.getReceivedDate().toString()); 可能为null
// log.debug("getDataHandler:{}", msg.getDataHandler());
//// log.debug("getFrom:{}",msg.getFrom()); //发件人,=?gb18030?B?0e6yxcvJ?= <abc@qq.com>
MimeMessage message = (MimeMessage) msg;
Multipart multipart = (Multipart) message.getContent();
for (int j = 0; j < multipart.getCount(); j++) {
BodyPart bodyPart = multipart.getBodyPart(j);
//如果是附件,写入到指定位置
if (bodyPart.isMimeType("application/octet-stream")) { //"text/plain","text/html"
DataSource source = bodyPart.getDataHandler().getDataSource();
String fileDir=baseDir+"\\" + source.getName(); //拼接附件名
try (InputStream in = source.getInputStream();OutputStream out = new FileOutputStream(fileDir)){
byte[] bytes = new byte[1024];
while (in.read(bytes) != -1){
out.write(bytes);
}
}catch (Exception e){
log.error("获取邮件getInputStream或 创建写入流错误,{}",e);
}
}
}
}
// 关闭资源
folder.close(false);
store.close();
}
// 执行
public static void main(String[] args) {
MailRecive server = new MailRecive();
try {
server.mailRecive();
} catch (Exception e) {
log.warn("邮件服务异常:{}", e);
}
}
}