随笔 - 221  文章 - 0  评论 - 57  阅读 - 162万 

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   玄同太子  阅读(647)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
历史上的今天:
2019-11-28 sed命令常用用法
点击右上角即可分享
微信分享提示