我使用此代码使用 java 发送邮件。在这里,我将一个 pdf 文件附加到邮件中。如果找不到文件,我想抛出并且找不到文件异常。怎么办?
try{
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver));
message.setSubject(subject);
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText("hai");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
//Attachement
messageBodyPart = new MimeBodyPart();
String filename = "file";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(source.getName());
multipart.addBodyPart(messageBodyPart);
}
message.setContent(multipart);
Transport transport = session.getTransport("smtp");
try{
transport.connect(host,from,password);
} catch (AuthenticationFailedException err){
String errMsg = "Authentication fails when sending mail. Sent failed to " + receiver;
log.error(errMsg,err);
throw new AuthenticationFailedException(errMsg + err.getMessage());
}
transport.send(message);
} catch (MessagingException re) {
String localizedError = "Unexpected error occurred at Email client. Sent failed to:" + receiver + ". ";
log.error(localizedError + re.getLocalizedMessage(), re);
throw new MessagingException(localizedError + re.getLocalizedMessage(), re);
}
这是我要添加文件未找到异常的代码