自己的项目在本地发邮件没任何问题。但部署到服务器,发送邮件显示连接异常。原来是云服务器出于安全考虑,关闭了服务器的25端口,而25端口是smtp的默认端口。所以使用465端口开启ssl加密传输
代码:
package cn.lzhhuo.login_register.util;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.Security;
import java.util.Date;
import java.util.Properties;
public class MailUtil {
/**
* 使用加密的方式,利用465端口进行传输邮件,开启ssl
* @param to 为收件人邮箱
* @param message 发送的消息
*/
public static void sendEmil(String to, String message) {
try {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
//设置邮件会话参数
Properties props = new Properties();
//邮箱的发送服务器地址
props.setProperty("mail.smtp.host", "smtp.qq.com");
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
//邮箱发送服务器端口,这里设置为465端口
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.auth", "true");
final String username = " ";
final String password = " ";
//获取到邮箱会话,利用匿名内部类的方式,将发送者邮箱用户名和密码授权给jvm
Session session = Session.getDefaultInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
//通过会话,得到一个邮件,用于发送
Message msg = new MimeMessage(session);
//设置发件人
msg.setFrom(new InternetAddress(username));
//设置收件人,to为收件人,cc为抄送,bcc为密送
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(to, false));
msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(to, false));
//设置邮件消息
msg.setSubject("激活邮件");
msg.setText(message);
//设置发送的日期
msg.setSentDate(new Date());
//调用Transport的send方法去发送邮件
Transport.send(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception { // 做测试用
String content="点击激活";
MailUtil.sendEmil(" @qq.com",content);
System.out.println("发送成功");
}
}
可能出现的问题:
无法连接到SMTP主机:smtp.qq.com,端口:465:
pom.xml配置错了:
使用默认25端口发送邮件
也可以参照以上来改动端口