Embedding images into html email with java mail
Asked Answered
J

2

15

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: enter image description here

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 | [email protected] | +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 = "[email protected]";

    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\"/>
Jauch answered 10/3, 2011 at 14:1 Comment(3)
Can you post the generated MIME code, or at least the mime code with the headers visible but the content trimmed down?Twopiece
Could you please tell me please how to find or generate the MIME code, so i can post it. I am kind of confused.Jauch
The only thing i changed was this imgPart.setHeader("Content-ID", "<logoimg_cid>"); now works perfectly.Jauch
T
9

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 [email protected]. That may not be your problem though.

Twopiece answered 10/3, 2011 at 14:27 Comment(6)
I used both the methods imgPart.setDisposition(BodyPart.INLINE); and also htmlPart.setDisposition(BodyPart.INLINE); but the result is the same. I dont understand what you said about the content id could you explain me what i should do with it?Jauch
You set the content-id to "logoimg". A content-ID is supposed to be a unique identifier which is not duplicated anywhere in the world, and it has to contain an @ sign. Why, I don't know. You need to show us the generated MIME. What MIME does the email producce?Twopiece
Ok i am a little unexperienced with html tag attributes. you mean something like this: <img src=\"cid:logoimg\"/ conten-type=\"logoimg\">? Also i dont understand how to find the MIME that the email produces, where can i find that?Jauch
I found this: multipart/mixed; boundary="----=_Part_16_27478153.1299771549937" then i call the method getContentType() i dont know where to find the code with the @ sign, i dont really understand what do you meanJauch
The only thing i changed was this imgPart.setHeader("Content-ID", "<logoimg_cid>"); now works perfectly.Jauch
Glad you got it working. Basically the url of the image starting with "cid:" is supposed to be the Content-ID header of the image MIME-part, with "cid:" on the front. The "cid:" URL basically means "The image is in this message somewhere, look for something with this content-ID header".Twopiece
M
12

The error is because of <img src=\"cid:logoimg\"/>

There should be: imgPart.setHeader("Content-ID", "<logoimg>");

Not: imgPart.setHeader("Content-ID", "logoimg");

Ie: You need the '<' and '>'

Mesentery answered 18/3, 2013 at 6:27 Comment(1)
Thank you! This helped. I too was trying "logoimg" instead of "<logoimg>"Eatage
T
9

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 [email protected]. That may not be your problem though.

Twopiece answered 10/3, 2011 at 14:27 Comment(6)
I used both the methods imgPart.setDisposition(BodyPart.INLINE); and also htmlPart.setDisposition(BodyPart.INLINE); but the result is the same. I dont understand what you said about the content id could you explain me what i should do with it?Jauch
You set the content-id to "logoimg". A content-ID is supposed to be a unique identifier which is not duplicated anywhere in the world, and it has to contain an @ sign. Why, I don't know. You need to show us the generated MIME. What MIME does the email producce?Twopiece
Ok i am a little unexperienced with html tag attributes. you mean something like this: <img src=\"cid:logoimg\"/ conten-type=\"logoimg\">? Also i dont understand how to find the MIME that the email produces, where can i find that?Jauch
I found this: multipart/mixed; boundary="----=_Part_16_27478153.1299771549937" then i call the method getContentType() i dont know where to find the code with the @ sign, i dont really understand what do you meanJauch
The only thing i changed was this imgPart.setHeader("Content-ID", "<logoimg_cid>"); now works perfectly.Jauch
Glad you got it working. Basically the url of the image starting with "cid:" is supposed to be the Content-ID header of the image MIME-part, with "cid:" on the front. The "cid:" URL basically means "The image is in this message somewhere, look for something with this content-ID header".Twopiece

© 2022 - 2024 — McMap. All rights reserved.