利用Spring Boot(SMTP)发送邮件

利用Spring Boot发送邮件,以163邮箱为例

1.添加Maven包依赖,在pom.xml文件中添加如下依赖

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

2.在application.properties文件中添加如下代码

spring.mail.host=smtp.163.com
spring.mail.username=***@163.com
spring.mail.password=***
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

注意spring_mail_password那里的密码是授权密码,而不是登陆密码,授权密码在邮箱设置,pop3/smtp处可以设置

3.测试代码

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("163")
public class My163MailTest {
    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String username;

    @Test
    public void testSendSimple() {
        SimpleMailMessage message = new SimpleMailMessage();
//        message.setFrom(username);
        message.setFrom("***@163.com");//发送邮箱,也就是你的邮箱,或者可用上面的代码直接获取
        message.setTo("###@qq.com");
        message.setSubject("love");
        message.setText("你好");
        javaMailSender.send(message);
    }
}

注意点:此处连接163邮箱发送邮件,有时回报554 DT:SPM错误,这是网易的反垃圾机制

网易邮箱错误码详情:企业退信的常见问题?-163邮箱常见问题

个人经验:主题,内容不要包含Test,测试等字眼

当天申请的授权码,当天使用该邮箱会一直报这个错误,这点要注意!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值