【问题标题】:Add attachments to existing eml file将附件添加到现有 eml 文件
【发布时间】:2014-08-01 04:31:35
【问题描述】:

我有一个现有的 eml 文件,其中包含正文和附件。

我只是想在这个文件中添加附件,而不是删除现有的添加附件。

我有这个代码来创建 eml:

public static void createMessage(String to, String from, String subject, String body, List<File> attachments) {
try {
    Message message = new MimeMessage(Session.getInstance(System.getProperties()));
    message.setFrom(new InternetAddress(from));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
    message.setSubject(subject);
    // create the message part 
    MimeBodyPart content = new MimeBodyPart();
    // fill message
    content.setText(body);
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(content);
    // add attachments
    for(File file : attachments) {
        MimeBodyPart attachment = new MimeBodyPart();
        DataSource source = new FileDataSource(file);
        attachment.setDataHandler(new DataHandler(source));
        attachment.setFileName(file.getName());
        multipart.addBodyPart(attachment);
    }
    // integration
    message.setContent(multipart);
    // store file
    message.writeTo(new FileOutputStream(new File("c:/mail.eml")));
} catch (MessagingException ex) {
    Logger.getLogger(Mailkit.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
    Logger.getLogger(Mailkit.class.getName()).log(Level.SEVERE, null, ex);
}

}

但是我如何添加到现有而不是创建?

【问题讨论】:

    标签: java jakarta-mail eml


    【解决方案1】:
    public static void addAttachment(Message msg, File attachment) throws Exception {
        //Create the new body part and add the file
        MimeBodyPart attachment = new MimeBodyPart();
        DataSource source = new FileDataSource(file);
        attachment.setDataHandler(new DataHandler(source));
        attachment.setFileName(file.getName());
    
        //Add the new body part to the e-mail
        msg.getContent().addBodyPart(attachment);
    }
    

    在上述方法中,使用附件创建一个新的正文部分,然后将该正文部分添加到已经存在的电子邮件的多部分中。

    【讨论】:

    • 假设现有的 eml 文件始终是并且仅是具有单个多部分的消息。您需要在其中进行转换才能将 getContent() 的结果转换为 Multipart。
    猜你喜欢
    • 1970-01-01
    • 2016-07-10
    • 2011-02-16
    • 2019-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-04
    • 2021-06-22
    相关资源
    最近更新 更多