使用 Spring Boot 发送邮件

发送邮件是网站的必备功能之一,用户注册验证、忘记密码或者发送营销信息。Spring Boot使用 spring-boot-starter-mail,让邮件发送的业务更加简洁和完善。

邮件相关协议内容如下:
  • SMTP 协议:发送邮件协议;
  • POP3 协议:获取邮件协议;
  • IMAP:接收信息的高级协议;
  • MIME:邮件拓展内容格式:信息格式,附件格式。

本人以qq邮箱为例。第一步肯定是要让qq邮箱 开通POP3 /SMTP 服务,因为我们项目中有用到,否则就会因没有授权而抛错。

使用 Spring Boot 发送邮件_第1张图片
授权页面01[图片上传中...(TIM截图20171206112905.png-255fe0-1512531023545-0)]

使用 Spring Boot 发送邮件_第2张图片
授权页面02

这其中会产生一个授权码,要记下来,下面要用。
好,接下来可以写代码了。

1.添加依赖

     
        org.springframework.boot
        spring-boot-starter-mail
     

2.配置application.yml文件
spring:
  application:
    name: mail
  mail:
    host: smtp.qq.com
    username: [email protected]
    password: you-password  #开启 POP3 之后设置的客户端授权密码
    default-encoding: UTF-8
    properties:
      mail:
        smtp:
          auth: true #这地方必须加,不然会授权失败,提示350错误
          starttls:
            enable: true
            required: true
3.新建服务类

MailService .java


/**
 * 发送邮件
 */
public interface MailService {

    public void sendSimpleMail(String to, String subject, String content);

    public void sendHtmlMail(String to, String subject, String content);

    public void sendAttachmentsMail(String to, String subject, String content, String filePath);

    public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId);
}

MailServiceImpl.java


import com.sqlb.service.MailService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

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

@Component
@Slf4j
public class MailServiceImpl implements MailService {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;


    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);

        try {
            mailSender.send(message);
            log.info("简单邮件已经发送。");
        } catch (Exception e) {
            log.error("发送简单邮件时发生异常!", e);
        }
    }

    @Override
    public void sendHtmlMail(String to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();

        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            mailSender.send(message);
            log.info("html邮件发送成功");
        } catch (MessagingException e) {
            log.error("发送html邮件时发生异常!", e);
        }
    }

    @Override
    public void sendAttachmentsMail(String to, String subject, String content, String filePath) {
        MimeMessage message = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = file.getFilename();
            helper.addAttachment(fileName, file);
            //helper.addAttachment("test"+fileName, file);

            mailSender.send(message);
            log.info("带附件的邮件已经发送。");
        } catch (MessagingException e) {
            log.error("发送带附件的邮件时发生异常!", e);
        }
    }

    @Override
    public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId) {
        MimeMessage message = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource res = new FileSystemResource(new File(rscPath));
            helper.addInline(rscId, res);

            mailSender.send(message);
            log.info("嵌入静态资源的邮件已经发送。");
        } catch (MessagingException e) {
            log.error("发送嵌入静态资源的邮件时发生异常!", e);
        }
    }
}
4.接下来就是测试了

import com.sqlb.service.MailService;
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 org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import static org.junit.Assert.*;


@SpringBootTest
@RunWith(SpringRunner.class)
public class MailServiceImplTest {

    @Autowired
    private MailService mailService;

    @Autowired
    private TemplateEngine templateEngine;

    @Test
    public void sendSimpleMail() throws Exception {
        mailService.sendSimpleMail("receiver-email","这是一封简单邮件","大家好,这是我的第一封邮件!");
    }

    @Test
    public void sendHtmlMail() throws Exception {
        String content="\n" +
                "\n" +
                "    

hello world ! 这是一封html邮件!

\n" + "\n" + ""; mailService.sendHtmlMail("[email protected]","这是一封HTML邮件",content); } @Test public void sendAttachmentsMail() throws Exception { String filePath="e:\\temp\\fastdfs-client-java-5.0.0.jar"; mailService.sendAttachmentsMail("[email protected]", "主题:带附件的邮件", "有附件,请查收!", filePath); } @Test public void sendInlineResourceMail() throws Exception { String rscId = "neo006"; String content="这是有图片的邮件:"; String imgPath = "e:\\temp\\weixin.jpg"; mailService.sendInlineResourceMail("[email protected]", "主题:这是有图片的邮件", content, imgPath, rscId); } @Test public void sendTemplateMail() { //创建邮件正文 Context context = new Context(); context.setVariable("id", "006"); String emailContent = templateEngine.process("emailTemplate", context); mailService.sendHtmlMail("[email protected]","主题:这是模板邮件",emailContent); } }

ok 效果如下,大功告成!


使用 Spring Boot 发送邮件_第3张图片

你可能感兴趣的:(使用 Spring Boot 发送邮件)