0

这是我的代码:

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 语句吗?最后我也应该使用吗?我是 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();
}
4

1 回答 1

4

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

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();
}
于 2013-08-07T15:42:17.403 回答