DMS
DMS

Reputation: 818

How can we send image which is used in html as an attachment for email in JAVA?

I am trying to send a report which is generated through java code. I am using jasper report to generate various reports. In my report I have image in header. This works fine with all formats(PDF,XLS, RTF) of report except HTML. It do not show image in HTML report as it is not able to find the image.

How can I send image with email and use with HTML report using Java Mail?

Upvotes: 2

Views: 3069

Answers (4)

Amitabh
Amitabh

Reputation: 172

Send html email using JavaMail with embedded images and attachments to go. (My last post was deleted because it was a link (https://github.com/QuickrWorld/email-sender.git). I think the point was valid -- what if the git repository was deleted or modified so much that it no longer was a valid answer?). So I have added the code directly in the response below. Though, I'm still wondering why my answer was singled out for deletion. Other answers in this post also are just links. Or am I missing something?)

// EmailSender.java
package com.quickrworld.mail;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.URLDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
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;

public class EmailSender {
  static Properties p = null;
  static Properties getDefaultProperties() {
    if (p == null) {
      p = new Properties();
      String mailSmtpHost = "smtp.gmail.com";
      String mailSmtpAuth = "true";
      String mailSmtpPort = "465";
      String mailSmtpSocketFactoryPort = "465";
      String mailSmtpSocketFactoryClass = "javax.net.ssl.SSLSocketFactory";
      String mailSmtpSocketFactoryFallback = "false";
      String mailDebug = "false";
      p.put("mail.smtp.host", mailSmtpHost);
      p.put("mail.smtp.auth", mailSmtpAuth);
      p.put("mail.smtp.port", mailSmtpPort);
      p.put("mail.smtp.socketFactory.port", mailSmtpSocketFactoryPort);
      p.put("mail.smtp.socketFactory.class", mailSmtpSocketFactoryClass);
      p.put("mail.smtp.socketFactory.fallback",
          mailSmtpSocketFactoryFallback);
      // p.put("mail.smtp.starttls.enable","true");
      // p.put("mail.smtp.EnableSSL.enable","true");
      p.put("mail.debug", mailDebug);
    }
    return p;
  }

  public void sendMessage(
      String mailSubject, 
      String mailFrom,
      List<String> mailTos, 
      List<String> mailCcs, 
      List<String> mailBccs,
      String html, 
      List<ImageResource> images, 
      List<Resource> attachments,
      Properties p, 
      String user, 
      String password) throws MessagingException, MalformedURLException {
    Session s = Session.getInstance(p);
    Message m = new MimeMessage(s);
    m.setSubject(mailSubject);
    InternetAddress from = new InternetAddress(mailFrom);
    for (String mailTo : mailTos) {
      InternetAddress to = new InternetAddress(mailTo);
      m.addRecipient(Message.RecipientType.TO, to);
    }
    for (String mailCc : mailCcs) {
      InternetAddress cc = new InternetAddress(mailCc);
      m.addRecipient(Message.RecipientType.CC, cc);
    }
    for (String mailBcc : mailBccs) {
      InternetAddress bcc = new InternetAddress(mailBcc);
      m.addRecipient(Message.RecipientType.BCC, bcc);
    }
    m.setFrom(from);
    Multipart multipart = new MimeMultipart("related");
    // html
    BodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(html, "text/html");
    multipart.addBodyPart(htmlPart);
    // images
    for (ImageResource imageResource : images) {
      String path = imageResource.getPath();
      String fileName = imageResource.getName();
      String cid = imageResource.getCid();
      boolean isURL = imageResource.isURL();
      addImageWithCid(multipart, path, fileName, cid, isURL);
    }
    // attachments
    for (Resource attachment : attachments) {
      addAttachment(multipart, attachment);
    }
    // message
    m.setContent(multipart);
    // send
    Transport transport = s.getTransport("smtp");
    transport.connect(user, password);
    transport.sendMessage(m, m.getAllRecipients()); // Actually this can be any valid address set
    transport.close();
  }

  private void addAttachment(Multipart multipart, 
      Resource attachment) throws MessagingException, MalformedURLException {
    String attachmentPath = attachment.getPath();
    String attachmentName = attachment.getName();
    boolean isURL = attachment.isURL();
    if(isURL) {
      BodyPart attachmentBodyPart = new MimeBodyPart();
      URL attachmentURL = new URL(attachmentPath);
      URLDataSource source = new URLDataSource(attachmentURL);
      attachmentBodyPart.setDataHandler(new DataHandler(source));
      attachmentBodyPart.setFileName(attachmentName);
      multipart.addBodyPart(attachmentBodyPart);      
    } else {
      BodyPart attachmentBodyPart = new MimeBodyPart();
      DataSource source = new FileDataSource(attachmentPath);
      attachmentBodyPart.setDataHandler(new DataHandler(source));
      attachmentBodyPart.setFileName(attachmentName);
      multipart.addBodyPart(attachmentBodyPart);
    }
  }

  private void addImageWithCid(
      Multipart multipart, 
      String imageFilePath,
      String imageFileName,
      String imageFileCid, 
      boolean isURL) throws MessagingException, MalformedURLException {    
    if(isURL) {
      BodyPart imgPart = new MimeBodyPart();
      URL imageFileURL = new URL(imageFilePath);
      URLDataSource ds = new URLDataSource(imageFileURL);
      imgPart.setDataHandler(new DataHandler(ds));
      imgPart.setHeader("Content-ID", imageFileCid);
      imgPart.setFileName(imageFileName);
      multipart.addBodyPart(imgPart);
    } else {
      BodyPart imgPart = new MimeBodyPart();
      DataSource ds = new FileDataSource(imageFilePath);
      imgPart.setDataHandler(new DataHandler(ds));
      imgPart.setHeader("Content-ID", imageFileCid);
      imgPart.setFileName(imageFileName);
      multipart.addBodyPart(imgPart);
    }
  }
}
// Resource.java
package com.quickrworld.mail;

public class Resource {
  private String path;
  private String name;
  private boolean isURL;
  public Resource() {

  }
  public Resource(String path, boolean isURL) {
    this(path, path, isURL);
  }
  public Resource(String path, String name, boolean isURL) {
    this.path = path;
    this.name = name;
    this.isURL = isURL;
  }
  public String getPath() {
    return path;
  }
  public void setPath(String path) {
    this.path = path;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public boolean isURL() {
    return isURL;
  }
  public void setURL(boolean isURL) {
    this.isURL = isURL;
  }
}
// ImageResource.java
package com.quickrworld.mail;

public class ImageResource extends Resource {
  private String cid;
  public ImageResource() {
    super();
  }
  public ImageResource(String path, String name, String cid, boolean isURL) {
    super(path, name, isURL);
    this.cid = cid;
  }
  public String getCid() {
    return cid;
  }
  public void setCid(String cid) {
    this.cid = cid;
  }
}
// EmailMain.java
package com.quickrworld.mail;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.mail.MessagingException;

public class EmailMain {
  // Please ensure you have a tomcat running on port 8080 on localhost (for tomcat.png and favicon.ico)
  // please ensure you have files file1.txt and file2.txt in the working directory (for attachments)
  public static void main(String[] args) {
    EmailSender emailSender = new EmailSender();
    String mailSubject = "My Mail Subject (Named)";
    String mailFrom = "[email protected]";
    List<String> mailTos = new ArrayList<String>();
    mailTos.add("[email protected]");
    List<String> mailCcs = new ArrayList<String>();
    mailCcs.add("[email protected]");
    List<String> mailBccs = new ArrayList<String>();
    mailBccs.add("[email protected]");
    String html = "<html><body><h2>Heading</h2>Our logo:<br/>"
        + "<img src=\"cid:img-cid-1\"/><br/>See images in the email - and two attachments<br/>"
        + "<div><img src=\"cid:img-cid-2\"/></div></body></html>";
    // remove the values for user and password before posting to git
    String user = "[email protected]";
    String password = "password";
    Properties p = EmailSender.getDefaultProperties();
    p.put("mail.debug", "true");
    List<ImageResource> imageResources = new ArrayList<ImageResource>();
    imageResources.add(new ImageResource("logo.png","logo.png","<img-cid-1>",false));
    imageResources.add(new ImageResource("http://localhost:8080/favicon.ico","favicon.ico","<img-cid-2>",true));    
    List<Resource> attachmentResources = new ArrayList<Resource>();
    attachmentResources.add(new Resource("file1.txt", "attached-file1.txt", false));
    attachmentResources.add(new Resource("file2.txt", "attached-file2.txt", false));
    attachmentResources.add(new Resource("http://localhost:8080/tomcat.gif","attached-tomcat.gif",true));    
    try {
      emailSender.sendMessage(mailSubject, mailFrom, mailTos, mailCcs,
          mailBccs, html, imageResources,
          attachmentResources, p, user, password);
    } catch (MessagingException e) {
      e.printStackTrace();
    } catch (MalformedURLException e) {
      e.printStackTrace();
    }
  }
}

Upvotes: 1

sperumal
sperumal

Reputation: 1519

You can use absolute URL (e.g http://servername.com/images/xyz.jpg) instead of relative URL. JasperReport can be configured to use absolute URL.

Or

I don't know whether this works in embedded emails. But you can try using inline images, you have to convert your image to base64 string. This will increase the size of your HTML if the images are too big and its hard to maintain when image changes.

<img src="data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub/    /ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcppV0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7" width="16" height="14" alt="embedded folder icon">

Upvotes: 2

Cygnusx1
Cygnusx1

Reputation: 5409

It works with PDF, XLS and RTF because the img in stored inside the document!.

With HTML, you cannot do that, you have to ref. the img with a src property and include the img as attachment to your mail, so it can be read.

or

Make your images accessible thru http from a web server and point the src=http://myimgserver.com/myimg.jpg

Upvotes: 0

David Kroukamp
David Kroukamp

Reputation: 36423

below has all you need for sending attachments etc helped me greatly when I did my JavaMail client : Send Email's Java and this here: Java Sending Embedded images in JavaMail and here Sending HTML Email with images seem to point more in your direction.

Upvotes: 2

Related Questions