I have a web application where I need to display .eml files (in RFC 822 format) to the users, formatted properly as e-mail - show the HTML to text body properly, show images, attachments and so on. Do you know of a component / library that can do those things?
I prefer it would be in Java (and to integrate with spring easily :-) ), but any other implementation which runs on Apache is fine as well.
Javamail can read EML file.
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());
}
}
Handle EML file with JavaMail
You could convert .eml into javax.mail.Messages mailMessage as:
Loading .eml files into javax.mail.Messages
then you could use this library to convert in MessageBean:
http://javaclue.blogspot.com/2009/09/portable-java-mail-message-bean_02.html
MessageBean mb = MessageBeanUtil.mimeToBean(mailMessage);
Related
Can any one help me with a java code where i want that my html code to be added in body of the mail and the mail client should pop up so that a person can enter the To: and can edit the body if needed.
I have tried this code but this one just sends the mail.What i want is the my mail client should popup with body already entered.
package you;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Properties;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
public class test1 {
public void fnSendMail(String Status) throws IOException, InvalidFormatException, URISyntaxException {
String htmlContent = null;
if (Status.equals("Completed")) {
htmlContent = "<html><br>Below is Test Execution Report.<br>Please find the attached for Detailed Results"
+ "<br><br><table border='1' cellpadding='2' cellspacing='3' width='40%' bordercolor='#999999' style='border-collapse: collapse;'>"
+ "<tr><th>SNo</th><th>Run_Method</th><th>abc_name</th><th>Execution_Status</th></tr>" + "</table>"
+ "<br><br><br><h3 style='color:FireBrick;'>Please do not respond to this mail </h3></html>";
} else {
htmlContent = "<html><br>" + "<h3 style='color:FireBrick;'>Automation got failed due to some issue, hence "
+ "Please verify Maven Errors.<br><br>Execution Status till failure is attached.</h3></html>";
}
String from = "abc#cdf.com";
String host = "x.y.z";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
Multipart multipart = new MimeMultipart();
BodyPart messageBodyText = new MimeBodyPart();
message.setSubject("CSI API Automated Testing Report is " + Status);
messageBodyText.setContent(htmlContent, "text/html");
multipart.addBodyPart(messageBodyText);
message.setContent(multipart);
Transport.send(message);
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
public static void main(String[] args) {
test1 test2= new test1();
try {
test2.fnSendMail("Completed");
System.out.println("Email sent.");
} catch (Exception ex) {
System.out.println("Failed to sent email.");
ex.printStackTrace();
}
}
}
Any other way to do this will also work, but i need is java and javascript only
Instead of calling Transport.send you have to call MimeMessage.saveChanges then use MimeMessage.writeTo to save it to the filesystem as '.eml'. Then open that file with java.awt.Desktop.open to launch the email client. Your system must have a mime association with eml or the open call will fail.
If the O/S mime type for eml is not set to something like outlook.exe /eml %1 then you might have to resort to using the process API to launch outlook directly using the eml switch. For example, if you want to preview the foo.eml draft message then the command would be:
outlook.exe /eml foo.eml
You'll have to handle clean up after the email client is closed.
You also have to think about the security implications of email messages being left on the file system.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I want to generate a PDF document from a "raw" email. This email could containt html or just text. I don't care for attachments.
The resulting pdf should contain the proper formatting (from css and html) and also embedded images.
My first idea was to render the email using an email client like thunderbird and then print it to pdf. Does thunderbird offer such an API or are there java libraries available to print an email to pdf?
I've found a better solution to the one I posted before. saving the email to html, then use jtidy to clean it up to xhtml. and lastly use flying saucer html renderer to save it into pdf.
Here is an example I wrote:
import com.lowagie.text.DocumentException;
import org.w3c.tidy.Tidy;
import org.xhtmlrenderer.pdf.ITextRenderer;
import java.io.*;
import java.util.*;
import javax.mail.*;
public class Email2PDF {
public static void main(String[] args) {
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getInstance(props, null);
Store store = session.getStore();
//read your latest email
store.connect("imap.gmail.com", "youremail#gmail.com", "password");
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message msg = inbox.getMessage(inbox.getMessageCount());
Multipart mp = (Multipart) msg.getContent();
BodyPart bp = mp.getBodyPart(0);
String filename = msg.getSubject();
FileOutputStream os = new FileOutputStream(filename + ".html");
msg.writeTo(os);
//use jtidy to clean up the html
cleanHtml(filename);
//save it into pdf
createPdf(filename);
} catch (Exception mex) {
mex.printStackTrace();
}
}
public static void cleanHtml(String filename) {
File file = new File(filename + ".html");
InputStream in = null;
try {
in = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
OutputStream out = null;
try {
out = new FileOutputStream(filename + ".xhtml");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
final Tidy tidy = new Tidy();
tidy.setQuiet(false);
tidy.setShowWarnings(true);
tidy.setShowErrors(0);
tidy.setMakeClean(true);
tidy.setForceOutput(true);
org.w3c.dom.Document document = tidy.parseDOM(in, out);
}
public static void createPdf(String filename)
throws IOException, DocumentException {
OutputStream os = new FileOutputStream(filename + ".pdf");
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(new File(filename + ".xhtml"));
renderer.layout();
renderer.createPDF(os) ;
os.close();
}
}
Enjoy!
I put a piece of software together that converts eml files to pdf's by parsing (and cleaning) the mime/structure, converting it to html and then use wkhtmltopdf to convert it to a pdf file.
It also handles inline images, corrupt mime headers and can use a proxy.
The code is available at github under apache V2 license.
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import javax.mail.*;
public class Email2PDF {
public static void main(String[] args) {
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getInstance(props, null);
Store store = session.getStore();
store.connect("imap.gmail.com", "youremail#gmail.com", "password");
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message msg = inbox.getMessage(inbox.getMessageCount());
Multipart mp = (Multipart) msg.getContent();
BodyPart bp = mp.getBodyPart(0);
createPdf(msg.getSubject(), (String) bp.getContent());
} catch (Exception mex) {
mex.printStackTrace();
}
}
public static void createPdf(String filename, String body)
throws DocumentException, IOException {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(filename + ".pdf"));
document.open();
document.add(new Paragraph(body));
document.close();
}
}
I've used itext as the pdf library
You can read HTML content using email client and then use iText to convert it in to PDF
Look into fpdf and fpdi, both free libraries for PHP are used in the creation of PDF docs.
Since the SMTP protocol has conventions, actually strict rules, you can always count on the first empty line to be the before the content of the message. So you can definitely parse everything after the first part of the line to get the entirety of the message.
For embedded images, you'll need a base 64 decoder (usually) or some other decoder based on the email's attachment encoding type to transform the data into a human readable image.
You could try the Apache PDFbox library.
It seems to have a nice API and it also supports printing. PrintPDF
You would have to run the print command from CLI with your file as a parameter.
Edit: It is Java and open-source.
Hope it helps!
I'm using javamail to read emails from gmail Trash folder and if there is email in Draft folder with attachments then these attachments appear in Trash folder.
Steps to reproduce:
1) create new email with attachment(s) and close it, it appears in Draft folder. 2) Read emails from Trash folder using program below. Attachment(s) from draft email appear. If I open Trash folder in browser I don't see these attachments. Do you know why attachment appear in Trash folder when emails are read using javamail?
import java.io.IOException;
import java.util.Properties;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
public class MailClient {
public static void main(String[] args) throws Exception {
MailClient client = new MailClient();
client.execute();
}
void execute() throws MessagingException, IOException {
String[] credentials = new String[] {"name#gmail.com", "password"};
boolean debug = false;
Folder folder = null;
Store store = null;
try {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getDefaultInstance(props, null);
session.setDebug(debug);
store = session.getStore("imaps");
store.connect("imap.gmail.com", credentials[0], credentials[1]);
folder = store.getFolder("[Gmail]/Trash");
folder.open(Folder.READ_WRITE);
Message messages[] = folder.getMessages();
System.out.println("No of Messages : " + folder.getMessageCount());
System.out.println("No of Unread Messages : " + folder.getUnreadMessageCount());
for (int i = 0; i < messages.length; ++i) {
System.out.println("MESSAGE #" + (i + 1) + ":");
Message msg = messages[i];
String from = "unknown";
if (msg.getReplyTo().length >= 1) {
from = msg.getReplyTo()[0].toString();
} else if (msg.getFrom().length >= 1) {
from = msg.getFrom()[0].toString();
}
String subject = msg.getSubject();
System.out.println(subject);
msg.setFlag(Flags.Flag.SEEN, true);
}
} finally {
if (folder != null) {
folder.close(true);
}
if (store != null) {
store.close();
}
}
}
}
Your program doesn't do anything with attachments. Why do you believe the attachments for the draft message, but not the message itself, appear in the Trash folder? And what message in the Trash folder are those attachments attached to?
How are you creating the Draft message? Through the Gmail web interface? Is it possible that Gmail is saving multiple drafts of your draft message, and the old drafts are being moved into the Trash folder, with only the latest draft left in the Drafts folder?
I have successfully followed tutorials of how to embed images into HTML with javamail. However i am now trying to read from a template html file and then embed images into this before sending.
I am sure that the code is right for the embedding images as when i use:
bodyPart.setContent("<html><body><h2>A title</h2>Some text in here<br/>" +
"<img src=\"cid:the-img-1\"/><br/> some more text<img src=\"cid:the-img-1\"/></body></html>", "text/html");
The images display fine. However when i read from a file using:
readHTMLToString reader = new readHTMLToString();
String str = reader.readHTML();
bodyPart.setContent(str, "text/html");
The images do not show up when the email sends.
My code for reading the html to string is as follows:
public class readHTMLToString {
static String finalFile;
public static String readHTML() throws IOException{
//intilize an InputStream
File htmlfile = new File("C:/temp/basictest.html");
System.out.println(htmlfile.exists());
try {
FileInputStream fin = new FileInputStream(htmlfile);
byte[] buffer= new byte[(int)htmlfile.length()];
new DataInputStream(fin).readFully(buffer);
fin.close();
String s = new String(buffer, "UTF-8");
finalFile = s;
}
catch(FileNotFoundException e)
{
System.out.println("File not found" + e);
}
catch(IOException ioe)
{
System.out.println("Exception while reading the file " + ioe);
}
return finalFile;
}
}
My complete class for sending the email is as follows:
package com.bcs.test;
import java.io.IOException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class SendEmail {
public static void main(String[] args) throws IOException {
final String username = "usernamehere#gmail.com";
final String password = "passwordhere";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from-email#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("recepientemailhere"));
message.setSubject("Testing Subject");
//SET MESSAGE AS HTML
MimeMultipart multipart = new MimeMultipart("related");
// Create bodypart.
BodyPart bodyPart = new MimeBodyPart();
// Create the HTML with link to image CID.
// Prefix the link with "cid:".
//bodyPart.setContent("<html><body><h2>A title</h2>Some text in here<br/>" +
// "<img src=\"cid:the-img-1\"/><br/> some more text<img src=\"cid:the-img-1\"/></body></html>", "text/html");
readHTMLToString reader = new readHTMLToString();
String str = reader.readHTML();
// Set the MIME-type to HTML.
bodyPart.setContent(str, "text/html");
// Add the HTML bodypart to the multipart.
multipart.addBodyPart(bodyPart);
// Create another bodypart to include the image attachment.
BodyPart imgPart = new MimeBodyPart();
// Read image from file system.
DataSource ds = new FileDataSource("C:\\temp\\dice.png");
imgPart.setDataHandler(new DataHandler(ds));
// Set the content-ID of the image attachment.
// Enclose the image CID with the lesser and greater signs.
imgPart.setDisposition(MimeBodyPart.INLINE);
imgPart.setHeader("Content-ID","the-img-1");
//bodyPart.setHeader("Content-ID", "<image_cid>");
// Add image attachment to multipart.
multipart.addBodyPart(imgPart);
// Add multipart content to message.
message.setContent(multipart);
//message.setText("Dear Mail Crawler,"
// + "\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
Ive read through numerous answers about this but really not sure why this is happening. I thought it was because of an issue with my html file however i created a very basic one using the same content as the initial setContent code above and the pictures dont appear in this basic example.
Something to do with reading into a byte array?
Any help greatly appreciated.
Thanks
The way email clients interpret HTML code is different from writing to HTML template file. But one thing you could try for sure is once you get the template, copy the byte array of the image to the src attribute. You could try with inline images as browser inteprets src attribute and make another request to get the data.
Gives you a lot more insight in to the concept.Inline Images in HTML
Of course you need to make sure that the data in the file is actually encoded in UTF-8 and not in the default encoding for your computer. If you test this with all ASCII text, it shouldn't matter.
Assuming you have the same text in the file that you have in the string in the sample code above, you can compare the two cases (string, file) to see how the messages JavaMail would send differ by using message.writeTo(new FileOutputStream("msg.txt")); just before or in place of the Transport.send call.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do you send email from a Java app using Gmail?
How do I send an SMTP Message from Java?
Here's an example for Gmail smtp:
import java.io.*;
import java.net.InetAddress;
import java.util.Properties;
import java.util.Date;
import javax.mail.*;
import javax.mail.internet.*;
import com.sun.mail.smtp.*;
public class Distribution {
public static void main(String args[]) throws Exception {
Properties props = System.getProperties();
props.put("mail.smtps.host","smtp.gmail.com");
props.put("mail.smtps.auth","true");
Session session = Session.getInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("mail#tovare.com"));;
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("tov.are.jacobsen#iss.no", false));
msg.setSubject("Heisann "+System.currentTimeMillis());
msg.setText("Med vennlig hilsennTov Are Jacobsen");
msg.setHeader("X-Mailer", "Tov Are's program");
msg.setSentDate(new Date());
SMTPTransport t =
(SMTPTransport)session.getTransport("smtps");
t.connect("smtp.gmail.com", "admin#tovare.com", "<insert password here>");
t.sendMessage(msg, msg.getAllRecipients());
System.out.println("Response: " + t.getLastServerResponse());
t.close();
}
}
Now, do it this way only if you would like to keep your project dependencies to a minimum, otherwise i can warmly recommend using classes from apache
http://commons.apache.org/email/
Regards
Tov Are Jacobsen
Another way is to use aspirin (https://github.com/masukomi/aspirin) like this:
MailQue.queMail(MimeMessage message)
..after having constructed your mimemessage as above.
Aspirin is an smtp 'server' so you don't have to configure it. But note that sending email to a broad set of recipients isnt as simple as it appears because of the many different spam filtering rules receiving mail servers and client applications apply.
Please see this post
How can I send an email by Java application using GMail, Yahoo, or Hotmail?
It is specific to gmail but you can substitute your smtp credentials.
See the following tutorial at Java Practices.
http://www.javapractices.com/topic/TopicAction.do?Id=144
See the JavaMail API and associated javadocs.
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public void postMail(String recipients[], String subject,
String message , String from) throws MessagingException {
//Set the host smtp address
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.jcom.net");
// create some properties and get the default Session
Session session = Session.getDefaultInstance(props, null);
session.setDebug(false);
// create a message
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Optional : You can also set your custom headers in the Email if you Want
msg.addHeader("MyHeaderName", "myHeaderValue");
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
}