Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

第 33 章 Spring boot with Email

目录

33.1. jakarta.mail
33.2. spring-boot-starter-mail
33.2.1. Maven
33.2.2. Resource
33.2.3. POJO
33.2.4. RestController
33.2.5. Test
33.3. 用法详解
33.3.1. 开启 DEBUG
33.3.2. SMTP SSL 配置
33.3.3. SMTP TLS 配置
33.3.4. 发送文本邮件
33.3.5. 发送HTML邮件
33.3.6. 发送带附件的邮件

33.1. jakarta.mail

原生 jakarta.mail 例子

		
        <!-- Source: https://mvnrepository.com/artifact/com.sun.mail/jakarta.mail -->
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>jakarta.mail</artifactId>
            <version>2.0.2</version>
            <scope>compile</scope>
        </dependency>		
		
		
			
package cn.netkiller.component;

import jakarta.activation.DataHandler;
import jakarta.activation.URLDataSource;
import jakarta.mail.*;
import jakarta.mail.internet.*;
import org.springframework.resilience.annotation.Retryable;
import org.springframework.stereotype.Component;

import java.net.URL;
import java.util.*;

@Component
public class EmailComponent {

    protected final Map<String, SequencedMap<String, String>> emailAccount = new HashMap<String, SequencedMap<String, String>>() {{
        put("outlook", new LinkedHashMap<>() {{
            put("host", "smtp-mail.outlook.com");
            put("port", "587");
            put("auth", "true");
            put("username", "netkiller@outlook.com");
            put("password", "5BtS7vR4");
        }});
        put("exmail", new LinkedHashMap<>() {{
            put("host", "smtp.exmail.qq.com");
            put("port", "465");
            put("auth", "true");
            put("username", "neo@netkiller.cn");
            put("password", "h2yVh5XJ2vyg972i");
        }});
    }};

    @Retryable(
            value = {MessagingException.class}
    )
    public void sendEmailWithAttachment(String to, String subject, String body, String filePath) throws Exception {

        SequencedMap<String, String> account = emailAccount.get("outlook");
// 配置SMTP服务器
        Properties properties = new Properties();
        properties.put("mail.smtp.host", account.get("host")); // 替换为SMTP服务器地址
        properties.put("mail.smtp.port", account.get("port"));
        properties.put("mail.smtp.auth", account.get("auth"));
        properties.put("mail.user", account.get("username"));
        properties.put("mail.password", account.get("password"));
// TLS
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.starttls.required", "true");
// SSL
//        properties.put("mail.transport.protocol", "smtps");
//        properties.put("mail.smtp.ssl.enable", "true");

        properties.put("mail.smtp.ssl.protocols", "TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;");
        properties.put("mail.smtp.ssl.ciphersuites", "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA256:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:RC4-MD5:RC4-SHA;");
        properties.put("mail.smtp.ssl.trust", "*"); // 信任所有证书
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.socketFactory.fallback", "false");


// 创建会话
        Session session = Session.getInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(account.get("username"), account.get("password")); // 替换为邮箱和授权码
            }
        });
        session.setDebug(true);

// 创建邮件
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(account.get("username")));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);

// 设置邮件内容和附件
        Multipart multipart = new MimeMultipart();

// 添加文本内容
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText(body);
        multipart.addBodyPart(textPart);

// 添加附件
//        MimeBodyPart attachmentPart = new MimeBodyPart();
//        attachmentPart.attachFile(filePath);
//        multipart.addBodyPart(attachmentPart);

        // URL 网络附件
        String url = "https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png";
        MimeBodyPart attachmentPart = new MimeBodyPart();
        attachmentPart.setDataHandler(new DataHandler(new URLDataSource(new URL(url))));
        attachmentPart.setFileName(MimeUtility.encodeText("logo.png"));
        multipart.addBodyPart(attachmentPart);

        message.setContent(multipart);
// 发送邮件
        Transport.send(message);
    }
}