springboot 整合邮件服务
1. 新建 maven 项目,引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2. 新建接口文件
package com.example.demo.service;
import javax.mail.MessagingException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Path;
public interface MailService {
/**
* 1. from 发件人
* 2. to 收件人
* 3. subject 邮件主题
* 4. cc 抄送
* 5. bcc 密送
*/
void sendMail(String to, String subject, String content, Path path) throws MessagingException, UnsupportedEncodingException;
}
3. 新建实现类
package com.example.demo.service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;
@Slf4j
@Service
public class MailServiceImpl implements MailService {
@Value("${mail.from.mail.addr}")
private String from;
@Value("${mail.from.mail.pass1}")
private String password1;
@Value("${mail.from.mail.pass2}")
private String password2;
@Override
public void sendMail(String to, String subject, String content, Path path) throws MessagingException, UnsupportedEncodingException {
log.info("send start");
log.info("username >>> " + from);
log.info("p1 >>> " + password1);
log.info("p2 >>> " + password2);
Properties properties = new Properties();
properties.setProperty("mail.smtp.host", "smtp.163.com");
properties.setProperty("mail.smtp.username", from);
properties.setProperty("mail.smtp.password", password1);
properties.setProperty("mail.smtp.defaultEncoding", "UTF-8");
properties.setProperty("mail.smtp.auth", "true");
// 安全类型:ssl 端口号:465
properties.setProperty("mail.smtp.port", "465");
properties.put("mail.smtp.ssl.enable", "true");
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, password2);
}
});
//得到一个邮件
MimeMessage message = new MimeMessage(session);
// 设置发件人 from
message.setFrom(new InternetAddress(from));
//设置收件人 to
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
//设置主题 subject
message.setSubject(subject);
//设置包含 html 内容的 mimebodypart
Multipart multipart = new MimeMultipart();
BodyPart html = new MimeBodyPart();
html.setContent(content, "text/html; charset=utf-8");
multipart.addBodyPart(html);
//设置附件。。。
if (path != null) {
File file = path.toFile();
String fileName = file.getName();
log.info("fileName >>> " + fileName);
BodyPart bodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(file);
bodyPart.setDataHandler(new DataHandler(source));
//避免 filename 乱码
bodyPart.setFileName(MimeUtility.encodeWord(fileName));
multipart.addBodyPart(bodyPart);
}
//设置邮件内容
message.setContent(multipart);
Transport.send(message);
log.info("send end");
}
}
4. 在配置文件中配置用户名、密码信息
application.properties
mail.from.mail.addr=xxx
mail.from.mail.pass1=xxx
# 客户端的授权码
mail.from.mail.pass2=xxx
5. 测试类
package com.example.demo;
import com.example.demo.service.MailServiceImpl;
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 javax.mail.MessagingException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Paths;
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestMail {
@Autowired
MailServiceImpl mailService;
@Test
public void test() {
try {
mailService.sendMail("XXX@163.com",
"test-mail",
"<h1>TEST</h1>",
Paths.get("/Users/zhangzheng/Desktop/test-mail.rtf"));
} catch (MessagingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}