Spring Boot集成JavaMailSender发送电子邮件

导读:本篇文章讲解 Spring Boot集成JavaMailSender发送电子邮件,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

Spring Boot集成电子邮件发送功能


一、项目配置

1. 引入依赖

 <!--发送邮件依赖-->
  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-mail</artifactId>
  </dependency>

2. 开启邮箱的SMTP协议

本文以QQ邮箱为例进行叙述。
在这里插入图片描述

3. 配置文件添加相关配置

#编码格式
spring.mail.default-encoding=UTF-8
#配置STMP服务器,此处使用QQ邮箱
spring.mail.host=smtp.qq.com
#发送邮件的用户名及授权码,注意不是登陆密码
spring.mail.username=xxxxxxx@qq.com
spring.mail.password=xxxxxx
#使用的协议
spring.mail.protocol=smtp

二、发送简单文本邮件

MailServiceImpl
代码如下(示例):

@Service
public class MailServiceImpl implements MailService {
    private Logger logger =  LoggerFactory.getLogger(MailServiceImpl.class);

    @Autowired
    JavaMailSender javaMailSender;

    @Override
    public void sendSimplMail() {
        SimpleMailMessage message = new SimpleMailMessage();
        //发件人
        message.setFrom("xxxxxx@qq.com");
        //收件人
        message.setTo("xxxxxxx@qq.com");
        //邮件标题
        message.setSubject("Come on!");
        //邮件内容
        message.setText("加油");
        javaMailSender.send(message);
        logger.info("邮件发送成功");
    }
 }

三、发送附件邮件

MailServiceImpl
代码如下(示例):

@Service
public class MailServiceImpl implements MailService {
    private Logger logger =  LoggerFactory.getLogger(MailServiceImpl.class);

    @Autowired
    JavaMailSender javaMailSender;
	@Override
    public void sendComplexMail(){
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try{
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
            try{
                //发件人
                mimeMessageHelper.setFrom("xxxxxx@qq.com");
                //收件人
                mimeMessageHelper.setTo("xxxxxx@qq.com");
                //邮件标题
                mimeMessageHelper.setSubject("Happy");

                mimeMessageHelper.addInline("dog.gif",new File("D:/dog.gif"));
                mimeMessageHelper.addAttachment("test.doc",new File("D:/test.doc"));
                javaMailSender.send(mimeMessage);
                 logger.info("复杂邮件发送成功");
            } catch (MessagingException e) {
                logger.warn("邮件发送失败=====>"+e.getMessage());
            }
        } catch (MessagingException e) {
            e.printStackTrace();
        }


    }
}

三、邮件功能工具类

  1. MailVo 实体类
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.File;
import java.util.Date;

@AllArgsConstructor
@NoArgsConstructor
@Data
public class MailVo {
    private String id;  //邮件id
    private String from;  //邮件发送人
    private String to;  //邮件接收人(多个邮箱则用逗号","隔开)
    private String subject;  //邮件主题
    private String text;  //邮件内容
    private Date sentDate;  //发送时间
    private String cc;  //抄送(多个邮箱则用逗号","隔开)
    private String bcc;  //密送(多个邮箱则用逗号","隔开)
    private String status;  //状态
    private String error;  //报错信息

    private File[] files;  //邮件附件
}
  1. MailUtil 工具类
import com.example.cabledisp.vo.MailVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.Date;

@Component
public class MailUtil {
    private static Logger logger = LoggerFactory.getLogger(MailUtil.class);//提供日志类

    @Autowired
    private ApplicationContext applicationContext;

    private static JavaMailSender mailSender;

    @PostConstruct
    public void init(){
        MailUtil.mailSender = applicationContext.getBean(JavaMailSender.class);
    }

    /**
     * 邮箱信息检查,可根据实际需求更改
     * @param mailVo
     * */
    public static void checkMail(MailVo mailVo) {
        if (StringUtils.isEmpty(mailVo.getTo())) {
            throw new RuntimeException("邮件收信人不能为空");
        }
        if (StringUtils.isEmpty(mailVo.getSubject())) {
            throw new RuntimeException("邮件主题不能为空");
        }
        if (StringUtils.isEmpty(mailVo.getText())) {
            throw new RuntimeException("邮件内容不能为空");
        }
    }

    /**
     * 构建复杂邮件信息类
     * 附件邮件部分可优化
     *
     * @param mailVo
     * */
    public static void sendMimeMail(MailVo mailVo) {
        try {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mailSender.createMimeMessage(), true); //true表示支持复杂类型
            messageHelper.setFrom(mailVo.getFrom()); //邮件发信人
            messageHelper.setTo(mailVo.getTo().split(",")); //邮件收信人
            messageHelper.setSubject(mailVo.getSubject()); //邮件主题
            messageHelper.setText(mailVo.getText()); //邮件内容
            if (!StringUtils.isEmpty(mailVo.getCc())) { //抄送
                messageHelper.setCc(mailVo.getCc().split(","));
            }
            if (!StringUtils.isEmpty(mailVo.getBcc())) { //密送
                messageHelper.setCc(mailVo.getBcc().split(","));
            }
            if (mailVo.getFiles() != null) { /添加邮件附件
                for (File file : mailVo.getFiles()) {
                    messageHelper.addAttachment(file.getName(), file);
                }
            }
            if (StringUtils.isEmpty(mailVo.getSentDate())) { //发送时间
                mailVo.setSentDate(new Date());
                messageHelper.setSentDate(mailVo.getSentDate());
            }
            System.out.println(messageHelper.getMimeMessage());
            mailSender.send(messageHelper.getMimeMessage()); //正式发送邮件
            mailVo.setStatus("ok");
            logger.info("发送邮件成功:{}->{}", mailVo.getFrom(), mailVo.getTo());
        } catch (Exception e) {
            throw new RuntimeException(e); //发送失败
        }
    }


    /**
     *  保存邮件,未完成
     *  可根据需求决定是否启用
     * @param mailVo
     * */
    public MailVo saveMail(MailVo mailVo) {
        //将邮件保存到数据库..
        return mailVo;
    }

}
  1. 测试
import com.example.cabledisp.vo.MailVo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.File;
import java.util.Date;


@SpringBootTest
@RunWith(SpringRunner.class)
public class MailServiceTest {
    @Autowired
    MailService mailService;

    @Test
    public void sendComplexMail() {
        mailService.sendComplexMail();
    }

    @Test
    public void Send() {
        File[] files = new File[1];
        MailVo mailVo = new MailVo();

        mailVo.setFrom("xxxxx@qq.com");
        mailVo.setTo("xxxxx@qq.com");
        mailVo.setSentDate(new Date());
        mailVo.setSubject("Mail工具类");
        mailVo.setText("Mail工具类");
        files[0] =new File("D:/test.doc");
        mailVo.setFiles(files);
        mailService.send(mailVo);
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/119767.html

(0)
seven_的头像seven_bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!