2014-06-11 128 views
0

我有一個現有的eml文件,其中包含正文和附件。將附件添加到現有的eml文件

我只是想添加附件到這個文件,而不是抹掉現有的onlt來添加附件。

我有這樣的代碼來創建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); 
} 

}

但我怎麼添加到現有的而不是創造?

回答

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

在上面的方法中,使用附件創建一個新的bodypart,然後bodypart被添加到已經存在的電子郵件的多部分。

+0

假定現有的eml文件始終是唯一一個帶有單個多部分的消息。並且您需要在那裏爲getContent()的結果強制轉換爲Multipart。 –