【发布时间】:2017-04-24 01:08:57
【问题描述】:
我正在使用预配置的 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
我能够使用 echo "This is the body" | mail -s "This is the subject" to@domain.com
测试从 Postfix 服务器发出的邮件
并且确实在测试收件箱中收到了电子邮件。
我不能 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。
【问题讨论】:
标签: java jakarta-mail postfix-mta postfix