Create a .eml (email) file in Java

前端 未结 5 819
不思量自难忘°
不思量自难忘° 2020-12-01 07:50

Anybody knows how to do this? I got all the information of the email (body, subject, from , to, cc, bcc) and need to generate an .eml file out of it.

5条回答
  •  Happy的楠姐
    2020-12-01 08:33

    You can create eml files with the following code. It works fine with thunderbird and probably with other email clients:

    public static void createMessage(String to, String from, String subject, String body, List 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);
        }
    }
    

提交回复
热议问题