背景:
邮件使用的场景:注册验证、网站营销、安全的最后一道防线、提醒、监控告警、触发机制
邮件发送的原理
邮件传输协议:SMTP、POP3协议
SMTP接力传送,注重传输
POP3注重从邮件服务器上查看邮件
IMAP 交互式邮件协议(对POP3的补充)
Mime 邮件访问协议
SpringBoot发送邮件,工作中一般通过搭建邮件系统,或者做成微服务的接口形式(HTTP/API)供调用,再结合MQ使用
邮件一般有简单文本邮件、HTML邮件、附件邮件、图片邮件等。
注意:邮箱需开通POP3、IMAP协议
使用之前先导入所需要的jar包
org.springframework.boot
spring-boot-starter-mail
邮件模板需要的jar包
org.springframework.boot
spring-boot-starter-thymeleaf
配置文件:application.properties
####到所涉及的邮箱里查找###
####smtp.126.com
####smtp.163,com
spring.mail.host=smtp.qq.com
spring.mail.username=*********@qq.com
####填写授权码,不是邮箱密码
spring.mail.password=zwyhplxkihoibafa
spring.mail.default-encoding=UTF-8
Demo:
package com.neo.helloworld.service;
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.Service;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
/**
* @Author Rhine
* @Date 2019/1/30 16:30
**/
@Service
public class MailService {
@Value("${spring.mail.username}")
private String from;
@Autowired
private JavaMailSender mailSender;
private final Logger logger=LoggerFactory.getLogger(this.getClass());
/**
* 简单文本邮件
* @param to 收件人
* @param subject 邮件主题
* @param content 邮件内容
*/
public void sendSimpleMail(String to,String subject,String content){
SimpleMailMessage mailMessage=new SimpleMailMessage();
mailMessage.setTo(to);
mailMessage.setSubject(subject);
mailMessage.setText(content);
mailMessage.setFrom(from);
mailSender.send(mailMessage);
}
/**
* 发送HTML邮件
* @param to
* @param subject
* @param content
* @throws MessagingException
*/
public void sendHtmlMail(String to,String subject,String content) throws MessagingException {
MimeMessage message=mailSender.createMimeMessage();
MimeMessageHelper helper=new MimeMessageHelper(message,true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content,true);
mailSender.send(message);
}
/**
* 发送带有附件的文件
* @param to
* @param subject
* @param content
* @param filePath
* @throws MessagingException
*/
public void sendAttachmentsMail(String to,String subject,String content,String filePath) throws MessagingException {
MimeMessage message=mailSender.createMimeMessage();
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(fileName+"Test",file);//有几个附件就添加几个addAttachment()
mailSender.send(message);
}
/**
* 发送带有图片的邮件
* @param to
* @param subject
* @param content
* @param rscPath
* @throws MessagingException
*/
public void sendInlinResourceMail(String to, String subject, String content, String rscPath,String rscId) {
logger.info("发送静态邮件开始:{},{},{},{},{}",to,subject,content,rscPath,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);//有几张图片就有几个addInline()方法,content里img标签就有几个
helper.addInline(rscId,res);
mailSender.send(message);
logger.info("发送静态图片邮件成功!");
} catch (MessagingException e) {
logger.error("发送静态邮件失败:",e);
}
}
}
测试方法:
package com.neo.helloworld.service;
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 javax.mail.MessagingException;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MailServiceTest {
@Autowired
private MailService mailService;
@Autowired
private TemplateEngine templateEngine;
//简单文本邮件
@Test
public void sendSimpleMailTest() {
mailService.sendSimpleMail("[email protected]","MailSendTest:这是一封爱的邮件","Test 邮件正文:老婆辛苦了,老公爱你!么么哒");
}
//网页邮件
@Test
public void sendHtmlMail() throws MessagingException {
String content="\n" +
"\n"+
"hello world,这是一封HTML邮件!
\n"+
"\n"+
"";
mailService.sendHtmlMail("[email protected]","MailSendTest:这是一封HTML的邮件",content);
}
//附件邮件
@Test
public void sendAttachmentsMail() throws MessagingException {
String filePath="C:\\Users\\Rhine\\Desktop\\备忘.txt";
mailService.sendAttachmentsMail("[email protected]","MailSendTest:这是一封附件邮件","这是一个附件邮件",filePath);
}
//图片邮件
@Test
public void sendInlinResourceMail() {
String imgPath="C:\\Users\\Rhine\\Desktop\\4444555.jpg";
String rscId="neo001";
String content="给你一张靓仔的照片" +
""+
"";
mailService.sendInlinResourceMail("[email protected]","MailSendTest:这是一封图片邮件",content,imgPath,rscId);
}
//模板邮件
@Test
public void testTemplateTest() throws MessagingException {
Context context=new Context();
context.setVariable("id","006");
String emailContext=templateEngine.process("emailTemplate",context);
mailService.sendHtmlMail("[email protected]","subject:这是一个模板邮件",emailContext);
}
}
其中模板为存放在resource\templates\emailTemplate.html
邮件模板
您好,感谢您的注册,这是一封验证邮件,请点击下面的链接完成注册,感谢您的支持!
激活账号
常见的错误:
421 HL:ICC 该IP同时并发连接数过大
451 Requested mail action not taken:too much fail... 登录失败次数过多,被临时禁止登录
553 authentication is required 认证失败(出现最频繁,检查邮箱配置)