1. 需求:项目中有个功能实现将账单邮件推送
2. 过程:1)需要开启POP3/SMTP支持:https://jingyan.baidu.com/article/4f7d5712b1ac7c1a201927da.html
2)添加相关jar依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
3) 配置项:
#发送邮件服务器
spring.mail.host=smtp.qq.com
spring.mail.username=xxx@qq.com
#客户端授权码
spring.mail.password=xxxxx
#发送邮件协议
spring.mail.protocol=smtp
spring.mail.properties.mail.smtp.auth=true
#端口号465或587
spring.mail.properties.mail.smtp.port=465
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.ssl.enable=true
spring.mail.default-encoding=utf-8
#与上面的username保持一致
spring.mail.from=xxx@qq.com
4) 邮件格式校验:
private boolean validEmail(String email) {
String regex = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(email);
return m.matches() ? true : false;
}
5) 组装内容并发送:
@Component
public class MailUtil {
@SuppressWarnings("unused")
private static Logger LOGGER = LoggerFactory.getLogger(MailUtil.class);
@Autowired private JavaMailSender javaMailSender;
@Autowired private BillUtil billUtil;
// 获取配置文件的username
@Value("${spring.mail.username:}")
private String username;
public void sendMail(
String clientMail,
String userName,
String earningsDate,
String monthEarningsVb,
String monthContributionVb,
String totalVb,
List<RespBillOrderDetail> billOrderDetails) {
try {
//使用JavaMail的MimeMessage,支付更加复杂的邮件格式和内容
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//创建MimeMessageHelper对象,处理MimeMessage的辅助类
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
//使用辅助类MimeMessage设定参数
helper.setFrom(new InternetAddress(username, "GBei", "UTF-8"));
helper.setTo(clientMail);
helper.setSubject("GBei账单");
//邮件内容
String content = billUtil.sendBill(userName, earningsDate, monthEarningsVb, monthContributionVb, totalVb, billOrderDetails);
helper.setText(content, true);
// 发送邮件
javaMailSender.send(mimeMessage);
} catch (MessagingException e){
LOGGER.debug("=========MessagingException=========");
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
LOGGER.debug("=========UnsupportedEncodingException========");
e.printStackTrace();
}
}
}
3. 实现结果:
4. 备注:
如果出现如下错误:org.springframework.mail.MailAuthenticationException: Authentication failed
则:1,检查自己邮箱是否开通pop3/smtp服务。 2、程序中所填的邮箱密码是否为开通pop3/smtp服务时所给的授权码。