Create an email object in java and save it to file

后端 未结 2 1985
执笔经年
执笔经年 2020-12-16 06:22

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-li

相关标签:
2条回答
  • 2020-12-16 07:17

    You create a Message object the same way you would create one for sending, but instead of sending it you write it to a file. You don't need an email server. There's lots of examples of creating messages in the demo programs included with the JavaMail download, and in the JavaMail FAQ. See the Message.writeTo method to write the message to a file (Message is a Part, and writeTo is on Part).

    0 讨论(0)
  • 2020-12-16 07:17

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题