Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an email object in java and save it to file

i need to backup the emails contained in a PST file (outlook storage). i'm using libpst which is the only free library i found on the web ( http://code.google.com/p/java-libpst/ )

so i can access all the information in each single email (subject, body, sender ecc..), but i need to put them on a file

here someone said you can create an EML file from a "javax.mail.Message" object: Create a .eml (email) file in Java

the problem is: how do i create this Message object? i don't have a server or an email session, just the information contained in the email

p.s. creating a .msg file would be fine too

like image 617
Pronte Avatar asked Nov 17 '11 13:11

Pronte


1 Answers

Here's the code to create a valid eml file with java mail api. works fine with thunderbird and probably other email clients:

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 59
salocinx Avatar answered Sep 24 '22 01:09

salocinx