SpringBoot邮件发送(QQ邮箱)

1,导入mail依赖

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

2.在properties配置邮箱

# 发件人QQ号
[email protected]
# QQ邮箱授权码
spring.mail.password=xxxxxxxxxxxxxxx
# 主机
spring.mail.host=smtp.qq.com
# qq邮箱需要开启安全连接
spring.mail.properties.mail.stmp.ssl.enable=true

3.测试类代码

package com.peng;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@SpringBootTest
class SpringbootSecurityApplicationTests {
    @Autowired
    private JavaMailSenderImpl javaMailSender;
    @Test
    void contextLoads() {
        //简单邮件
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("灵异事件");//主题
        message.setText("九十岁老太为何起死回生,数百头母猪为何半夜惨叫。女生宿舍为何频频失窃,超市方便面为何惨遭黑手。在达一切的背后,是人性的扭曲、还是道德的沦丧。敬请观注鹏哥解说!!");
        message.setTo("[email protected]");
        message.setFrom("[email protected]");
        javaMailSender.send(message);
    }
    @Test
    void test() throws MessagingException {
        //复杂邮件
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);//组装,开启之后可以添加附件
        helper.setSubject("ok");//主题
        helper.setText("九十岁老太为何起死回生,数百头母猪为何半夜惨叫。女生宿舍为何频频失窃,超市方便面为何惨遭黑手。在达一切的背后,是人性的扭曲、还是道德的沦丧。敬请观注鹏哥解说!!");
        helper.addAttachment("按什么名称发送.后缀",new File("文件路径"));
        helper.setTo("收件人");
        helper.setFrom("发件人");
        javaMailSender.send(mimeMessage);
    }

}

你可能感兴趣的:(SpringBoot,spring,boot,java,spring)