Wednesday, 26 September 2012

Adding An Image Attachment To An Email In Java

This post describes how to add an image attachment to an email in Java. The code example is available from Github in the Java-Email-Sending directory. To make it work, you will need to set a proper 'to' email address in the code, together with a sending email server login and password if necessary.

Adding An Image Attachment

The following adds a text body to the email, together with image:
String to = "";
String from = "";

// Which server is sending the email?
String host = "localhost";

// Setting sending mail server
Properties ps = System.getProperties();
ps.setProperty("", host);

// Providing email and password access to mail server
ps.setProperty("mail.user", "");
ps.setProperty("mail.password", "xxxxxxxxxxxxx");

// Retrieving the mail session
Session session = Session.getDefaultInstance(ps);

// Create a default MimeMessage
MimeMessage m = new MimeMessage(session);
m.setFrom(new InternetAddress(from));
    Message.RecipientType.TO, new InternetAddress(to));
m.setSubject("This an email test !!!");

// Create a multipart message
Multipart mp = new MimeMultipart();

// Body text
BodyPart messageBP = new MimeBodyPart();
messageBP.setText("Some message body !!!");

// Attachment
BodyPart messageBP2 = new MimeBodyPart();
String image = "/MyImage.jpg";

InputStream is = EmailWithAttachment.class

DataSource source = new ByteArrayDataSource(
    IOUtils.toByteArray(is), "image/jpeg");

messageBP2.setDataHandler(new DataHandler(source));

// Sending the message
We use the Apache IOUtils tool to convert our image into a byte array.

The email will look like this:

Email With Image Attachment