我正在开发一个需要向客户发送提醒的网络应用。我正在使用JavaMail。但是当我提供无效的接收者电子邮件地址(电子邮件ID不存在)时,程序 不会抛出 SendFailedException
。 但发件人电子邮件ID的收件箱中包含发送邮件发送失败的递送报告。有没有办法在程序中检测到这个失败 ?使用的代码如下:
[注意使用了gmail smpt]
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.stmp.user", "abc@gmail.com");
//If you want you use TLS
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.password", "password");
// If you want to use SSL
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
String username = "abc@gmail.com";
String password = "password";
return new PasswordAuthentication(username,password);
}
});
String[] to = {"test1@gmail.com","test2@yahoo.in","test3@gmail.com","test4@gmail.com"};
String from = "abc@gmail.com";
String subject = "Testing...";
MimeMessage msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(from));
InternetAddress[] addressTo = new InternetAddress[to.length];
for (int i = 0; i < to.length; i++)
{
addressTo[i] = new InternetAddress(to[i]);
}
msg.setRecipients(RecipientType.TO, addressTo);
// msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
// msg.setText("JAVA is the BEST");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText("This is message body");
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = "file.txt";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
msg.setContent(multipart );
Transport transport = session.getTransport("smtp");
transport.send(msg);
System.out.println("E-mail sent !");
}
catch(Exception exc) {
System.out.println(exc);
}
}
}
答案 0 :(得分:0)
您可能误解了how "store and forward" works for email:发件人很少会立即知道该地址无效。这很可能是域名无效的情况,但即使这样,您也无法保证SMTP会话将报告错误,因为这取决于您提供的MTA如何处理电子邮件。