springboot系列12: 邮件发送

今天讲解springboot的spring-boot-starter-mail邮件发送,业务场景:注册验证,忘记密码或者是给用户发送营销信息等。

 

1、pom配置

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

 

2、application.propertis配置邮箱

#邮箱服务器地址
spring.mail.host=smtp.163.com
#用户名
spring.mail.username=z13128600812@163.com
#开通授权码
spring.mail.password=**********
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.auth=true
spring.mail.port=25

mail.fromMail.addr=z13128600812@163.com

 

3、发送邮件服务实现

 

@Component
public class MailServiceImpl implements MailService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JavaMailSender mailSender;

    @Value("${mail.fromMail.addr}")
    private String from;

    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        try {
            mailSender.send(message);
            logger.info("简单邮件已经发送。");
        } catch (Exception e) {
            logger.error("发送简单邮件时发生异常", e);
        }
    }
}

 

4、测试类发送邮件

 

@RunWith(SpringRunner.class)
@SpringBootTest
public class MailServiceTest {

    @Autowired
    private MailService MailService;

    @Test
    public void testSimpleMail() throws Exception {
        MailService.sendSimpleMail("1796969389@qq.com","test simple mail"," hello this is simple mail");
    }
}

 

5、运行结果

 

2020-06-07 23:02:00.365  INFO 5592 --- [           main] com.example.service.MailServiceTest      : Started MailServiceTest in 2.461 seconds (JVM running for 7.097)
2020-06-07 23:02:01.618  INFO 5592 --- [           main] c.example.service.impl.MailServiceImpl   : 简单邮件已经发送。
Disconnected from the target VM, address: '127.0.0.1:15328', transport: 'socket'

 

posted @ 2022-01-13 19:29  IT6889  阅读(43)  评论(0编辑  收藏  举报