Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save an email as .eml with X-Unsent: 1 using Message.writeTo

I want email to be saved as .eml format with attachments. I able to save the .eml but when i open it, it should be opened in draft format where user should be able to enter from, to , subject and also edit email body. Curently i have to manually edit the saved .eml file to add X-Unsent:1 to display as draft. how can i achieve this in code, which property of mimeMessage can help me do it?

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

}

like image 638
Divya Mehta Avatar asked Dec 01 '17 10:12

Divya Mehta


1 Answers

How about adding this line:

 message.setHeader("X-Unsent", "1");
like image 117
PKey Avatar answered Nov 08 '22 19:11

PKey