添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
添加配置文件
spring.mail.host=smtp.163.com
spring.mail.port=465
spring.mail.username=xxx@163.com
spring.mail.password=xxx
spring.mail.protocol=smtps
spring.mail.test-connection=true
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.smtp.ssl.enable=true
spring.mail.properties.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.starttls.enable=true
注意:
- 这里的密码不是邮箱密码,需要到网易云邮箱去设置
- 端口号如果是本地测试可以设成25,但是如果部署到服务器的话25端口无法使用
15894565761.jpg
生成的密码只会显示一次!!!!!
添加工具类
package com.austshop.austshop.Utils;
import org.apache.log4j.Logger;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
public class SendMail {
private static Logger logger = Logger.getLogger(FileUtils.class);
private final String from = "xxxx@163.com";
private final String to = "xxxx@qq.com";
@Async
public void handleMailSend(JavaMailSenderImpl javaMailSender, String subject, String id, String description) {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
try {
mimeMessageHelper.setTo(to);
} catch (MessagingException e) {
e.printStackTrace();
}
try {
mimeMessageHelper.setFrom(from);
} catch (MessagingException e) {
e.printStackTrace();
}
try {
mimeMessageHelper.setSubject(subject);
} catch (MessagingException e) {
e.printStackTrace();
}
String href = "http://zddddm/article/" + id;
StringBuilder sb = new StringBuilder();
sb.append("<html><head></head>");
sb.append("<body><h1>1212121</h1><p>" + description + "点<a href=" + href + ">这里</a></p></body>");
sb.append("</html>");
// 启用html
try {
mimeMessageHelper.setText(sb.toString(), true);
} catch (MessagingException e) {
e.printStackTrace();
}
// 发送邮件
javaMailSender.send(mimeMessage);
logger.debug("邮件发送成功,from:wanzhipengx@163.com" + from + "to:" + to + "content:" + sb.toString());
}
}
调用工具类
sendMail.handleMailSend(javaMailSender, "文章更新", id, "有文章更新啦");
进行测试
15894568271.jpg注意
部署到服务器之后调用报错
1.连接到25端口超时
解决办法:上面说的,修改端口
2.修改端口之后,报错:无法连接
解决办法:配置文件可能有问题,参考上面我的配置文件
网友评论