2012-06-21 40 views
2

我想发送一个通过java代码生成的报告。我正在使用碧玉报告来生成各种报告。在我的报告中,我在标题中有图片。这适用于HTML以外的所有报告格式(PDF,XLS,RTF)。它不会在HTML报告中显示图像,因为它无法找到图像。在JAVA中怎么发送用于html的图像作为邮件的附件?

如何使用电子邮件发送图像并使用HTML邮件使用Java邮件?下面

+0

你用什么库发送这些电子邮件? – biziclop

+0

我正在使用javax.mail – DMS

回答

0

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

使用HTML,你不能这样做,你必须参考。带有src属性的img,并将img作为附件添加到您的邮件中,以便读取它。

从Web服务器让您的图像访问直通HTTP和指向SRC = HTTP://myimgserver.com/myimg.jpg

+1

正如@sperumal指出的那样,你可以将图像存储在HTML文档中。并且您可以在HTML电子邮件中使用多个附件。 (我甚至不认为远程图像会出于安全原因在HTML电子邮件中工作。) – biziclop

+0

与base64字符串的好处...! – Cygnusx1

1

,可以使用绝对URL(如http://servername.com/images/xyz.jpg)代替相对URL。 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"> 
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 = "[email protected]"; 
    List<String> mailTos = new ArrayList<String>(); 
    mailTos.add("[email protected]"); 
    List<String> mailCcs = new ArrayList<String>(); 
    mailCcs.add("[email protected]cs.com"); 
    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(); 
    } 
    } 
} 
相关问题