SpringBoot集成发邮件功能

pom文件添加依赖

<!--邮件依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
            <version>2.1.5.RELEASE</version>
        </dependency>

application.properties配置文件配置

# MailProperties
#添加邮箱的配置。**注意!**使用qq邮箱时,密码是qq邮箱开启POP/SMTP后的授权码,不是邮箱本身的密码
# MailProperties
spring.mail.host=smtp.qq.com
spring.mail.port=465
spring.mail.username=xxxxxx@qq.com
spring.mail.password=我是qq邮箱授权码
#加密的协议
spring.mail.protocol=smtps
#使用ssl安全连接
spring.mail.properties.mail.smtp.ssl.enable=true

编写发邮件的工具类
util.MailCLient

@Component
public class MailClient {
    //记录日志
    private static final Logger logger = LoggerFactory.getLogger(MailClient.class);

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;   //发件人

    //发送邮件,参数:发给谁,主题,内容
    public void sendMail(String to, String subject, String content) {
        try {
            //模板
            MimeMessage message = mailSender.createMimeMessage();
            //使用帮助类构建详细的message内容
            MimeMessageHelper helper = new MimeMessageHelper(message);
            helper.setFrom(from);//发件人
            helper.setTo(to);    //收件人
            helper.setSubject(subject);  //主题
            helper.setText(content, true);//内容,支持html文本
            mailSender.send(helper.getMimeMessage());//发送
        } catch (MessagingException e) {
            logger.error("发送邮件失败:" + e.getMessage());
        }
    }
}

编写测试类

@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)
public class MailTests {
    @Autowired
    private MailClient mailClient;
    @Autowired
    private TemplateEngine templateEngine;

    @Test
    public void testTextMail() {
        mailClient.sendMail("xxxxxx@qqcom", "TEST", "Welcome.");
    }

    @Test
    public void testHtmlMail() {
        Context context = new Context();
        context.setVariable("username", "sunday");

        String content = templateEngine.process("/mail/demo", context);
        System.out.println(content);

        mailClient.sendMail("xxxxxx@qq.com", "HTML", content);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值