SprongBoot发送邮件(一)发送简单文本邮件HelloWorld

本文详细介绍了如何在SpringBoot项目中配置并使用JavaMailSender发送邮件。从添加依赖、配置属性到实现邮件发送功能,包括使用Junit进行测试的全过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用SpringBoot发送邮件首先要加入依赖:

        <!--发送邮件需要的依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

然后在application.properties中配置以下信息

#发送邮件的协议以及主机,我用的QQ邮箱所以是smtp.qq.com,如果是126邮箱则应该改为smtp.126.com
spring.mail.host=smtp.qq.com
#发送邮箱的邮箱地址
spring.mail.username=824668713@qq.com
#移动客户端授权码(不是登录密码,需要到相应邮箱账户中获取)
spring.mail.password=zxvbyuabergtfg
#编码
spring.mail.default-encoding=UTF-8

然后在SpringBoot项目中新建包service,新建类MailService.java ,在类上面添加注解@Service

@Service
public class MailService {

}

注入JavaMailSender对象

    @Autowired
    private JavaMailSender javaMailSender;

以及注入配置文件中的username作为邮件的发件人

    //注入配置文件中的username
    @Value("${spring.mail.username}")
    private String from;

新建sendSimpleMail(String to, String subject, String content)方法如下:


    /**
     * @param to      邮件收件人
     * @param subject 邮件主题
     * @param content 邮件内容
     */
    public void sendSimpleMail(String to, String subject, String content) {

        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();

        //设置邮件的发件人
        simpleMailMessage.setFrom(from);
        //设置收件人
        simpleMailMessage.setTo(to);
        //设置邮件的主题
        simpleMailMessage.setSubject(subject);
        //设置邮件的内容
        simpleMailMessage.setText(content);

        //通过JavaMailSender对象发送邮件信息
        javaMailSender.send(simpleMailMessage);

    }

使用junit测试:

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

    @Resource
    MailService mailService;

    @Test
    public void sendSimpleMailTest() {
        mailService.sendSimpleMail("824668713@qq.com", "SpringBoot HelloWorld", "HelloWorld!");
    }


}

使用SpringBoot发送简单文本邮件就完成啦!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值