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);
The email will look like this:

This comment has been removed by the author.
ReplyDelete