Add attachments to existing eml file

拟墨画扇 提交于 2019-12-25 04:19:53

问题


I have an existing eml file which contain among others body and attachments.

I simply want to add attachments to this file, not erase existing onlt to add attachments.

I have this code to create 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);
}

}

But how do i add to existing rather then create?


回答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);
}

In the above method, a new bodypart is created with the attachment, and that bodypart is then added to the multipart of the e-mail which is already there.



来源:https://stackoverflow.com/questions/24157468/add-attachments-to-existing-eml-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!