Spring Boot 邮件发送

本文介绍如何配置QQ邮箱的POP3/SMTP服务,以便在SpringBoot应用中实现邮件发送功能。详细说明了Maven依赖添加、application.properties配置及邮件发送服务的实现,并提供了异常处理的常见原因。

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

开启QQ邮箱POP3/SMTP服务

在这里插入图片描述
在这里插入图片描述

添加Maven依赖

        <!-- 邮件发送 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

配置application.properties

spring.mail.password为邮箱的十六位授权码,不是邮箱的登录密码。

#-----------------------------------------Spring Boot 邮件发送---------------
spring.mail.host=smtp.qq.com
spring.mail.port=465
spring.mail.username=XXX@qq.com
spring.mail.password=aaaabbbbccccdddd
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.debug=true

邮件发送服务

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

@Component
public class MailService {
    // JavaMailSender是Spring Boot在MailSenderPropertiesConfiguration类中配置好的,该类在Mail自动配置类MailSenderAutoConfiguration中导入
    @Autowired
    JavaMailSender javaMailSender;

    /**
     *
     * @param from 邮件发送者
     * @param to 收件人
     * @param cc 抄送人
     * @param subject 邮件主题
     * @param content 邮件内容
     */
    public void sendSimpleMail(String from, String to, String cc, String subject, String content) {
        SimpleMailMessage simpMsg = new SimpleMailMessage();
        simpMsg.setFrom(from);
        simpMsg.setTo(to);
        simpMsg.setCc(cc);
        simpMsg.setSubject(subject);
        simpMsg.setText(content);
        javaMailSender.send(simpMsg);
    }
}

发送邮件测试

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

@RunWith(SpringRunner.class)
@SpringBootTest
public class SendmailApplicationTests {
    @Autowired
    MailService mailService;
    @Test
    public void sendSimpleMail() {
        mailService.sendSimpleMail("from@qq.com",
                "to@qq.com",
                "cc@qq.com",
                "测试邮件主题",
                "测试邮件内容");
    }
}

异常处理

org.springframework.mail.MailAuthenticationException: Authentication failed; nested exception is javax.mail.AuthenticationFailedException: 535 Error: ÇëʹÓÃÊÚȨÂëµÇ¼¡£ÏêÇéÇë¿
  1. 没有配置spring.mail.password
  2. spring.mail.password填写成登录密码而不是授权码
  3. 十六位授权码填写在配置文件中时,它们之间不应该有空格
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值