问题描述:
在使用公司邮箱通过JavaMail发送外部邮件例如发送到OUTLOOK邮箱,163邮箱等时,程序会报异常
javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay
可尝试以下解决方法:
增加smtp属性认证,以及指定TLSv1.2协议
// 设置邮件服务器属性
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.auth", "true");
properties.put("mail.smtp.ssl.protocols", "TLSv1.2");
以下是完整测试代码,可参考:
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendMail {
public static void main(String [] args)
{
// 收件人电子邮箱
String to = "xxxxx@163.com";
// 发件人电子邮箱
String from = "xxxxx@xxxx.com.cn";
// 指定发送邮件的主机
String host = "xxx.x.x.x";
// 获取系统属性
Properties properties = System.getProperties();
// 设置邮件服务器
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.auth", "true");
properties.put("mail.smtp.ssl.protocols", "TLSv1.2");
// 发件人邮箱的用户名和密码
String username = "your-email-userame";
String password = "your-email-password"; // 替换为你的邮箱密码或应用密码
// 创建一个 Authenticator 对象
Authenticator auth = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
};
// 设置 Session 对象使用 Authenticator
Session session = Session.getInstance(properties, auth);
// 获取默认session对象
// Session session = Session.getDefaultInstance(properties);
try{
// 创建默认的 MimeMessage 对象
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("This is the Subject Line!");
// 设置消息体
message.setText("This is actual message");
// 发送消息
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
参考文章: