Table of Contents
1. Loading an .EML file
When saving an email to a file, the resulting file has an eml extension (email files–which are in RFC 822 format). This kind of file can be read and parsed by JavaMail.
import java.util.*; import java.io.*; import javax.mail.*; import javax.mail.internet.*; public class ReadEmail { public static void main(String args[]) throws Exception{ display(new File("C:\\temp\\message.eml")); } public static void display(File emlFile) throws Exception{ Properties props = System.getProperties(); props.put("mail.host", "smtp.dummydomain.com"); props.put("mail.transport.protocol", "smtp"); Session mailSession = Session.getDefaultInstance(props, null); InputStream source = new FileInputStream(emlFile); MimeMessage message = new MimeMessage(mailSession, source); System.out.println("Subject : " + message.getSubject()); System.out.println("From : " + message.getFrom()[0]); System.out.println("--------------"); System.out.println("Body : " + message.getContent()); } }
A typical eml looks like this:
X-Mozilla-Status: 0001 X-Mozilla-Status2: 00000000 Received: from tomts25-srv.bellnexxia.net (tomts25.bellnexxia.net [209.226.175.188]) by tactika.com (8.9.3/8.9.3) with ESMTP id NAA07621 for <real@rgagnon.com>; Sun, 1 Feb 2004 13:25:33 -0500 (EST) Date: Sun, 01 Feb 2004 13:31:40 -0500 From: real gagnon <real@rgagnon.com> Reply-To: real@rgagnon.com User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.4) Gecko/20030624 Netscape/7.1 (ax) X-Accept-Language: en-us, en MIME-Version: 1.0 To: real@rgagnon.com Subject: Example for HowTo Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit X-UIDL: oP#!!c]^!!1;-!!T@1"!
Running the above HowTo gives this output:
Subject : Example for HowTo From : real gagnon <real@rgagnon.com> -------------- Body : This is an example for HowTo
2. Saving an email to .EML file
First you connect to the mail server with POP3 or IMAP protocol to retrieve the emails.
... folder = store.getDefaultFolder().getFolder("INBOX"); folder.open(Folder.READ_ONLY); Message[] messages = folder.getMessages(); ... for (int i=0; i < messages.length; ++i) { Message msg = messages[i]; String subject = msg.getSubject(); processSaveToFile(msg, subject); ... } ...
Individual email are represented by the Message class.
private void processSaveToFile (javax.mail.Message msg, String subject) throws MessagingException, IOException { String whereToSave = "c:/temp/ + sanitizeFilename(subject) + ".eml"; logger.info("Sauvegarde vers "+ whereToSave); OutputStream out = new FileOutputStream(new File(whereToSave)); try { msg.writeTo(out); } finally { if (out != null) { out.flush(); out.close(); } } }
Since the subject is used to set the filename, it’s not a bad idea to sanitize it to remove illegal characters.
private static String sanitizeFilename(String name) { return name.replaceAll("[:\\\\/*?|<> \"]", "_"); }
Done! Happy Coding!
Related posts:
Java Program to Implement Fisher-Yates Algorithm for Array Shuffling
Java String Conversions
Show Hibernate/JPA SQL Statements from Spring Boot
Java Program to Perform Insertion in a 2 Dimension K-D Tree
Giới thiệu Design Patterns
Using the Not Operator in If Conditions in Java
SOAP Web service: Upload và Download file sử dụng MTOM trong JAX-WS
Thao tác với tập tin và thư mục trong Java
Guide to Java 8 groupingBy Collector
So sánh HashSet, LinkedHashSet và TreeSet trong Java
Convert String to Byte Array and Reverse in Java
Intro to Inversion of Control and Dependency Injection with Spring
The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5
Java Program to Check for balanced parenthesis by using Stacks
Quick Guide to @RestClientTest in Spring Boot
Spring NoSuchBeanDefinitionException
Java Program to Compute Determinant of a Matrix
Java Program to Find kth Smallest Element by the Method of Partitioning the Array
Explain about URL and HTTPS protocol
Life Cycle of a Thread in Java
Java Program to Implement Knight’s Tour Problem
Java Program to Generate a Sequence of N Characters for a Given Specific Case
Java Program to Find the Longest Subsequence Common to All Sequences in a Set of Sequences
Java IO vs NIO
JUnit 5 for Kotlin Developers
Server-Sent Events in Spring
Java – Reader to InputStream
Registration with Spring Security – Password Encoding
Lớp Properties trong java
Java Program to Implement Hash Tables Chaining with List Heads
Tránh lỗi NullPointerException trong Java như thế nào?
Java Program to Find k Numbers Closest to Median of S, Where S is a Set of n Numbers