我在发送电子邮件时遇到异常问题。这是我下面的代码
public static void sendEmail(String email, String subjectBody, String srcAndFile) throws Exception {
System.out.println(srcAndFile);
try {
logger.debug("sending email to: " + email + "with attached file: " + srcAndFile);
Properties props = System.getProperties();
props.put("mail.smtp.host", address);
props.put("mail.smtp.port", "25");
props.put("mail.smtp.auth", "false");
Session session_m = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session_m);
message.setFrom (new InternetAddress(sender, sender));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
message.setSubject(subjectBody);
message.setText("Hi");
message.setHeader("Content-Type","text/plain;charset=windows-1251");
Multipart multiPart = new MimeMultipart();
MimeBodyPart messageText = new MimeBodyPart();
messageText.setContent(subjectBody, "text/plain");
multiPart.addBodyPart(messageText);
MimeBodyPart rarAttachment = new MimeBodyPart();
File f = new File(srcAndFile);
FileDataSource rarFile = new FileDataSource(f);
rarAttachment.setDataHandler(new DataHandler(rarFile));
rarAttachment.setFileName(rarFile.getName());
multiPart.addBodyPart(rarAttachment);
message.setContent(multiPart);
SMTPTransport t = (SMTPTransport)session_m.getTransport("smtp");
t.connect(addrress, sender, null);
t.sendMessage(message, message.getAllRecipients());
success = true;
} catch (AddressException e) {
logger.error(e.getMessage());
throw new AddressException("[sendEmail]: Incorrect email address");
} catch (MessagingException e) {
logger.error(e.getMessage());
throw new MessagingException("[sendEmail]: Unable to send email");
} catch (IOException e) {
logger.error(e.getMessage());
throw new IOException("[sendEmail]: Unable to find file to attach");
} catch (Exception e) {
logger.error(e.getMessage());
DBWrapper.processStatusDB("[sendEmail]","failed",e.getMessage());
throw new Exception("[sendEmail]: Error in method " + e.getMessage());
}
DBWrapper.processStatusDB("[sendEmail]","finished","process to send an email with " + FileManager.getFile(srcAndFile) + " has finished properly");
}
现在,当我想捕获一些错误时,问题就出现了:
无效地址
无法连接到服务器
这两种情况都发生在 (MessagingException e) 上。有没有办法将它们拆分为不同的异常。
问题是,如果收件人的电子邮件地址无效,我的程序应该与其他收件人一起继续。但是如果程序无法连接到邮件服务器,那么程序应该终止。但在我的情况下,即使电子邮件地址无效,它也会终止。由于 (MessagingException e) 引发错误,如代码所示。
是否有任何其他异常可以捕获 INVALID EMAIL ADDRESS?(AddressException e) 未捕获无效电子邮件的错误。
谢谢你。