pom.xml依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

properties配置:

spring.mail.host=smtp.qq.com
spring.mail.username=xxx@foxmail.com
spring.mail.password=grwysnaqetdnbhhb
spring.mail.port=465
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.from=${spring.mail.username}
spring.mail.properties.mail.smtp.ssl.enable=true

代码示例:

public class SendMailTest {
    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 简单邮件发送,适合纯文本无附件邮件
     */
    @Test
    public void sendSimpleMail() {
        SimpleMailMessage mail = new SimpleMailMessage();
        mail.setSubject("简单邮件标题" + System.currentTimeMillis());
        mail.setText("简单邮件内容");
        mail.setTo("xxx@meicloud.com");
        mail.setSentDate(new Date());
        javaMailSender.send(mail);
        logger.info("简单发送邮件完成");
    }

    /**
     * 多协议邮件发送,适合带附件和内容为HTML格式的邮件
     * 
     * @throws MessagingException
     */
    @Test
    public void sendMimeMail() throws MessagingException {
        // 待发送的附件
        List<File> attachments = Arrays.asList(new File("D:\\test1.txt"), new File("D:\\test2.txt"));
        String content = "多协议邮件,<a href='http://www.baidu.com'>连接到百度</a>,<span style=\"color: red; font-size: 24px\">红色大字</span>";

        MimeMessage mail = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mail, true);
        helper.setSubject("多协议邮件标题");
        // 设置邮件内容,并标记为HTML格式
        helper.setText(content, true);
        helper.setTo("xxx@meicloud.com");
        for (File file : attachments) {
            helper.addAttachment(file.getName(), file);
        }
        javaMailSender.send(mail);
        logger.info("多协议邮件发送完成");
    }
}

注意:

1、使用QQ邮件作为发件箱时需要开启IMAP/SMTP服务,密码用的是授权码,如下图:

2、使用QQ邮件作为发件箱时,需要指定发件人,可增加mail.smtp.from配置或者消息中指定,与登陆邮箱名一致。

 

posted on 2022-11-28 17:37  玄同太子  阅读(603)  评论(0编辑  收藏  举报