如何从JavaMailSender异常中检索附件名称?

时间:2015-04-09 22:52:05

标签: spring javamail

我正在使用org.springframework.mail.javamail.JavaMailSender(Spring Framework 4.1.6)。我通过致电发送了多封电子邮件:

mailSender.send(mimeMessagePreparators);

其中mimeMessagePreparators是MimeMessagePreparator数组。每个MimeMessagePreparator构建如下:

        MimeMessagePreparator mimeMessagePreparator = new MimeMessagePreparator() {
            public void prepare(MimeMessage mimeMessage) throws MessagingException {

                MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);

                // get the subscribers of the attachment and put them as the recipients
                // of this email
                mimeMessageHelper.setTo(subscribers);

                // all email have the same from, bcc, reply to, subject, and body
                String fromEmailAddress = emailTemplate.getFromEmailAddress();
                mimeMessageHelper.setFrom(fromEmailAddress);

                // note: bcc the sender so that they get the email too
                mimeMessageHelper.setBcc(fromEmailAddress);

                // this will help on auto replies and bounce messages
                // also it should help on deliverability
                mimeMessageHelper.setReplyTo(fromEmailAddress);

                String subject = emailTemplate.getSubject();
                mimeMessageHelper.setSubject(subject);

                String emailBody = emailTemplate.getBody();
                mimeMessageHelper.setText(OPEN_EMAIL_TAGS + emailBody + CLOSE_EMAIL_TAGS, true);

                // get the physical file and add as an email attachment
                FileSystemResource file = new FileSystemResource(new File(directory, attachment.getName()));
                mimeMessageHelper.addAttachment(attachment.getName(), file);

            }
        };

我需要知道哪些电子邮件失败(即发生了MailException),并最终告诉用户与失败的电子邮件关联的附件的名称。如何从例外中检索附件名称?到目前为止,我有

try {
        mailSender.send(mimeMessagePreparators);
} catch (MailSendException mailSendException) {

        Map<Object, Exception> map = mailSendException.getFailedMessages();

        for (Map.Entry<Object, Exception> entry : map.entrySet()) {
            MimeMessage mimeMessage = (MimeMessage) entry.getKey();
            // get attachment names from mimeMessage? or preferably
            // get in a more simplistic way using a helper such as MimeMessageHelper
} catch (MailException mailException) {
    // how do I get attachment names here?
}

1 个答案:

答案 0 :(得分:1)

如果您有一堆MimeMessage对象,请从此处查看JavaMail FAQ条目:

基本上,您需要迭代消息中的部分,确定哪些部分代表附件,然后访问您认为代表附件“名称”的部分中的任何元数据或标题。