我正在开发一个需要向客户发送提醒的网络应用程序。我正在使用 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);
}
}
}