邮箱协议端口
使用jakarta库发送邮件
示例
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.xin_admin.common.Result;
import com.xin_admin.security.AuthAnnotation;
import jakarta.activation.DataHandler;
import jakarta.activation.DataSource;
import jakarta.activation.FileDataSource;
import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeBodyPart;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.internet.MimeMultipart;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.yaml.snakeyaml.Yaml;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;
/**
* @author:aloha
* @create: 2023-08-09 09:26
* @Description: 发邮件
*/
@AuthAnnotation(needRole = "admin")
@Slf4j
@RestController
public class MailSend {
private static String host;
private static String port;
private static String username;
private static String password;
private String to;
private String subject;
private String text;
private String filename;
static {
Yaml yaml = new Yaml();
try(InputStream in = MailSend.class.getClassLoader().getResourceAsStream("config/mail-config.yml")){
Map map =(Map<String,Object>) yaml.load(in);
Map<String,String> config = (Map<String,String>) map.get("send");
host=config.get("host");
port=config.get("port");
username=config.get("username");
password=config.get("password");
}catch(Exception e){
log.warn(":{}",e);
}
}
@PostMapping("/mail")
public Result mailSend(@RequestBody String body) {
JSONObject obj = JSON.parseObject(body);
to = obj.getString("to");
subject=obj.getString("subject");
text=obj.getString("text");
filename=obj.getString("filename");
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.port", port);
properties.setProperty("mail.smtp.auth", "true");
// properties.setProperty("mail.smtp.starttls.enable", "true"); //公司加密端口被禁了,
Session session = Session.getInstance(properties, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
Result result=new Result();
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(text);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
//如有附件地址, 发送附件
if (filename != null) {
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
}
message.setContent(multipart);
Transport.send(message);
result.setCode(200);
} catch (Exception e) {
e.printStackTrace();
result.setCode(500);
result.setMsg(e.getMessage());
}
return result;
}
}
使用jakarta 接收邮件
安装依赖
前三个是接收邮件用的,其他的酌情安装
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: "[email protected]"
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?= <[email protected]>
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);
}
}
}
标签:java,String,jakarta,new,收发,private,import,mail,邮件
From: https://www.cnblogs.com/wakevol/p/17617597.html