参考链接:
https://blog.csdn.net/caychen/article/details/82887926
https://www.cnblogs.com/wushaopei/p/11979373.html
Mail依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>${spring-boot-mail.version}</version>
</dependency>
通用配置application.properties:
# 设置邮箱主机
spring.mail.host=smtp.qq.com
# 设置用户名
spring.mail.username=xxxxxx@qq.com
# 设置密码,该处的密码是QQ邮箱开启SMTP的授权码而非QQ密码
spring.mail.password=pwvtabrwxogxidac
# 设置是否需要认证,如果为true,那么用户名和密码就必须的,
# 如果设置false,可以不设置用户名和密码,当然也得看你的对接的平台是否支持无密码进行访问的。
spring.mail.properties.mail.smtp.auth=true
# STARTTLS[1] 是对纯文本通信协议的扩展。它提供一种方式将纯文本连接升级为加密连接(TLS或SSL),而不是另外使用一个端口作加密通信。
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
mail.from=${spring.mail.username}
mail.to=yyyyyy@qq.com
package com.example.poiutis.utils.Email;
import com.example.poiutis.model.common.EmailConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
/**
* @ClassName MailSenderFacade
* @Description TODO
* @Author wushaopei
* @Date 2019/7/25 10:22
* @Version 1.0
*/
@Component
public class MailSenderFacade {
@Autowired
private EmailConfig emailConfig;
private final Logger logger = LoggerFactory.getLogger(MailSenderFacade.class);
public void sendMailHtml(final String toEmail,final String subject,final String text){
try{
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setUsername(emailConfig.getUsername());
javaMailSender.setPassword(emailConfig.getPassword());
javaMailSender.setHost(emailConfig.getHost());
javaMailSender.setPort(25);
javaMailSender.setProtocol("smtp");
javaMailSender.setDefaultEncoding("UTF-8");
Properties mailProperties = new Properties();
mailProperties.put("mail.smtp.auth", true);
mailProperties.put("mail.smtp.starttls.enable", true);
javaMailSender.setJavaMailProperties(mailProperties);
MimeMessage mimeMessage = getMimeMessage(toEmail,subject,text, javaMailSender);
javaMailSender.send(mimeMessage);
logger.info("发往 "+toEmail+" 邮件发送成功");
} catch (MessagingException e) {
logger.error("发往 "+toEmail+" 邮件发送异常", e);
}
}
private MimeMessage getMimeMessage(String toEmail,String subject,String text, JavaMailSenderImpl javaMailSender) throws MessagingException {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
mimeMessageHelper.setFrom(emailConfig.getSenderName());
mimeMessageHelper.setTo(toEmail);
mimeMessageHelper.setSubject(subject);
mimeMessageHelper.setText(text, true);
return mimeMessage;
}
}