用java邮件将图像嵌入到html电子邮件中 [英] Embedding images into html email with java mail

查看:162
本文介绍了用java邮件将图像嵌入到html电子邮件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用javamail发送html和图像,但由于某些原因,我没有看到图像作为html的一部分,我只将它们看作附件。我不知道那是为什么。这是我的一个用户收到一封电子邮件时的样子:



我也想提一下HTML的外观:

  private String generateActivationLinkTemplate(){
String htmlText =;
htmlText =< table width = \600 \border = \0 \cellspacing = \0 \cellpadding = \0 \>< tr>< td>< img src = \cid:logoimg\/>< / td>< / tr>< tr>< td height = \220 \> ;< p>感谢加入Site.com< / p>< p> Lorem ipsum dolor sit amet,consectetur adipisicing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.Ut enim ad minim veniam,quis nostrud practitation ullamco laboris nisi ut aliquip ex ea commodo consequat。Duis aute irure dolor in reconhenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur。Excepteur sint occaecat cupidatat non proident,sunt in culpa qui officia deserunt mollit anim id est laborum。< / p> ;< p>用户名:< br />密码:< / p>< p>要确认您的电子邮件,请点击< a href = \#\> here< / a>。 ; / p>< / td>< / tr>< tr>< td hei ght = \50 \align = \center \valign = \middle \bgcolor = \#CCCCCC \> www.site.com | contact@site.com | +38200 123 456< / td> < / table>;}

我是否需要html,body,和一个头标签...?



这是java实现的样子:

  @Stateless(name =ejbs / EmailServiceEJB)
公共类EmailServiceEJB实现IEmailServiceEJB {

@Resource(name =mail / myMailSession)
私人会话mailSession;

public void sendAccountActivationLinkToBuyer(String destinationEmail,
String name){

//电子邮件的目的地
String to = destinationEmail;
String = from =dontreply2thismessage@gmail.com;

try {
Message message = new MimeMessage(mailSession);
// From:是我们的服务
message.setFrom(new InternetAddress(from));
// To:给出
的目标message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject(Uspij esna registracija);
//如何在http://www.rgagnon.com/javadetails/java-0321.html找到
message.setContent(generateActivationLinkTemplate(),text / html);

日期timeStamp = new Date();
message.setSentDate(timeStamp);

//准备一个多部分HTML
Multipart multipart = new MimeMultipart();
//准备HTML
BodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(generateActivationLinkTemplate(),text / html);

//准备图像
BodyPart imgPart = new MimeBodyPart();

String fileName =logoemailtemplate.png;

ClassLoader classLoader = Thread.currentThread()
.getContextClassLoader();
if(classLoader == null){
classLoader = this.getClass()。getClassLoader();
if(classLoader == null){
System.out.println(IT IS NULL AGAIN !!!!);
}
}

DataSource ds = new URLDataSource(classLoader.getResource(fileName));

imgPart.setDataHandler(new DataHandler(ds));
imgPart.setHeader(Content-ID,logoimg);

multipart.addBodyPart(imgPart);
multipart.addBodyPart(htmlPart);

//设置邮件内容!
message.setContent(multipart);

Transport.send(message);

catch(MessagingException e){
抛出新的RuntimeException(e);
}

}

我觉得java部分给我看起来不错,但我只是可疑的HTML标记,我有什么不对吗?我认为img标签不能正常工作,并且图像不会出现在电子邮件中(注意它只显示为附件):

 < img src = \cid:logoimg\/> 


解决方案

您是否检查过内容类型是否正确以及图像内容处置设置为内联?

另外Content-ID需要全球唯一,您不能只说logoimg。试试 logimg-randomnumbers-dontreply2thismessage@gmail.com 。这可能不是你的问题。

I am sending html and images with javamail but for some reason I don't see the images as part of the html, I see them only as an attachment. I don't know why is that. This is how it looks like when one of my users receive an email:

I would like to mention also that is how the html looks like:

private String generateActivationLinkTemplate() {
    String htmlText = "";
htmlText ="<table width=\"600\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">  <tr>    <td><img src=\"cid:logoimg\"/></td>  </tr>  <tr>    <td height=\"220\"> <p>Thanks for Joining Site.com</p>      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p>    <p>Username:<br />      Password: </p>    <p>To confirm your email click <a href=\"#\">here</a>.</p></td>  </tr>  <tr>    <td height=\"50\" align=\"center\" valign=\"middle\" bgcolor=\"#CCCCCC\">www.site.com | contact@site.com | +38200 123 456</td>  </tr></table>";}

Do I need an html,body, and a head tag...?

This is how the java implementation looks like:

@Stateless(name = "ejbs/EmailServiceEJB")
public class EmailServiceEJB implements IEmailServiceEJB {

@Resource(name = "mail/myMailSession")
private Session mailSession;

public void sendAccountActivationLinkToBuyer(String destinationEmail,
        String name) {

    // Destination of the email
    String to = destinationEmail;
    String from = "dontreply2thismessage@gmail.com";

    try {
        Message message = new MimeMessage(mailSession);
        // From: is our service
        message.setFrom(new InternetAddress(from));
        // To: destination given
        message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse(to));
        message.setSubject("Uspijesna registracija");
        // How to found at http://www.rgagnon.com/javadetails/java-0321.html
        message.setContent(generateActivationLinkTemplate(), "text/html");

        Date timeStamp = new Date();
        message.setSentDate(timeStamp);

        // Prepare a multipart HTML
        Multipart multipart = new MimeMultipart();
        // Prepare the HTML
        BodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(generateActivationLinkTemplate(), "text/html");

        // PREPARE THE IMAGE
        BodyPart imgPart = new MimeBodyPart();

        String fileName = "logoemailtemplate.png";

        ClassLoader classLoader = Thread.currentThread()
                .getContextClassLoader();
        if (classLoader == null) {
            classLoader = this.getClass().getClassLoader();
            if (classLoader == null) {
                System.out.println("IT IS NULL AGAIN!!!!");
            }
        }

        DataSource ds = new URLDataSource(classLoader.getResource(fileName));

        imgPart.setDataHandler(new DataHandler(ds));
        imgPart.setHeader("Content-ID", "logoimg");

        multipart.addBodyPart(imgPart);
        multipart.addBodyPart(htmlPart);            

        // Set the message content!
        message.setContent(multipart);

        Transport.send(message);

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }

}

I think the java part to me looks fine, but i am suspicious only is the html markup, i there something wrong with it? I think that the img tag is not working properly and for not reason the image dont appear on the email(Notice it only appears down as an attachment):

<img src=\"cid:logoimg\"/>

解决方案

Have you checked the content-type is correct and the image content-disposition is set to inline?

Also Content-ID needs to be globally unique, you can't just say "logoimg". Try logimg-randomnumbers-dontreply2thismessage@gmail.com. That may not be your problem though.

这篇关于用java邮件将图像嵌入到html电子邮件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆