gpt4 book ai didi

java - 如何添加文件找不到此代码的异常(exception)?

转载 作者:行者123 更新时间:2023-12-03 09:03:12 24 4
gpt4 key购买 nike

我使用此代码使用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);
}

这是我要添加文件的代码未找到异常

最佳答案

我本以为FileDataSource或DataHandler都可以做到这一点,但如果没有,只需添加:

new FileInputStream(filename).close();

在将filename参数传递给FileDataSource之前。
它将为您抛出该异常。

关于java - 如何添加文件找不到此代码的异常(exception)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11899559/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com