我正在使用预配置的 Postfix 服务器并使用 JavaMail 与之交互。我正在尝试向任何可能请求它的外部域发送电子邮件通知。
这是发送测试电子邮件的java方法:
public void TestEmail() {
String to = "to@domain.com";
String from = "noreply@hostdomain.com";
final String username = "user";
final String password = "password";
String host = "xxx.xxx.xxx.xxx";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject("Test Email");
message.setContent("This is a test email", "text/html");
Transport.send(message);
System.out.println("The test message was sent!");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
当我运行包含 JavaMail 代码的方法时,我得到
generalError: javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 454 4.7.1 <to@domain.com>: Relay access denied
我能够使用来自 Postfix 服务器的外发邮件进行测试,
echo "This is the body" | mail -s "This is the subject" to@domain.com
并且确实在测试收件箱中收到了电子邮件。
我不是 100% 确定 Postfix 服务器上的所有设置是什么,但我怀疑这就是问题所在,但我对它还不够熟悉,无法开始挖掘并随意更改所有内容。
编辑:
我Authenticator()
从会话创建中删除了设置并替换Transport.send()
为推荐的代码块
Transport transport = session.getTransport("smtp");
transport.connect(host, 587, username, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
整个新的代码集是:
String host = "xxx.xxx.xxx.xxx";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props, null);
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject("Test Email");
message.setContent("This is a test email", "text/html");
Transport transport = session.getTransport("smtp");
transport.connect(host, 587, username, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
System.out.println("The test message was sent!");
} catch (MessagingException e) {
System.out.println("Error: " + e);
e.printStackTrace();
throw new RuntimeException(e);
}
}
这已将我收到的错误消息更改为:Unrecognized SSL message, plaintext connection?
解决了
解决方案:Java 代码不是问题。Postfix 服务器未配置为接受来自非本地 IP/主机的电子邮件。IP 已添加到 mynetworks 变量中的 main.cf。