Attachment + Email + HTML + Play Framework - html

I'm using play framework in this project and I'm trying to send an E-mail with a Logo attached but I want to show this logo as part of my HTML code!
My Mailer:
EmailAttachment attachment = new EmailAttachment();
attachment.setDescription("Logo");
attachment.setName("logoMail.jpg");
attachment.setPath(Play.getFile("/public/images/email/logoMail.jpg").getPath());
addAttachment(attachment);
My HTML
The e-mail is sent, my Logo is attached there, but the image is never showed as a background on my DIV.
What am I doing wrong?
Thank you very much!

It depends on the e-mail client you are using to read your test e-mail. Most of them ignore or remove the background-image css property.
Take a look at the following:
http://www.email-standards.org/
http://www.campaignmonitor.com/design-guidelines/

I've been looking into embedding images into emails using MVC templates, and I think at the moment it's not supported.
As far as I can see, in order to use embedded images, the image attachment needs to have a Content-ID header on it. Attaching the image using addAttachment generates an attachment without this header.
The underlying email framework, apache commons email, allows you to embed images using the HtmlEmail.embed method, and there is an example of this in the Play documentation, but only when using Commons Email directly. addAttachment() will add an ordinary attachment, not an embedded one.
The problem is that HtmlEmail.embed returns the content id for the embedded image. The first problem is that there would need to be a mechanism for passing that content id forward into the template, so that you could reference it in the relevant link.
The second problem is that the way the Mailer.send() method is coded, the email itself is not created until after the template is rendered, and the result of attempting to render an html body is used to decide whether to create an HtmlEmail or a SimpleEmail. This method would need to be re-written to decide the type of email before rendering the template, and, if it was html, to create the HtmlEmail and attach the embedded images prior to rendering the template, so that it could pass the content ids to the renderer.
It certainly isn't impossible to make this change, and I might attempt it if I can find the time on my current project.

The solution could be to render HTML content manually and then put it into email. This code worked for me:
public static String test() throws EmailException, MalformedURLException {
HtmlEmail email = new HtmlEmail();
email.setHostName("smtp.server.com");
email.setAuthentication("username", "pwd");
email.setSubject("subject");
email.addTo("to#example.com");
email.setFrom("from#example.com");
URL url = new URL("https://example.com/image.png");
String cid = email.embed(url, "IMG1");
Template templateHtml = TemplateLoader.load("/Mails/test.html");
final Map<String, Object> templateHtmlBinding = new HashMap<String, Object>();
templateHtmlBinding.put("cid", cid);
String body = templateHtml.render(templateHtmlBinding);
email.setHtmlMsg(body);
return email.send();
}

I'm a bit late with my answer, but it is possible and integrates nicely with the MVC-Email tutorial. Assuming your mailer class is also notifiers.Mails, use this as a html template:
%{
String logoSrc = notifiers.Mails.getEmbedddedSrc("public/images/logo.png", "cool logo");
}%
<html>
<head>
</head>
<body>
Look at this cool image! <br>
<img src="${logoSrc}">
<br>
Amazing, no?
</body>
</html>

Related

Rendering a pdf file from an html view to display it on a web page as a image preview

I need to create a pdf preview that should be displayed on a web page as an image. The pdf file is just a simple report build on almost plain HTML. Essentially I had a problem with displaying checkboxes, now I replaced them with pics of checkboxes but the issue remains the same.
Here how I create the pdf report from my HTML view with help of groovy and grails:
def html = htmlRenderService.getReport(info)
ByteArrayOutputStream out = new ByteArrayOutputStream()
HtmlImageGenerator htmlImageGenerator = new HtmlImageGenerator()
htmlImageGenerator.loadHtml(html)
BufferedImage bi = htmlImageGenerator.bufferedImage
ImageIO.write(bi, "PNG", out)
byte[] bytes = out.toByteArray()
String base64bytes = encoder.encodeToString(bytes)
String src = "data:image/png;base64," + base64bytes
out.flush()
def getReport(Info info) {
return groovyPageRenderer.render(view: REPORT_VIEW,
model: [info: info])
}
Then I send the src string to my view and render it as:<img src="${src}" alt=""/>
Then my checkbox pic looks like this: <div style="/*style stuff*/ background-image: url(data:image/png;base64,LINK_TO_THE_IMAGE"></div>
In the end, I received a picture of my pdf report rendered pretty well displaying as an image on my page, BUT without checkboxes. Here is the picture of one part of it:
And here is the same part but from the pdf document which I rendered all the same way, but just downloaded directed from my webapp:
Here is an example where I combined both options(input checkbox and image checkbox) and rendered it as an image:
So what could cause this issue? Thank you in advance.
UPDATE: I came across today to this comment under another issue with HtmlImageGenerator:
HtmlImageGenerator seems to use a JEditorPane for rendering the HTML. Swing HTML support does not extend to the ability to render data images. It might be possible by digging into the HTMLEditorKit and changing the image loading element to support data images, but then you'd need to find a way to get HtmlImageGenerator to use the altered editor pane.
Seems that HtmlImageGenerator doesn't work well with images inside HTML files, but it's still unclear why it doesn't render checkbox inputs as well.
Without seeing the code you end up with after page load, check the chrome dev tools panel to see if the image has actually loaded correctly to the page which will tell you it's at least accessible to use. Then check if the url is output correctly to the div as the background-image. If it looks correct and there aren't related errors in the console, it is likely a css setting.
With background images, your container will need to contain content or else you will need to specify:
width
height
a display setting
background-position, and a
background-size
If you can upload more info, I might be able to be more specific.

Does the Win 10 UWP EmailMessage API support having an HTML body?

I have tried the following code to send an email from an Universal Windows Platform app. It works fine when I use EmailMessageBodyKind::PlainText. However, as indicated in the code below, EmailMessageBodyKind::Html seems to launch the email client with no content. Does anyone know what else needs to be set to get this to work - the documentation is sparse 8 (
using namespace Windows::Storage::Streams;
using namespace Windows::ApplicationModel::Email;
using namespace Windows::Security::Cryptography;
auto bin = CryptographicBuffer::ConvertStringToBinary(
L"<html><body>this <b>is</b> text</body></html>",
BinaryStringEncoding::Utf16LE);
auto memStream = ref new InMemoryRandomAccessStream();
concurrency::create_task(memStream->WriteAsync(bin)).then(
[memStream](unsigned)
{
auto email = ref new EmailMessage();
email->To->Append(ref new EmailRecipient(L"test#gmail.com"));
email->Subject = L"Email Report";
auto randomAccessStreamReference = RandomAccessStreamReference::CreateFromStream(memStream);
email->SetBodyStream(EmailMessageBodyKind::Html, randomAccessStreamReference);
EmailManager::ShowComposeNewEmailAsync(email);
}
);
Well, I got some bad news for you.
It is not possible to do so using EmailManager.ShowComposeNewEmailAsync
Regarding using SetBodyStream with EmailMessageBodyKind.Html, we have this from MSDN forum:
Currently, the EmailMessageBodyKind.Html won't work for create a new
HTML e-mail and there is no other way as a workaround, I've checked
the internal resource, this API is used for populating messages from
App server and save e-mail message into local folder.
The thing is: EmailManager.ShowComposeNewEmailAsync uses mailto to send the message and, as stated in some other question already answered here:
Section 2 of RFC 2368 says that the body field is supposed to be in
text/plain format, so you can't do HTML.
However even if you use plain text it's possible that some modern mail
clients would render the resulting link as a clickable link anyway,
though.
That being said, you're relying on the mail client to render that HTML for you.
I've tested this using Windows 10 Mail Client, Gmail and Outlook (both the later on a web browser), and all of them failed to render a simple HTML <b> tag on the mail body, showing it as plain text instead.
Now, for the alternatives (from that same MSDN forum thread):
Note that if I use the ShareDataContract (DataTransferManager), I am
able to set the HTML in the request and it will appear in the email
body if the user chooses to share via Mail. However I would like to
skip the Share UI and go directly with composing an email with
recipient already populated, HTML body, and image attachments.
One alternative is to persist the HTML body to a file and then include
that file as an additional attachment, however that is not ideal
The DataTransferManager successfully formatted the HTML message. Here's a small sample of how your sample code would look like, adapted from MSDN:
void YourView::ShareHtml()
{
DataTransferManager^ dataTransferManager = DataTransferManager::GetForCurrentView();
auto dataRequestedToken = dataTransferManager->DataRequested +=
ref new TypedEventHandler<DataTransferManager^, DataRequestedEventArgs^>(
this, &YourView::OnShareHtml);
DataTransferManager::ShowShareUI();
}
void YourView::OnShareHtml(DataTransferManager^ sender, DataRequestedEventArgs^ e)
{
DataRequest^ request = e->Request;
request->Data->Properties->Title = "Email Report";
String^ html = L"<html><body>this <b>is</b> text</body></html>";
String^ htmlFormat = HtmlFormatHelper::CreateHtmlFormat(html);
request->Data->SetHtmlFormat(htmlFormat);
}
The limitations of this approach are:
You cannot force the user to select e-mail as the sharing option
You cannot previously specify the mail recipient.

How can i add an image in html email from lotus domino agent?

i want to add a simple image into an email which i want to send from a lotus agent.
I paste below a part of the code:
StringBuilder sb = new StringBuilder();
sb.append("<div><img src=\"http://goo.gl/lziMZN\"></div>");
email.setHTMLPart(sb.toString());
email.send("mail#mail.com");
I also tried to use an image from my image resources in the nsf.
Whatever i tried i get an empty image area (browser-no-image icon) in the email i receive.
I also have checked "Allow restricted operations" in my agent.
I would prefer it if there is a solution to use an image from my resources and not an external link.
Any solutions?
UPDATE: this is the link for the xpHTMLMail class http://openntf.org/XSnippets.nsf/snippet.xsp?id=create-html-mails-in-ssjs-using-mime

Loading Background Image to Custom Html page in Web browser control

I have a scenario where I would need to navigate to my own custom html page, when the any request fails. The issue I am facing is I have a background Image which I need to display with the custom html page.
I have implemented the code as follows:
CustomHtmlDoc = "<html><head></head><body background=\"{0}\"; oncontextmenu='return false;'><br><br></br></br><hr><h4 style='font-family:Footlight MT Light;color:red;font-size:20px;'>" + "ErrorMessage" + "</h4><h4 style='font-family:Footlight MT Light;color:red;font-size:25px;'>Please Verify the Configured URL from Dashboard Configuration</h4> <hr></body></html>";
string CustomHtmlDocument = string.Format(CustomHtmlDoc,AppDomain.CurrentDomain.BaseDirectory + "AdministrationUIBrowser\\AdministrationUIBrowserFactory\\ErrorBackground.png");
WebBrowserControlView.DocumentText = CustomHtmlDocument;
I am able to get the error page as background when I try to run the scenario locally. But at the deployed end, I am just getting blank screen with only content without any background Image. Mine is a WPF application.
The DocumentText implementation in Windows Forms does not implement IMoniker and the loaded document will have a base address of about:blank, thus your page cannot find the background image.
You can use a base element to specify the base location for relative urls, or implement a url moniker. There is a sample on implementing a url moniker at http://www.codeproject.com/KB/miscctrl/csEXWB.aspx. Search LoadHtmlIntoBrowser(string html, string sBaseUrl) on the page.
Maybe you can use a Base64 encoded image. Check this service out. i've tested it and it works like a charm.
Hope it helps.
try 100% sure
(Image current folder)
this.webBrowser1.DocumentText =
#"<b>This is an image:</b> <img src='" +
System.IO.Path.GetDirectoryName(Application.ExecutablePath)
+"/ErrorBackground.png'>";

How to display image in html email message?

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 received. 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