赞
踩
项目需求是完成某些业务后发送smtp邮件通知用户
直接引入对应的springboot starter,这样就不用管版本问题了
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
也可以单独引入javax.mail依赖
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
注意,如果是 SpringBoot 3.0
以上版本就要改成jakarta.mail
, SpringBoot 3.0
以上版本 弃用Java EE
改用 Jakarta EE
了!本质上是没什么区别的,换个名字,api也基本一致
<!-- https://mvnrepository.com/artifact/com.sun.mail/jakarta.mail -->
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>jakarta.mail</artifactId>
<version>2.0.0</version>
</dependency>
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Slf4j
@Data
@Component
@RequiredArgsConstructor
public class EmailSender {
// 具体配置从配置文件引入
private final SmtpConfigProp smtpConfigProp;
private final SystemAlertEmailConfigProp systemAlertEmailConfigProp;
/**
* @param receivingAddresses like "xxxx@yy.com,xxxx@zz.com"
*/
public void send(String receivingAddresses, String subject, String content) {
// 先配置smtp的ip和端口
Properties properties = System.getProperties();
properties.put("mail.smtp.host", smtpConfigProp.getHost());
properties.put("mail.smtp.port", smtpConfigProp.getPort());
// 创建会话
Session session = Session.getDefaultInstance(properties);
// 创建消息主体
MimeMessage message = new MimeMessage(session);
try {
// 发送邮箱
message.setFrom(new InternetAddress(systemAlertEmailConfigProp.getSenderAddress()));
// 接收邮箱地址列表
message.setRecipients(Message.RecipientType.TO, receivingAddresses);
// 邮件标题
message.setSubject(String.format(systemAlertEmailConfigProp.getSubject(), subject));
// 邮件内容,这里是文本/html格式的内容
message.setContent(content, "text/html");
// send message
Transport.send(message);
log.info("Sending email:{} to {} via smtp", subject, receivingAddresses);
} catch (Exception e) {
log.error("Failed to send email.");
e.printStackTrace();
}
}
}
参考图片来源:网络
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。