SpringBoot 发送邮件功能详解及完整代码示例

SpringBoot 发送邮件功能详解及完整代码示例

  • SprintBoot 实现发送邮件功能很简单,相应的 jar 包已被封装到 starter 中,相应的 pom.xml 文件中添加 starter 依赖:
    SpringBoot 发送邮件功能详解及完整代码示例_第1张图片

  • 目录结构如下:
    SpringBoot 发送邮件功能详解及完整代码示例_第2张图片

  • 配置文件 application.yml 如下:

spring:
  mail:
    host: smtp.qq.com
    username: xxxxxx@qq.com//用于发送邮件的邮箱
    password: xxxxxxxxxxxxxxx//这里是相应邮箱开启POP3/SMTP、IMAP/SMTP服务后生成的授权码
  • QQ邮箱授权码获取如下图:
    SpringBoot 发送邮件功能详解及完整代码示例_第3张图片

  • 发送邮件接口类:SendMailService.java:

//SendMailService.java
package com.example.sprintboot_demo.mail;

import javax.mail.MessagingException;

public interface SendMailService {
    void sendMail() throws MessagingException;
}

  • 发送邮件接口实现类:SendMailServiceImpl.java:
//SendMailServiceImpl.java
package com.example.sprintboot_demo.mail.impl;

import com.example.sprintboot_demo.mail.SendMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.io.File;

@Service
public class SendMailServiceImpl implements SendMailService {

    @Autowired
    private JavaMailSender javaMailSender;

    private String from = "[email protected]";
    private String to = "[email protected]";
    private String subject = "springboot测试邮件";
    private String text = "你好:这是一封测试邮件。请坚持下去。加油!点击访问个人主页\n" +
            "";


    @Override
    public void sendMail() {

        //只能发送文本邮件
//        SimpleMailMessage mailMessage = new SimpleMailMessage();
//        mailMessage.setFrom(from);
//        mailMessage.setTo(to);
//        mailMessage.setSubject(subject);
//        mailMessage.setText(text);
//        javaMailSender.send(mailMessage);

        //发送多媒体邮件
        try {
            MimeMessage message = javaMailSender.createMimeMessage();

            //第二个参数控制着附件上传
            MimeMessageHelper helper = new MimeMessageHelper(message, true);

            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);

            //第二个参数表示以 html 语法解析文本
            helper.setText(text, true);


            File file1 = new File("D:\\aspring\\图片.jpeg");
            File file2 = new File("D:\\aspring\\邮件发送附件.txt");
            File file3 = new File("D:\\aspring\\邮件发送附件.zip");

            //添加附件
            helper.addAttachment("图片.jpeg", file1);
            helper.addAttachment("邮件发送附件.txt", file2);
            helper.addAttachment("邮件发送附件.zip", file3);

            javaMailSender.send(message);

        }catch (Exception e){
            e.printStackTrace();
            return;
        }

    }
}

  • 实现效果如下图所示:
    SpringBoot 发送邮件功能详解及完整代码示例_第4张图片

你可能感兴趣的:(SpringBoot,java,springboot,邮件,spring,boot,springboot发送邮件)