浅析SpringBoot如何使用JavaMailSender发送邮件及遇到问题501 mail from address must be same as authorization user

  Spring提供了非常好用的JavaMailSender接口实现邮件发送。在Spring Boot的Starter模块中也为此提供了自动化配置。下面通过实例看看如何在Spring Boot中使用JavaMailSender发送邮件。

一、简单邮件发送

1、导入依赖

  在Spring Boot的工程中的pom.xml中引入spring-boot-starter-mail依赖

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

2、填写邮件配置

  如其他自动化配置模块一样,在完成了依赖引入之后,只需要在application.properties中配置相应的属性内容。

spring: 
  mail:
    host: smtp.exmail.qq.com   // 邮件服务
    username: ***   // 使用哪个邮箱发送
    password: ***   // 邮箱密码
    port: 465
    protocol: smtp
    properties:
      mail:
        smtp:
          auth: true
          ssl:
            enable: true
          starttls:
            enable: true

3、编写邮件发送代码

package com.opengauss.exam.common.service;

import com.opengauss.exam.common.ExamMail;
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.Service;

@Service
public class EmailService {
    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String emailFrom;   // 从配置文件取发件方

    public void sendSimpleMail(ExamMail examMail) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(emailFrom);  // 发件方
        message.setTo(examMail.getRecipient());  // 收件方
        message.setSubject(examMail.getSubject()); // 邮件主题
        message.setText(examMail.getContent());  // 邮件内容
        javaMailSender.send(message);
    }
}
package com.opengauss.exam.common;

import lombok.Data;

@Data
public class ExamMail {
    private String subject;
    private String recipient;
    private String content;
}

  这样就可以实现简单邮件发送了。

二、发送附件

  在上面单元测试中加入如下测试用例(通过MimeMessageHelper来发送一封带有附件的邮件)

@Test
public void sendAttachmentsMail() throws Exception {
    MimeMessage mimeMessage = mailSender.createMimeMessage();

    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
    helper.setFrom("***");
    helper.setTo("***");
    helper.setSubject("主题:***");
    helper.setText("***");

    FileSystemResource file = new FileSystemResource(new File("weixin.jpg"));
    helper.addAttachment("附件-1.jpg", file);
    helper.addAttachment("附件-2.jpg", file);

    mailSender.send(mimeMessage);
}

三、遇到问题501 mail from address must be same as authorization user

  这里在测试的时候,遇到这个报错。原因其实很简单,就是emailFrom我随便写的一个邮箱,而不是我配置的那个邮箱,所以就报错:501 mail from address must be same as authorization user,意思也很好理解。

  解决方法就是:将 emailFrom 改成配置文件里的那个邮箱即可。

  其他比如通过模板发送一份好看的邮件,以后有时间再写。

原文地址:https://www.cnblogs.com/goloving/p/14912744.html