本文仅供参考,转载请注明出处,谢谢
我的开源中国博客地址:https://my.oschina.net/u/2486137/blog/1513638问题①: java发送qq邮件出现如下错误的解决方法:
503 Error: need EHLO and AUTH first !
pop.put("mail.smtp.auth", "true");//注意value值不能不设置,并且不能是Boolean类型,应为字符串,否则会报如上所示错误
问题②: Could not connect to SMTP host: smtp.qq.com, port: 465, response: -1
原因: 465端口是为SMTPS(SMTP-over-SSL)协议服务开放的,这是
SMTP协议基于SSL安全协议之上的一种变种协议.
解决方法: 配置文件需要加上如下代码即可解决.
pop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
附上所有的代码:
配置文件:
说明: 配置文件采用的是yml文件,跟properties相比,优点是结构化清晰,少写很多代码
> mail:
mailhost: smtp.qq.com
mailport: 465
user: 邮箱用户名
password: 密码(qq为授权码)
mailFrom: xxx@QQ.com #发送者的邮箱,
mailTo: xxx@qq.com,xxx@qq.com,xxx@foxmail.com #接收者的邮箱,群发请以逗号隔开
properties:
mail:
smtp:
auth: true
mailtimeout: 1000
mailssl: javax.net.ssl.SSLSocketFactory
starttls:
enable: true
required: true
>
> java代码:`
` @Value("${mailhost}")
private String host;
@Value("${mailport}")
private Integer port;
@Value("${user}")
private String username;
@Value("${password}")
private String password;
@Value("${mailFrom}")
private String from;
@Value("${mailTo}")
private String [] to;
@Value("${auth}")
private String auth;
@Value("${enable}")
private Boolean enable;
@Value("${required}")
private Boolean required;
@Value("${mailtimeout}")
private Integer timeout;
@Value("${mailssl}")
private String ssl;
public void onApplicationEvent(ApplicationEvent event) {
System.out.println("email cfg....");
System.out.println("print:"+this.toString());
//创建一个发送者对象
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost(this.host);
mailSender.setPort(this.port);
mailSender.setUsername(this.username);
mailSender.setPassword(this.password);
// 加认证机制
Properties pop = new Properties();
pop.put("mail.smtp.host", this.host);
// pop.put("mail.smtp.port", this.port);//已经在上面加过
pop.put("mail.smtp.auth", this.auth);//必须是字符串而不能是boolean否则报错
pop.put("mail.smtp.starttls.enable", this.enable);
pop.put("mail.smtp.timeout", this.timeout);
pop.put("mail.smtp.socketFactory.class", this.ssl);
mailSender.setJavaMailProperties(pop);
//组织邮件参数并执行发送
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(this.from);
message.setTo(this.to);
message.setSubject("主题:测试,spring boot发送邮件.");
message.setText("测 试\n 邮件为程序发送,是否收到?请回答");
mailSender.send(message);
System.out.println("send end....");
}
@Override
public String toString() {
return "EmailConfiguration [host=" + host + ", port=" + port + ", username=" + username
+ ", password=" + password + ", from=" + from + ", to=" + to + ", auth=" + auth
+ ", enable=" + enable + ", required=" + required + ", timeout=" + timeout + "]";
}
热门评论
邮箱开启了,账号密码写上去还是不行,不知道咋会sigh
说好的审核通过,加5积分呢