sumanth
sumanth

Reputation:

Adding image to email via Java mail

Here is my code:

MimeMessage mail = new MimeMessage(session);
mail.setFrom(from);
MimeMultipart multipart = new MimeMultipart("related");
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(bodyText, "text/html");

multipart.addBodyPart(htmlPart);

MimeBodyPart imgPart=new MimeBodyPart();
String path = "/ivr/imagelogos/accenture.jpg";
DataSource ds=new FileDataSource(path);
imgPart.setDataHandler(new DataHandler(ds));    
imgPart.setHeader("Content-ID","the-img-1");
multipart.addBodyPart(imgPart);

mail.setContent(multipart);

mail.setSentDate(new Date());
mail.setHeader("X-Mailer", "ALS Notifier Build 1.0.0.10");

// send the message
Transport.send(mail);

The code is being ran on a unix box - image path is based on unix file paths.

After running the code I receive this error:

IOException while sending message
javax.mail.MessagingException: IOException while sending message;
  nested exception is:
        java.io.FileNotFoundException: /ivr/imagelogos/accenture.jpg (No such file or directory)
        at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:676)

Upvotes: 0

Views: 4482

Answers (2)

Ms. Art
Ms. Art

Reputation: 11

Img src= is the most efficient way to insert just a few images, otherwise you may find it useful/helpful to define an array for multiple images.

Upvotes: 1

Eric Petroelje
Eric Petroelje

Reputation: 60559

Sounds like the /ivr/imagelogos/accenture.jpg file doesn't exist. Are you sure that's the right path? Maybe it's supposed to be relative to some other path? If it does exist, does the user running the Java app have read permissions on it?

Upvotes: 2

Related Questions