美文网首页SpringBoot
springboot实现邮件发送

springboot实现邮件发送

作者: 意识流丶 | 来源:发表于2017-03-05 19:24 被阅读2161次

Spring提供了非常好用的JavaMailSender接口实现邮件发送。在Spring Boot的Starter模块中也为此提供了自动化配置。
首先先引入邮件发送所需要的依赖
版本1.5.1(Jan 30, 2017更新的)

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

application.properties中配置相应的属性内容。我把属性文件改为yaml文件
host: smtp.qq.com是发件人使用发邮件的电子信箱服务器,如果是163邮箱就改成host: smtp.163.com

spring:
    mail:
       host: smtp.qq.com
       username:  发送方邮箱
       password:  QQ邮箱的话就是发送方的授权码
       properties:
          mail:
            smtp:
              auth: true//这样才能通过验证
              starttls:
                  enable: true
                  required: true

编写邮件发送测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
    @Autowired
    private JavaMailSender javaMailSender;
@Test
    public void sendAttachmentsMail() throws Exception {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom("发送方邮箱");
        helper.setTo("接收方邮箱");
        helper.setSubject("主题:有附件");
        helper.setText("有附件的邮件");
        mailSender.send(mimeMessage);
    }

由于Spring Boot的starter模块提供了自动化配置,所以在引入了spring-boot-starter-mail依赖之后,会根据配置文件中的内容去创建JavaMailSender实例,因此我们可以直接在需要使用的地方直接@Autowired来引入邮件发送对象。

然后运行后可能会出现这个异常
org.springframework.mail.MailAuthenticationException: Authentication failed; nested exception is javax.mail.AuthenticationFailedException: 530 Error: A secure connection is requiered(such as ssl).
More information at http://service.mail.qq.com/cgi-bin/help?id=28
原因:
发送方必须要开启smtp,获取到的授权码,开启方法如下:
http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256

执行测试:


Paste_Image.png

相关文章

网友评论

  • 小西奥:楼主,你应该 把 javaMailSender修为mailSender,而且错误的原因又两个,一个是邮箱没开启smtp,还有一个是没写端口,即在pom中没写授权码和端口
    意识流丶:其实都差不多,还是要开启smtp,不然还是发不了邮件,smtp码是每个邮箱唯一的,在springboot的配置文件中加就好了.
    用mailSender的话代码改成这样是可以的
    @Autowired
    MailSender mailSender;
    @Test
    public void sendAttachmentsMail() throws Exception {

    SimpleMailMessage helper = new SimpleMailMessage();
    helper.setFrom("发送方邮箱");
    helper.setTo("接收方邮箱");
    helper.setSubject("主题:有附件");
    helper.setText("有附件的邮件");
    mailSender.send(helper);
    }

本文标题:springboot实现邮件发送

本文链接:https://www.haomeiwen.com/subject/zvusgttx.html