SpringBoot发送简单文本邮件

Posted QW-lzm

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot发送简单文本邮件相关的知识,希望对你有一定的参考价值。

1、pom.xml添加 spring-boot-starter-mail 依赖

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

2、application.properties中添加发送邮件的配置

spring.mail.host=smtp.163.com
spring.mail.port=25
spring.mail.username=发送邮件的账号@163.com
spring.mail.password=授权码
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

mail.fromMail.addr=发送邮件的账号@163.com

3、发送邮件的接口

package com.st.service;

public interface MailService {

    public void sendSimpleMail(String to, String subject, String content);
    
}

4、发送邮件的实现类

package com.st.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.st.service.MailService;

@Service
@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);
        }
    }

}

5、测试类

package com.st;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.st.service.MailService;


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

    @Autowired
    private MailService mailService;

    //生成6位随机验证码
    int randNum = 1 + (int)(Math.random() * ((999999 - 1) + 1));
    
    @Test
    public void testSimpleMail() throws Exception {
        mailService.sendSimpleMail("接收邮件的账号@qq.com", "开发邮件发送功能", "验证码:"+randNum);
    }

}

 

以上是关于SpringBoot发送简单文本邮件的主要内容,如果未能解决你的问题,请参考以下文章

我应该如何使用 Outlook 发送代码片段?

SpringBoot实战一:发送邮件

用python实现自动发邮件的功能

springboot自定义文本/附件/html模板邮件发送

SpringBoot 实现发送简单邮件

SpringBoot 实现发送简单邮件