将附件添加到现有的eml文件 [英] Add attachments to existing eml file

查看:278
本文介绍了将附件添加到现有的eml文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我只是想向该文件添加附件,而不是删除现有的onlt以添加附件.

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

我有这段代码可以创建eml:

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?

推荐答案

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.

这篇关于将附件添加到现有的eml文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆