我们如何在JAVA中发送html中用作电子邮件附件的图像?

时间:2012-06-21 15:07:41

标签: java javamail ireport email-attachments

我正在尝试发送通过java代码生成的报告。我正在使用jasper报告生成各种报告。在我的报告中,我在标题中有图像。这适用于除HTML之外的所有报告格式(PDF,XLS,RTF)。它不会在HTML报告中显示图像,因为它无法找到图像。

如何使用电子邮件发送图像并使用Java Mail使用HTML报告?

4 个答案:

答案 0 :(得分:2)

下面有你发送附件等所需的一切,当我使用我的JavaMail客户端时,我有很大的帮助:Send Email's Java这里:Java Sending Embedded images in JavaMailSending HTML Email with images似乎指向了更多的方向

答案 1 :(得分:1)

您可以使用绝对网址(例如http://servername.com/images/xyz.jpg)而不是相对网址。可以将JasperReport配置为使用绝对URL。

或者

我不知道这是否适用于嵌入式电子邮件。但您可以尝试使用内联图片,您必须将图片转换为base64字符串。如果图像太大并且在图像更改时难以维护,这将增加HTML的大小。

<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">

答案 2 :(得分:0)

它适用于PDF,XLS和RTF,因为img存储在文档中!。

使用HTML,你不能这样做,你必须参考。带有src属性的img,并将img作为邮件的附件包含在内,因此可以阅读。

通过来自Web服务器的http访问您的图像并指向src = http://myimgserver.com/myimg.jpg

答案 3 :(得分:0)

使用带有嵌入式图像和附件的JavaMail发送html电子邮件。 (我的上一篇文章被删除了,因为它是一个链接(https://github.com/QuickrWorld/email-sender.git)。我认为这一点是有效的 - 如果git存储库被删除或修改得太多以至于它不再是一个有效的答案呢?)。所以我在下面的响应中直接添加了代码。虽然,我仍然想知道为什么我的答案被挑出来删除。这篇文章中的其他答案也只是链接。或者我错过了什么?)

// 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 = "from@mailfrom.com";
    List<String> mailTos = new ArrayList<String>();
    mailTos.add("mailto@maito.com");
    List<String> mailCcs = new ArrayList<String>();
    mailCcs.add("mailcccs@mailccs.com");
    List<String> mailBccs = new ArrayList<String>();
    mailBccs.add("mailbccs.mailbccs@mailbccs.com");
    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 = "x@y.com";
    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();
    }
  }
}