开发者

How to display image in html email message?

开发者 https://www.devze.com 2023-01-13 08:55 出处:网络
I\'m writing a j2ee application, that generates an html and sends it as email. In my html, a have an image, but it is not displayed when email is recei开发者_JS百科ved. The html code is something like

I'm writing a j2ee application, that generates an html and sends it as email. In my html, a have an image, but it is not displayed when email is recei开发者_JS百科ved. The html code is something like:

<img src="myimage.gif"></img>

where "myimage.gif" is sent as attached file in the email. I tried to change it to

<img src="cid:myimage.gif"></img>

but still no result. Any ideas? It should be without a link to the image.


You should upload your image to you server and reference that as a hard coded url in the src

e.g. upload to myserver.com/images/myimage.gif the in your html

<img src="http://myserver.com/images/myimage.gif" />


Take a look at Commons Email. It's build on top of the Java Mail API but simplifies it.

They have an example for sending html mails with inline images http://commons.apache.org/email/userguide.html

import org.apache.commons.mail.HtmlEmail;
...

// Create the email message
HtmlEmail email = new HtmlEmail();
email.setHostName("mail.myserver.com");
email.addTo("jdoe@somewhere.org", "John Doe");
email.setFrom("me@apache.org", "Me");
email.setSubject("Test email with inline image");

// embed the image and get the content id
URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif");
String cid = email.embed(url, "Apache logo");

// set the html message
email.setHtmlMsg("<html>The apache logo - <img src=\"cid:"+cid+"\"></html>");

// set the alternative message
email.setTextMsg("Your email client does not support HTML messages");

// send the email
email.send();


If the image is small enough, you could use my HTML Table pixel format :)

see my blog for details: HTML Table Pixel Format

This is just plain valid HTML, however it renders as an image.

/end of shameless plug

0

精彩评论

暂无评论...
验证码 换一张
取 消