javax.mail/jakarta.mail框架发送smtp邮件

项目需求是完成某些业务后发送smtp邮件通知用户

引入依赖

直接引入对应的springboot starter,这样就不用管版本问题了

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-mailartifactId>
        dependency>

也可以单独引入javax.mail依赖

        <dependency>
            <groupId>com.sun.mailgroupId>
            <artifactId>javax.mailartifactId>
            <version>1.6.2version>
        dependency>

注意,如果是 SpringBoot 3.0 以上版本就要改成jakarta.mail, SpringBoot 3.0以上版本 弃用Java EE 改用 Jakarta EE了!本质上是没什么区别的,换个名字,api也基本一致


<dependency>
    <groupId>com.sun.mailgroupId>
    <artifactId>jakarta.mailartifactId>
    <version>2.0.0version>
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 "[email protected],[email protected]"
     */
    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();
        }

    }

}

javax.mail/jakarta.mail框架发送smtp邮件_第1张图片

参考图片来源:网络

你可能感兴趣的:(spring,boot,java,spring,boot,smtp,邮件,jakarta)