我们使用 Java Mail 1.5 API 发送邮件。我们用于开发的 SMTP 主机没有任何抑制列表,因此,如果任何无效电子邮件(例如“[email protected]”)将被发送,尽管其被硬退回,但我们会在 getInvalidAddresses()
中得到它。异常(exception),
但是,如果我们尝试使用具有抑制列表的产品 SMTP 服务器,则同一电子邮件“[email protected]”会导致其他电子邮件无法发送,如果它们属于同一“收件人”列表的一部分,例如“[email protected]” ; [email protected] ”,我们的期望是至少“[email protected] ”应该收到电子邮件,但即使这样也不会发送,并且 getInvalidAddresses()
为空
com.sun.mail.smtp.SMTPAddressFailedException: 254 4.7.1 - <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e098999aa098999ace838f8d" rel="noreferrer noopener nofollow">[email protected]</a> is suppressed for sender smtp.xxx.xxx
public class SendMail {
public static void main(String[] args) {
final String username = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9eebedfbecf0fff3fbdefaf1f3fff7f0b0fdf1f3" rel="noreferrer noopener nofollow">[email protected]</a>";
final String password = "xxxxxxxxxxxx";
Properties prop = new Properties();
prop.put("mail.smtp.host", "mysmtp.domain.com");
prop.put("mail.smtp.port", "25");
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.sendpartial", "true");
prop.put("mail.smtp.socketFactory.port", "25");
prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
Session session = Session.getInstance(prop,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6006120f0d20040f0d01090e4e030f0d" rel="noreferrer noopener nofollow">[email protected]</a>"));
message.setRecipients(
Message.RecipientType.TO,
InternetAddress.parse("<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e690878a8f82a682898b878f88c885898b" rel="noreferrer noopener nofollow">[email protected]</a>, <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4f3736350f373635612c2022" rel="noreferrer noopener nofollow">[email protected]</a>")
);
message.setSubject("Test Mail");
message.setText("Test Mail");
Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
我们如何处理 Java Mail API 中的黑名单错误?
最佳答案
您遇到的问题是由电子邮件服务器使用的返回代码 254
引起的。根据RFC 5321 (RFC 821的最新体现),没有这样的代码。这个返回码似乎是 Oracle's Email Delivery 的发明.
Java Mail(及其后继者 Jakarta Mail)解释(参见 source code )未知:
- 4xx 返回代码为
validUnsentAddresses
, - 5xx 返回代码为
invalidAddresses
, - 2xx 返回代码表示完全传送失败,因为无法对该代码的含义进行有根据的猜测。
在这种情况下,服务器可能应该返回 550
代码,意思是“由于策略原因而拒绝命令”。
关于Java Mail SMTP 硬退回问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66255781/