发送邮件时候,出现一个问题:使用 25 端口的时候正常,但是使用 465端口的时候却总是不行。
1.问题
Exception in thread "main" java.lang.RuntimeException: org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtp.qq.com:465 at com.rjj.tool.EmailTool.sendEmail(EmailTool.java:41) at com.rjj.tool.EmailTool.main(EmailTool.java:54)Caused by: org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtp.qq.com:465 at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1242) at org.apache.commons.mail.Email.send(Email.java:1267) at com.rjj.tool.EmailTool.sendEmail(EmailTool.java:39) ... 1 moreCaused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.qq.com, port: 465, response: -1 at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1379) at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:412) at javax.mail.Service.connect(Service.java:310) at javax.mail.Service.connect(Service.java:169) at javax.mail.Service.connect(Service.java:118) at javax.mail.Transport.send0(Transport.java:188) at javax.mail.Transport.send(Transport.java:118) at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1232) ... 3 more
2.项目引入的jar都是有的
端口也是全部开放的。
3.代码是这样子的
public static String sendEmail(String emailServer, Integer port, String fromEmail, String password, String toEmail, String title, String content) { SimpleEmail email = new SimpleEmail(); // email.setSSL(true); if (StrKit.notBlank(emailServer)) { email.setHostName(emailServer); } else { // 默认使用本地 postfix 发送,这样就可以将postfix 的 mynetworks 配置为 127.0.0.1 或 // 127.0.0.0/8 了 email.setHostName("127.0.0.1"); } // 如果密码为空,则不进行认证 if (StrKit.notBlank(password)) { email.setAuthentication(fromEmail, password); } // 端口号不为空,使用配置的端口 if (port != null) { //email.setSslSmtpPort(port.toString()); email.setSmtpPort(port); } email.setCharset("utf-8"); try { email.addTo(toEmail); email.setFrom(fromEmail); email.setSubject(title); email.setMsg(content); return email.send(); } catch (EmailException e) { throw new RuntimeException(e); } }
找出问题所在是端口的问题,发邮件时候25端口不用加密也是可以使用,发邮件的的,但是465端口使用的时候需要加密的。
解决:代码中已经标识了,这里在发邮件的时候需要把邮件设置
SSL加密,就可以了,这里有两种方式: 1.端口加密:email.setSslSmtpPort(port.toString()); 2.直接开启ssl加密: email.setSSL(true);
这样就可以正常发送邮件了。
一点一滴记录遇到的问题与解决方式。。。