springboot项目发送邮件

最初的发送邮件要用javamail,后来spring提供了JavaMailsender接口简化了代码。springboot更是提供了spring-boot-starter-mail

Spring 的 JavaMailSenderImpl 提供了强大的邮件发送功能,可发送普通文本邮件、带附件邮件、HTML 格式邮件、带图片邮件,设置发送内容编码格式、设置发送人的显示名称。

简述几个概念:

Message 类:定义发送人。收件人。标题。内容。发送时间等信息的创建和解析邮件的核心API

Transport 类:发送邮件的核心 API 类。

Store 类:接收邮件的核心API类。

邮件相关协议内容如下。

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

下图用于演示两帐户相互发送邮件的过程:

亲测代码如下:

引入依赖包



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

   org.springframework.boot
   spring-boot-starter-thymeleaf

定义发送邮件的接口

public interface MailService {

    public void sendSimpleMail(String to, String subject, String content);//简单邮件

    public void sendHtmlMail(String to, String subject, String content);//html邮件

    public void sendAttachmentsMail(String to, String subject, String content, String filePath);//带附件邮件

    public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId);//带静态资源文件(图片)的邮件

}
package com.neo.service.mail;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;

/**
 * 邮件发送: 描述信息
 *
 * @author liyy
 * @date 2018-07-18 14:22
 */
@Component
public class MailServiceImpl implements MailService{

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JavaMailSender mailSender;

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

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

        try {
            mailSender.send(simpleMailMessage);
            logger.info("简单邮件已经发送。");
        } catch (Exception e) {
            logger.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.setSubject(subject);
            helper.setTo(to);
            helper.setText(content);
            helper.setCc("[email protected]");//抄送
            mailSender.send(message);
            logger.info("html邮件已经发送。");
        } catch (MessagingException e) {
            logger.info("html邮件已经发送。");
            e.printStackTrace();
        }

    }

    @Override
    public void sendAttachmentsMail(String to, String subject, String content, String filePath) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setSubject(subject);
            helper.setTo(to);
            helper.setText(content);
            helper.setCc("[email protected]");//抄送
            //添加附件
            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = file.getFilename();
            helper.addAttachment(fileName,file);
            mailSender.send(message);
            logger.info("带附件邮件已经发送。");
        } catch (MessagingException e) {
            logger.info("带附件邮件已经发送。");
            e.printStackTrace();
        }
    }

    @Override
    public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setSubject(subject);
            helper.setTo(to);
            helper.setText(content);
            helper.setCc("[email protected]");//抄送
            //添加附件
            FileSystemResource file = new FileSystemResource(new File(rscPath));
            helper.addInline(rscId,file);
            mailSender.send(message);
            logger.info("带静态资源文件邮件已经发送。");
        } catch (MessagingException e) {
            logger.info("带静态资源文件邮件已经发送。");
            e.printStackTrace();
        }
    }
}

测试类

package com.neo;

import com.neo.service.mail.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;


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

    @Autowired
    private MailService mailService;

    @Autowired
    private TemplateEngine templateEngine;

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

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

hello world ! 这是一封html邮件!

\n" + "\n" + ""; mailService.sendHtmlMail("[email protected]","这是一封HTML邮件",content); } @Test public void sendAttachmentsMail() { String filePath="C:\\bqs\\分期还打包目录\\test\\spring-boot-package-war.war"; mailService.sendAttachmentsMail("[email protected]", "主题:带附件的邮件", "有附件,请查收!", filePath); } @Test public void sendInlineResourceMail() { String rscId = "neo006"; String content="这是有图片的邮件:"; String imgPath = "C:\\bqs\\分期还打包目录\\test\\login-bg.jpg"; mailService.sendInlineResourceMail("[email protected]", "主题:这是有图片的邮件", content, imgPath, rscId); } /** * 按照模板发送邮件 */ @Test public void sendTemplateMail() { //创建邮件正文 Context context = new Context(); context.setVariable("id", "006"); String emailContent = templateEngine.process("template1", context); mailService.sendHtmlMail("[email protected]","主题:这是模板邮件",emailContent); } }

template1对应html文件的名称。html作为模板邮件进行发送

例如一个template1.html如下:



    
        
        邮件模板
    
    
        您好,感谢您的注册,这是一封验证邮件,请点击下面的链接完成注册,感谢您的支持!
激活账号

配置文件如下:

application.properties

spring.mail.host=smtp.qq.com
[email protected]
spring.mail.password=iipjqncncrgvcbcf
spring.mail.default-encoding=UTF-8
spring.application.name=spirng-boot-mail

spring.mail.password=iipjqncncrgvcbcf  这里的密码并非登陆邮件的密码。而是第三方登陆邮件所需要的授权码。如果是qq邮箱则需要登陆qq邮箱进行授权。

 

你可能感兴趣的:(java,框架)