Springboot实现邮件发送功能(使用QQ邮箱)

Springboot实现邮件发送功能(使用QQ邮箱)

1. 邮箱准备

登录QQ邮箱,进入账户设置,开启POP3和IMAP服务,然后点击生成授权码(一般需要手机发送短信获取授权码,需要自己单独保存)获取邮箱授权。

Springboot实现邮件发送功能(使用QQ邮箱)_第1张图片

2. 配置

依赖引入

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-mailartifactId>
dependency>
<dependency>
    <groupId>org.projectlombokgroupId>
    <artifactId>lombokartifactId>
    <optional>trueoptional>
dependency>
<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-testartifactId>
    <scope>testscope>
dependency>

application.yaml文件配置

spring:
  mail:
    username: [email protected] # 发送人邮箱
    password: xxxxx # 邮箱授权码(上面获取到的)
    host: smtp.qq.com # 邮件服务器,163邮箱就是smtp.163.com
    protocol: smtp # 协议,可以不配,默认就是这个

3. 编写发送邮件代码

  1. 这里封装了一个Email类,储存邮件信息
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class Email implements Serializable {

    /**
     * 邮件接收方,可多人
     */
    private String[] tos;
    /**
     * 邮件主题
     */
    private String subject;
    /**
     * 邮件内容
     */
    private String content;
}
  1. 编写MailUtils 邮件发送类
@Component
public class MailUtils {
    @Value("${spring.mail.username}")
    private String from;
    @Autowired
    private JavaMailSender mailSender;
    
    public R sendCommonEmail(Email email) {
        //创建简单邮件消息
        SimpleMailMessage message = new SimpleMailMessage();
        //发送人
        message.setFrom(from);
        //接受人
        message.setTo(email.getTos());
        //邮件标题
        message.setSubject(email.getSubject());
        //邮件内容
        message.setText(email.getContent());
        try {
            mailSender.send(message);
            return R.success("发送普通邮件成功");
        } catch (MailException e) {
            e.printStackTrace();
            return R.failure("普通邮件方失败");
        }
    }
    //发送内容为html
    public R sendEmailUseHtml(Email email) {
        //创建一个MIME消息
        MimeMessage message = mailSender.createMimeMessage();
        try {

            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message, true);
            //发送人
            mimeMessageHelper.setFrom(from);
            //接收人
            mimeMessageHelper.setTo(email.getTos());
            //邮件主题
            mimeMessageHelper.setSubject(email.getSubject());
            //邮件内容 true代表内容是html
            mimeMessageHelper.setText(email.getContent(), true);
            mailSender.send(message);
            return R.success("发送普通邮件成功");
        } catch (MessagingException e) {
            e.printStackTrace();
            return R.failure("普通邮件方失败");
        }
    }
    // 带附件的邮件发送
    public R enclosureEmail(Email email, File file) {
        //创建一个MINE消息
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            //发送人
            helper.setFrom(from);
            //接收人
            helper.setTo(email.getTos());
            //邮件主题
            helper.setSubject(email.getSubject());
            //邮件内容   true 表示带有附件或html
            helper.setText(email.getContent(), true);

            String fileName = file.getName();
            //添加附件
            helper.addAttachment(fileName, file);
            mailSender.send(message);
            return R.success("附件邮件成功");
        } catch (MessagingException e) {
            e.printStackTrace();
            return R.success("附件邮件发送失败" + e.getMessage());
        }
    }
}

Tips:
Spring为我们创建并管理了一个JavaMailSender,因此直接注入就行,但是必须将这个类加上@Component注解交由Spring管理。

  1. 编写测试类进行邮件发送测试
@SpringBootTest
public class SendMailTests {
    @Autowired
    MailUtils mailUtils;
    @Test
    public void testCommonEmail(){
        Email email = new Email();
        email.setTos(new String[]{"[email protected]"})
                .setSubject("test")
                .setContent("测试内容");

        R r = mailUtils.sendCommonEmail(email);
        System.out.println(r);
    }

    @Test
    public void testSendEmailUseHtml(){
        Email email = new Email();
        String content = "\n" +
                "    

标题

\n"
+ "

测试一下发送html

\n"
+ ""; email.setTos(new String[]{"[email protected]"}) .setSubject("test html email") .setContent(content); R r = mailUtils.sendEmailUseHtml(email); System.out.println(r); } @Test public void test(){ Email email = new Email(); email.setTos(new String[]{"[email protected]"}) .setSubject("邮件测试") .setContent("test email with attachment"); File file = new File("F:\\test.pdf"); R r = mailUtils.enclosureEmail(email,file); System.out.println(r); } }

备注:统一封装结果返回类R

@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true) // lombok支持:开启链式调用
public class R <T> implements Serializable {

    // 状态码
    private int code;
    // 提示信息
    private String message;
    // 返回数据
    private T data;

    public R(int code, String message){
        this.code = code;
        this.message = message;
    }

    public static <T> R<T> failure(String message){
        return new R<>(400, message);
    }
    public static <T> R<T> failure(){

        return new R<>(400, "失败");
    }

    public static <T> R<T> success(){
        return new R<>(200, "成功");
    }
    public static <T> R<T> success(String message){
        return new R<>(200, message);
    }
}

你可能感兴趣的:(springboot,spring,boot,java)