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 = "jverstry@gmail.com";
String from = "ffff@ooop.com";

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

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

// Providing email and password access to mail server
ps.setProperty("mail.user", "jverstry@gmail.com");
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));
m.addRecipient(
    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 !!!");
mp.addBodyPart(messageBP);

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

InputStream is = EmailWithAttachment.class
    .getResourceAsStream(image);

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

messageBP2.setDataHandler(new DataHandler(source));
mp.addBodyPart(messageBP2);
m.setContent(mp);

// Sending the message
Transport.send(m);
We use the Apache IOUtils tool to convert our image into a byte array.

The email will look like this:

Email With Image Attachment

1 comment: