通过Java API发送邮件:即使附件失败,如何发送邮件?

时间:2013-08-07 15:39:48

标签: java

这是我的代码:

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();
}

1 个答案:

答案 0 :(得分: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();
}