解决阿里云无法发送邮件问题
Posted w329636271
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了解决阿里云无法发送邮件问题相关的知识,希望对你有一定的参考价值。
阿里云邮件无法发送腾讯邮件解决办法/
使用smtp协议可以解决
具体代码如下:
package cn.celoan.upload.service;
import java.util.List;
import java.util.Properties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
/**
* 邮件发送系统
*
* @author wyzhang
* @date 2021/1/11 9:47
*/
@Service
@Slf4j
public class MailService {
private volatile JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
private String userName;
@Value("${spring.mail.sendTo}")
private String sendTo;
@Value("${spring.mail.host}")
private String host;
@Value("${spring.mail.username}")
private String username;
@Value("${spring.mail.password}")
private String password;
public MailService() {}
public JavaMailSender getMail() {
if (this.javaMailSender != null) {
return this.javaMailSender;
}
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
// 从配置文件获取参数
// SMTP服务器地址
javaMailSender.setHost(host);
// 使用SMTPS协议465端口
javaMailSender.setPort(465);
// 邮箱登陆用户名
javaMailSender.setUsername(username);
// 邮箱登录密码
javaMailSender.setPassword(password);
Properties properties = new Properties();
// 登录服务器是否需要认证
properties.put("mail.smtp.auth", "true");
// SSL证书Socket工厂
properties.setProperty(
"mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
// 使用SMTPS协议465端口
properties.setProperty("mail.smtp.socketFactory.port", "465");
javaMailSender.setJavaMailProperties(properties);
this.javaMailSender = javaMailSender;
return this.javaMailSender;
}
public void sendMail(String title, String content) {
try {
for (String sendName : sendTo.split(",")) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(userName);
message.setTo(sendName);
message.setSubject(title);
message.setText(content);
log.info("send mail to {} {}", sendName, message);
JavaMailSender sender = getMail();
sender.send(message);
}
} catch (Exception e) {
log.error("{}", e);
}
}
public void sendMail(String title, List<String> content) {
try {
for (String sendName : sendTo.split(",")) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(userName);
message.setTo(sendName);
message.setSubject(title);
message.setText(String.join("\\n", content));
log.info("send mail to {} {}", sendName, message);
JavaMailSender sender = getMail();
sender.send(message);
}
} catch (Exception e) {
log.error("{}", e);
}
}
}
以上是关于解决阿里云无法发送邮件问题的主要内容,如果未能解决你的问题,请参考以下文章