java实战-邮件发送
前言
-
发送邮件功能是一个比较常用的业务需求,今天就抽空做一下总结
准备工作
- 邮箱是要有的(生产中建议多个邮箱,随机发送)
- 邮箱授权码,自行百度一下
SpringBoot方式
-
Springboot中需要引入的依赖 <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
-
application.yml进行配置
spring:
mail:
host: smtp.163.com
port: 25
default-encoding: UTF-8
properties:
mail:
debug: true
username: xxxx_system@163.com
password: XXVMHDQYJFLNFOXX
- templates下文件内容
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>用户邮箱验证</title>
<style>
body, div, p, ul, li, a {
margin: 0;
padding: 0;
list-style: none;
text-decoration: none;
}
body {
height: 100%;
width: 100%;
background-color: #FFE7E7;
}
.wrap {
width: 750px;
height: 100%;
margin: 0 auto;
}
nav {
font-weight: 700;
padding: 20px 10px;
box-sizing: border-box;
background: #f9f9f9;
}
.nav-title {
text-indent:25px;
margin: 0 0 20px;
}
.nav-content, .nav-end, .card-time {
text-indent:25px;
font-size: 15px;
line-height: 30px;
}
.list ul {
width: 100%;
height: 36px;
font-size: 13px;
display: flex;
align-items: center;
background: #e4e4e4;
border-radius: 8px 8px 0 0;
}
.list .list-ul {
background: #fff;
border-radius: 0;
height: 52px;
line-height: 52px;
background: #f9f9f9;
}
.list .list-ul li {
font-size: 12px;
}
</style>
</head>
<body>
<div class="wrap">
<nav>
<p class="nav-title">Hi, <span th:text="${nickName}"></span>:</p>
<p class="nav-content">本邮件仅供邮箱验证使用,验证码为<b style="color: deepskyblue"
th:text="${verifyCode}"></b>,有效期为5分钟,
逾期需重新获取.</p>
<p class="nav-end">如有任何疑问,请拨打客服电话。感谢您的使用!</p>
</nav>
</div>
</body>
</html>
- 测试类
@SpringBootTest
class MailServerApplicationTests {
@Autowired
JavaMailSender javaMailSender;
@Autowired
private TemplateEngine templateEngine;
@Test
void sendSimpleMail() {
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject("这是一封测试邮件");
message.setFrom("evaluate_system@163.com");
message.setTo("511250051@qq.com");
message.setCc("tyvek_zhang@126.com");
message.setBcc("1024043315@qq.com");
message.setSentDate(new Date());
message.setText("这是测试邮件的正文");
javaMailSender.send(message);
}
@Test
void sendAttachMail() throws MessagingException {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
helper.setSubject("这是一封测试邮件");
helper.setFrom("xxxx_system@163.com");
helper.setTo("511250051@qq.com");
helper.setSentDate(new Date());
helper.setText("这是测试邮件的正文");
helper.addAttachment("hello world.pdf",new File("F:\\mywork\\hello world.pdf"));
javaMailSender.send(mimeMessage);
}
@Test
void sendMailWithThf() throws MessagingException {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setSubject("这是一封测试邮件");
helper.setFrom("xxxx_system@163.com");
helper.setTo("511250051@qq.com");
helper.setSentDate(new Date());
Context context = new Context();
context.setVariable("nickName", "foo");
context.setVariable("verifyCode", "6666");
String process = templateEngine.process("verifyEmail.html", context);
helper.setText(process,true);
javaMailSender.send(mimeMessage);
}
}
不使用SpringBoot方式
-
需要引入的依赖 <!--邮箱依赖-->
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.4.7</version>
</dependency>
-
工具类 public class Mail163Utils {
private static final String SENDER_NAME = "邮箱验证" ;
private static final String SENDER_ADDRESS = "xxxx_system@163.com" ;
private static final String SENDER_PWD = "CTVMHDQYJFLNFOBC" ;
private static final String PRIVATE_ADDRESS = "xxxx_system@163.com" ;
private static final Session EMAIL_SESSION = getEmailSession();
public static void sendEmail(List<String> emailAddressList, String title, String content, List<File> fileList) throws Exception {
MimeMessage mimeMessage = getMimeMessage(emailAddressList, title, content);
if (!CollectionUtils.isEmpty(fileList)){
Multipart multipart = getMultipart(fileList);
mimeMessage.setContent(multipart);
BodyPart contentPart = new MimeBodyPart();
contentPart.setContent(content, "text/html;charset=UTF-8");
multipart.addBodyPart(contentPart);
}
Transport.send(mimeMessage);
}
private static MimeMessage getMimeMessage(List<String> emailAddressList, String title, String content) throws Exception {
MimeMessage message = new MimeMessage(EMAIL_SESSION);
message.setFrom(new InternetAddress(SENDER_ADDRESS, SENDER_NAME));
InternetAddress[] address = new InternetAddress[emailAddressList.size()] ;
for (int i = 0; i < emailAddressList.size(); i++){
address[i] = new InternetAddress(emailAddressList.get(i)) ;
}
message.setRecipients(Message.RecipientType.TO, address);
message.setRecipient(Message.RecipientType.BCC, new InternetAddress(PRIVATE_ADDRESS));
message.setRecipients(Message.RecipientType.CC, SENDER_ADDRESS);
message.setSubject(title, "UTF-8");
message.setContent(content, "text/html;charset=UTF-8");
message.setSentDate(new Date());
return message;
}
private static Multipart getMultipart(List<File> fileList) {
if (CollectionUtils.isEmpty(fileList)) {return null;}
Multipart multipart = new MimeMultipart();
fileList.stream().parallel().forEach(file -> {
try {
BodyPart attachmentBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(file);
attachmentBodyPart.setDataHandler(new DataHandler(source));
attachmentBodyPart.setFileName(MimeUtility.encodeWord(file.getName()));
multipart.addBodyPart(attachmentBodyPart);
} catch (Exception e) {
e.printStackTrace();
}
});
return multipart ;
}
private static Session getEmailSession(){
Properties props = new Properties();
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.host", "smtp.163.com");
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(SENDER_ADDRESS, SENDER_PWD);
}
};
return Session.getInstance(props, authenticator);
}
}
|