邮件发送是一个非常常见的功能,最初 Sun 公司提供了 JavaMail 用来实现邮件发送,但是配置烦琐。后来 Spring 中提供了 JavaMailsender 用来简化邮件配置,而 Spring Boot 则提供了 MailSenderAutoConfiguration 对邮件的发送做了进一步简化。
在开始之前我们需要申请开通 POP3/SMTP 服务或者 IMAP/SMTP服务。
这里我使用的163邮箱开通:开通 POP3/SMTP 服务或者 IMAP/SMTP服务
一、添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
二、添加配置信息
# 配置邮件服务器的地址
spring.mail.host=smtp.163.com
# 配置邮件服务器的端口(465或587)
spring.mail.port=465
# 配置用户的账号
spring.mail.username=2333@163.com
# 配置用户的密码(即上面我们申请到的授权码)
spring.mail.password=TSSCBFCCJUTABBTB
# 配置默认编码
spring.mail.default-encoding=UTF-8
# SSL 连接配置
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
# 开启 debug,这样方便开发者查看邮件发送日志
spring.mail.properties.mail.debug=true
三、开发代码
(1)编写请求接口
import com.example.demo.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
@RestController
public class MailController {
private final static String FROM_MAIL = "2333@163.com";
private final static String TO_MAIL = "123@qq.com";
@Autowired
MailService mailService;
@GetMapping("/sendMail")
public String sendMail() {
mailService.sendSimpleMail(FROM_MAIL, TO_MAIL, TO_MAIL, "邮件的标题", "邮件的内容");
return "发送成功";
}
@GetMapping("/sendAttachFileMail")
public String sendAttachFileMail() {
File file = new File("/Users/gongzhiqiang/Downloads/邮件发送附件.txt");
mailService.sendAttachFileMail(FROM_MAIL, TO_MAIL, "邮件的标题", "邮件的内容", file);
return "发送成功";
}
@GetMapping("/sendMailWithImg")
public String sendMailWithImg() {
String html = "<h3>hello 皮卡丘</h3>" +
"<div><img width='66px' src='cid:p1'/></div>" +
"<div><img width='66px' src='cid:p2'/></div>";
String[] imgUrlArr = {"/Users/gongzhiqiang/Downloads/pikaqiu.jpeg", "/Users/gongzhiqiang/Downloads/pikaqiu1.jpeg"};
String[] valArr = {"p1", "p2"};
mailService.sendMailWithImg(FROM_MAIL, TO_MAIL, "邮件的标题", html, imgUrlArr, valArr);
return "发送成功";
}
}
(2)编写服务
import java.io.File;
public interface MailService {
void sendSimpleMail(String from, String to, String cc, String subject, String content);
void sendAttachFileMail(String from, String to, String subject, String content, File file);
void sendMailWithImg(String from, String to, String subject, String content,
String[] srcPath,String[] resIds);
}
import com.example.demo.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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;
@Service
@Slf4j
public class MailServiceImpl implements MailService {
@Autowired
JavaMailSender javaMailSender;
/**
* 发送邮件
* @param from 邮件发送者
* @param to 收件人
* @param cc 抄送人
* @param subject 邮件主题
* @param content 邮件内容
*/
@Override
public void sendSimpleMail(String from, String to, String cc, String subject, String content) {
// 简单邮件直接构建一个 SimpleMailMessage 对象进行配置并发送即可
SimpleMailMessage simpMsg = new SimpleMailMessage();
simpMsg.setFrom(from);
simpMsg.setTo(to);
simpMsg.setCc(cc);
simpMsg.setSubject(subject);
simpMsg.setText(content);
javaMailSender.send(simpMsg);
}
/**
* 发送待附件的邮件
* @param from 邮件发送者
* @param to 收件人
* @param subject 邮件主题
* @param content 邮件内容
* @param file 附件
*/
@Override
public void sendAttachFileMail(String from, String to, String subject, String content, File file) {
try {
MimeMessage message = javaMailSender.createMimeMessage();
// 这里使用 MimeMessageHelper 简化了邮件配置
// 第二个参数true表示构造一个 multipart message 类型邮件
// multipart message类型邮件包含多个正文、附件以及内嵌资源,邮件表现形式更加丰富
MimeMessageHelper helper = new MimeMessageHelper(message,true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content);
helper.addAttachment(file.getName(), file);
javaMailSender.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
}
@Override
public void sendMailWithImg(String from, String to, String subject, String content,
String[] srcPath,String[] resIds) {
if (srcPath.length != resIds.length) {
log.error("发送失败");
return;
}
try {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message,true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
//第二个参数true表示邮件正文是HTML格式(默认为false)
helper.setText(content,true);
for (int i = 0; i < srcPath.length; i++) {
//通过FileSystemResource构造静态资源,让后调用addInline方法将资源加入到邮件对象中
FileSystemResource res = new FileSystemResource(new File(srcPath[i]));
helper.addInline(resIds[i], res);
}
javaMailSender.send(message);
} catch (MessagingException e) {
log.error("发送失败");
}
}
}
四、验证结果
(1)请求发送邮箱接口:http://127.0.0.1:8082/sendMail
(2)请求发送带附件邮箱接口:http://127.0.0.1:8082/sendAttachFileMail
(3)请求发送带图片邮箱接口:http://127.0.0.1:8082/sendMailWithImg