gpt4 book ai didi

java - 通过Java API发送邮件: How to send the mail even if attachment fails?

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

这是我的代码:

try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(messageSubject);
message.setText(messageBody);

BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText(messageBody);
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
String filename = attachment;
DataSource source = new FileDataSource(filename);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart2);
message.setContent(multipart );

Transport.send(message);
} catch (MessagingException mex) {
mex.printStackTrace();
}

即使邮件附件因某种原因失败,我如何仍能发送电子邮件? ATM 如果附件失败,则不会发送电子邮件,这对我来说很糟糕。我应该使用另一个 try/catch 语句吗?我也应该使用finally 吗?我是 Java 新手(3-4 周)

编辑:将我的代码更改为此,但没有工作

try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(messageSubject);
message.setText(messageBody);

try {
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText(messageBody);
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
String filename = attachment;
DataSource source = new FileDataSource(filename);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart2);
message.setContent(multipart);
} catch (Exception e) {
message.setText(messageBody2);
e.printStackTrace();
}

Transport.send(message);

} catch (MessagingException mex) {
mex.printStackTrace();
}

最佳答案

是的。我希望能够做到(伪代码如下)

try {
// set up standard message
try {
// perform attachment
}
catch {
// perhaps amend your original message to indicate attachment failed
}
send();
}
catch {
// handle a complete failure here...
}

尽管我会专注于为什么附件失败。这还有道理吗?

您可以采用两种不同的方法来构建/发送,这样您就不必在遇到故障时清理/修改消息。这可能是一种更干净的方法,例如(再次伪代码)

try {
sendMessageWithAttachment();
}
catch {
sendMessageWithoutAttachment();
}

关于java - 通过Java API发送邮件: How to send the mail even if attachment fails?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18107716/

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