阿里云服务器禁用了25端口,所以改为465端口采用SSL协议传输邮件
163网易免费邮箱相关服务器信息:
相关代码:
package com.yc.util;
import java.io.File;
import java.util.Properties;
import java.util.Random;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.servlet.http.HttpSession;
public class SendEmailUtil
{
public int sendEmail(String reperson,HttpSession sessions)
{
int result=0;
// 收件人电子邮箱
String to = reperson;
// 发件人电子邮箱
String from = "你的真实邮箱地址";
// 指定发送邮件的主机为 smtp.qq.com
String host = "smtp.163.com"; //163邮件服务器
// 获取系统属性
Properties properties = System.getProperties();
// 设置邮件服务器
properties.setProperty("mail.smtp.host", host);
properties.put("mail.smtp.auth", "true");
//阿里云服务器禁用25端口,所以服务器上改为465端口
properties.put("mail.smtp.socketFactory.port", "465");
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.setProperty("mail.smtp.socketFactory.fallback", "false");
properties.setProperty("mail.smtp.socketFactory.port", "465");
// 获取默认session对象
Session session = Session.getDefaultInstance(properties,new Authenticator(){
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication("你的真实邮箱地址", "你的真实密码"); //发件人邮件用户名、密码
}
});
try{
// 创建默认的 MimeMessage 对象
MimeMessage message = new MimeMessage(session);
// Set From: 头部头字段
message.setFrom(new InternetAddress(from));
// Set To: 头部头字段
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: 头部头字段
message.setSubject("注册论坛网验证码");
// 设置消息体
Random rand=new Random();
String txt=String.valueOf(rand.nextInt(9000)+1000);
sessions.setAttribute("yanzhengma",txt);
message.setText("你好"+reperson+"! 欢迎注册论坛网。验证码为:"+txt);
// 发送消息
Transport.send(message);
result=1;
}catch (MessagingException mex) {
mex.printStackTrace();
}
return result;
}
}
贴上以上的代码以为可以发送,在本地电脑可以发送,在服务器上仍然发送失败,查看输出日志后才发现报的是以下的错误:
解决方法:在/etc/hosts中添加127.0.0.1本地映射
1.在linux终端输入 hostname
2.打开/etc/hosts编辑添加一行 127.0.0.1 iZwz9dgm0ak5eyqrkwypkjZ
3.再输入 hostname -i
解决以上问题,终于可以发送邮件啦!欢迎关注下方公众号,一起交流,期待你的到来
参考:https://www.cnblogs.com/hoojjack/p/8025284.html
https://www.cnblogs.com/FLFL/p/6476358.html
https://blog.csdn.net/zhangyunfei_happy/article/details/56276206