Embedded image visible in mailboxes other than Microsoft Outlook - java

I created an email sending job which pics the receivers email id from the excel sheet and an email content from the html file(with embedded image) both placed in a system locally.
But when the mail is sent through the job the image is not visible in MS Outlook but visible in yahoo and gmail as an attachment.
email sending code:
while (it.hasNext())
{
ReadHTMLContent content = new ReadHTMLContent();
MimeMultipart multipart = new MimeMultipart("related");
MimeBodyPart messageBodyPart1 = new MimeBodyPart();
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
to = (String) it.next();
b = to.matches(emailCheck);
if (b!= null && b == true) {
MimeMessage message = new MimeMessage(session);
msgContent = fetchMailContent();
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject("This is the Subject Line!");
messageBodyPart1.setContent(msgContent, "text/html");
multipart.addBodyPart(messageBodyPart1);
String collect = content.getImageSrc();
String imgStrng = collect;
DataSource fds = new FileDataSource(imgStrng);
messageBodyPart2.setDataHandler(new DataHandler(fds));
messageBodyPart2.setHeader("Content-ID", "<image>");
multipart.addBodyPart(messageBodyPart2);
message.setContent(multipart);
Transport.send(message);
System.out.println("Sent message successfully to " + to);
} else {
System.out.println("Invalid Email ID " + to);
}
}
Sample HTML from where i am getting the mail content has an embedded image, stored locally in a system:
<html>
<head><title>Sample test mail job</title></head>
<body bgcolor=white>
<table border="0" cellpadding="10">
<tr>
<td>
<h1>Testing EMail crone job</h1>
</td>
</tr>
</table>
<p>Weather is cold today </p>
<tr>
<td>
<img src="D:\\Email POC\\images\\Koala.jpg">
</td>
</tr>
</body>
</html>
Please let me know how is it possible to make it visible in outlook mail box as well.
Thanks in advance.

Outlook uses Word as an email editor. You can read about supported and unsupported HTML elements, attributes, and cascading style sheets properties in the following articles in MSDN:
Word 2007 HTML and CSS Rendering Capabilities in Outlook 2007 (Part 1 of 2)
Word 2007 HTML and CSS Rendering Capabilities in Outlook 2007 (Part 2 of 2)
img src=" "
You need to add a reference to an image loaded to any web server or add an image as a hidden attachment. So, the result markup should look like the following one:
img src="cid:attachmentName"
Add the attachment using the Attachments.Add method.
Set the PR_ATTACH_CONTENT_ID property using the PropertyAccessor object.
Set the cid value (see #2) for the reference in the message body.
string img = "<br/><p><o:p><img src=\"" + att.FileName
+ "\" width=1 height=1 border=0 /></o:p></p>";
item.HTMLBody = item.HTMLBody.Replace("</body>", img + "</body>");
string PR_ATTACH_CONTENT_ID = "http://schemas.microsoft.com/mapi/proptag/0x3712001E";
string HIDDEN_ATTACHMENT = "http://schemas.microsoft.com/mapi/proptag/0x7FFE000B";
var pa = att.PropertyAccessor;
if (pa != null)
{
pa.SetProperty(PR_ATTACH_CONTENT_ID, att.FileName);
pa.SetProperty(HIDDEN_ATTACHMENT, false);
}

The msgContent string needs to reference the attached image using the Content-Id you've specified, i.e., using:
<img src="cid:image"/>
If msgContent is being created by some other program, you may need to process the html and change the references to the image.

Related

How to create com.microsoft.graph.models.Message with attachment?

I'm trying to send email with inline attachment using MS Graph. I know how to send email without attachment but when I'm trying to send message with attachment I don't know how can I add this attachment to the message.
Here is my code:
// recipients
Recipient recipient = new Recipient();
EmailAddress emailAddress = new EmailAddress();
emailAddress.address = "tom#mail.com";
recipient.emailAddress = emailAddress;
List<Recipient> recipients = List.of(recipient);
// body
ItemBody body = new ItemBody();
body.contentType = BodyType.HTML;
body.content = "<html><body>my image:<br><img src='cid:my_image_CID'></body></html>";
// inline image
Attachment attachment = new Attachment();
attachment.isInline = true;
attachment.contentType = ".png";
attachment.id = "my_image_CID";
//attachment.contentBytes - I DON'T SEE THIS FIELD...
// message
Message message = new Message();
message.subject = "my subject";
message.body = body;
message.toRecipients = recipients;
//message.attachments = ??? - how to create this object?
there are examples in the internet that I can set attachment.contentBytes but I don't see this attribute.
For the message I can set attachments object which is of type
AttachmentCollectionPage
but I don't know how can I create this object.
I'm using the following versions:
Microsoft Graph Java SDK » 5.42.0
Microsoft Graph Java Core SDK » 2.0.14
You need to use FileAttachment which extends Attachment and has property contentBytes.

putting HTML message into java mail api program

I have the below java program which is used to send mails through java mail api but rite now i have to make sure that the body of the mail should be
in HTML format below is the HTML message that should be printed in body can you please advise how can i embed this message in my mail body which should be of an HTML type IN THE MAIL. Please advise folks
<HTML><BODY></table>Hello,<br><br>Please be advised following details<font color=black face="Arial" size=2><br><br><table border=1
cellpadding=3 cellspacing=0><font color=black face="Arial" size=2><font size=3 face="Arial"><b><tr bgcolor=lightblue><TD nowrap>ABC Reference</TD><TD
nowrap>RTS Reference</TD><TD nowrap>RTYU</TD><TD nowrap>Amount</TD><TD nowrap>Amount</TD><TD nowrap> Amount</TD><TD nowrap>Value
Date</TD><TD nowrap>Remarks</TD></tr></b></font><tr><TD nowrap>315</TD><TD nowrap>IRMAR1</TD><TD nowrap>S</TD><TD nowrap>1,35</TD><TD
nowrap>1352</TD><TD nowrap>0</TD><TD nowrap>13-Apr-2015</TD><TD nowrap></TD></tr><tr><TD nowrap>SM/82970</TD><TD nowrap>IRMAR157</TD><TD
nowrap>AUD</TD><TD nowrap>9,787</TD><TD nowrap>9787</TD><TD nowrap>0</TD><TD nowrap>13-Apr-2015</TD><TD nowrap></TD></tr><tr><TD
nowrap>SM/829705/0315</TD><TD nowrap>IRMAR15</TD><TD nowrap>GBP</TD><TD nowrap>16,968</TD><TD nowrap>16968</TD><TD nowrap>0</TD><TD nowrap>10-Apr-
2015</TD><TD nowrap></TD></tr></font></table><br><br>Please note that this is a system generated email.</table><br><br>For any queries
mail to our group email</table><br><br>Thanks & Regards,<br>ERTY,<br>HFFEREJ,<br>14 3rd RETEY,
Rajasthan, 4540058, India</table><br><br>--------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------
</BODY></HTML>
Below is my program to send tha mails in wgich now instead of text i want to send the html message ..
public class abcMailTest {
public static void main(String[] args) {
String mailSmtpHost = "77.77.77.77";
String mailSmtpPort = "4321" ;
String mailTo = "avdg#abc.com";
//String mailCc = "avdg#abc.com ";
String mailFrom = "avdg#abc.com";
String mailSubject = "sgdtetrtrr";
String mailText = "Test Mail for mail body "; //**** HTML message of above should come up ****
sendEmail(mailTo, mailFrom, mailSubject, mailText, mailSmtpHost ,mailSmtpPort );
}
public static void sendEmail(String to, String from, String subject, String text, String smtpHost , String mailSmtpPort) {
try {
Properties properties = new Properties();
properties.put("mail.smtp.host", smtpHost);
properties.put("mailSmtpPort", mailSmtpPort);
//obtaining the session
Session emailSession = Session.getDefaultInstance(properties);
emailSession.setDebug(true);
//creating the message
Message emailMessage = new MimeMessage(emailSession);
emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
Address[] cc = new Address[] {
new InternetAddress("avdg#abc.com"),
new InternetAddress("AER#gmail.com")};
emailMessage.addRecipients(Message.RecipientType.CC, cc);
emailMessage.setFrom(new InternetAddress(from));
emailMessage.setSubject(subject);
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(text, "text/html");
messageBodyPart.setText(text);
// Create a multipart message
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
MimeBodyPart attachPart = new MimeBodyPart();
String filename = "c:\\abc.pdf";
DataSource source = new FileDataSource(filename);
attachPart.setDataHandler(new DataHandler(source));
attachPart.setFileName(filename);
multipart.addBodyPart(attachPart);
// Send the complete message parts
emailMessage.setContent(multipart);
emailSession.setDebug(true);
Transport.send(emailMessage);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
Try modifying following sample code. The below is my sample code, you can do this for your HTML format replacing with your message string.
// Create body of email
String msg = "<![CDATA[<html><body><div style='text-align:center;'>"
+ "<h2>Analysis Report</h2>"
+ "<div>The Analysis request for Batch ID:"
+ "<span style='background-color: rgb(206, 249, 216);'>{GROUP NAME}</span>"
+ " submitted on<span style='background-color: rgb(206, 249, 216);'>{SUBMISSION_TIMESTAMP}</span> "
+ "has been processed.</div><div style='margin-top: 10px;'>"
+ "The result was: <br><div style='background-color: rgb(255, 213, 157); "
+ "margin-top: 10px; margin-bottom: 10px;'>{MESSAGE TEXT}</div></div>"
+ "<div>Please log on to the system to view detailed information.</div>"
+ "</div></body></html>]]>";
msg = msg.replace("{GROUP NAME}", groupName);
msg = msg.replace("{SUBMISSION_TIMESTAMP}", submissionTimestamp);
msg = msg.replace("{MESSAGE TEXT}", messageText);
message.setText(msg, "ISO-8859-1");
message.setHeader("content-Type", "text/html;charset=\"ISO-8859-1\"");
EDIT:
My Email Template:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<template id="analysisEmailBodyTemplate">
<analysisEmailBody>
<![CDATA[
<html>
<body>
<div style="text-align:center;">
<h2>Analysis Report</h2>
<div>
The Analysis request for Batch ID:
<span style="background-color: rgb(206, 249, 216);">{GROUP NAME}</span> submitted on
<span style="background-color: rgb(206, 249, 216);">{SUBMISSION_TIMESTAMP}</span> has been processed.
</div>
<div style="margin-top: 10px;">The result was: <br>
<div style="background-color: rgb(255, 213, 157); margin-top: 10px; margin-bottom: 10px;">{MESSAGE TEXT}</div>
</div>
<div>Please log on to the system to view detailed information.</div>
</div>
</body>
</html>
]]>
</analysisEmailBody>
</template>
<template id="analysisEmailSubjectTemplate">
<analysisEmailSubject>
Analysis System results for Batch ID: {GROUP NAME}
</analysisEmailSubject>
</template>
</root>
To Parse XML: Follow Read XML file in Java – (DOM Parser) tutorial to read the value of node whichever you want. Then set the message read from XML file to msg variable.
I hope this will help you.
You're calling messageBodyPart.setContent followed by MessageBodyPart.setText. The second call overwrites what the first call did, and switches it back to plain text.
You need to learn how to read the API documentation for JavaMail. It's a lot faster than posting messages here. Start with the MimeBodyPart.setText method. Replace your two method calls with:
messageBodyPart.setText(text, null, "html");
Read through all the methods for MimeBodyPart. You'll find others that are useful as well.

Change String colour JavaMail

I am using JavaMail library, I would like to change the body of the emails, sentences in different color? How can I do it? My application is in (Swing/JFrame)
An example of sending email as HTML: http://www.tutorialspoint.com/java/java_sending_email.htm
What Baadshah is suggesting is adding all of your color formatting inside the Content string using html tags.
message.setContent("<h1>This is actual message</h1>",
"text/html" );
You can programatically construct the string that contains the body message.
String line1 = "This is the first line in the body. We want it to be blue."
addColor(line1, Color.BLUE);
Then create a method for handling the colorizing html:
public static String addColor(String msg, Color color) {
String hexColor = String.format("#%06X", (0xFFFFFF & color.getRGB()));
String colorMsg = "<FONT COLOR=\"#" + hexColor + "\">" + msg + "</FONT>";
return colorMsg;
}
You can examine different ways of colorizing in HTML here: http://www.htmlgoodies.com/tutorials/colors/article.php/3479011/How-To-Change-Text-Color-Using-HTML-and-CSS.htm. This includes old ways of doing it, like using FONT (as my example above) or modern ways of doing it using CSS.
Edit: The toHexString returns an 8 Character hex code (alpha + red + blue + green) while HTML only wants the RGB without alpha. I used the solution from this link, and setup a SSCCE:
import java.awt.Color;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class EmailTestHTML
{
public static void main(String [] args)
{
// Recipient's email ID needs to be mentioned.
String to = "targetemail#somehost.com";
// Sender's email ID needs to be mentioned
String from = "youremail#somehost.com";
// Assuming you are sending email from localhost
String host = "putYourSMTPHostHere";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
// String with body Text
String bodyText = addColor("This line is red.", Color.RED);
bodyText += "<br>" + addColor("This line is blue.", Color.BLUE);
bodyText += "<br>" + addColor("This line is black.", Color.BLACK);
System.out.println(bodyText);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Send the actual HTML message, as big as you like
message.setContent(bodyText,
"text/html" );
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
public static String addColor(String msg, Color color) {
String hexColor = String.format("#%06X", (0xFFFFFF & color.getRGB()));
String colorMsg = "<FONT COLOR=\"#" + hexColor + "\">" + msg + "</FONT>";
return colorMsg;
}
}
Note:
In my environment I had to set this argument in the Run Configuration:
-Djava.net.preferIPv4Stack=true
More on that here.
Its just css.
Nothing to do with JAVA.The browser detects your HTML content which you are sending in email.
For example
<div style="font-size:14px">Dear user</div>
You have to send the mail in HTML format to be able to change text color.
See the JavaMail FAQ.
For me this worked flawlessly, Worth a shot :
String htmlText2 = "<font color=red>Jon Targaryen</font>\n";
or if you want to use hex color :
String htmlText2 = "<font color=#93cff2>Jon Targaryen</font>\n";
You can add more attributes like Headings or Bold :
String htmlText2 = "<H1><font color=red>Jon Targaryen</font></H1>\n";
String htmlText2 = "<b><H1><font color=red>Jon Targaryen</font></H1></b>\n";

setting HTML text in MultiPartEmail

I have java code for sending email with attachment as below.
String myEmailId = "xx#yahoo.co.in";
String myPassword = "#xx";
String senderId = "yy#gmail.com";
try {
MultiPartEmail email = new MultiPartEmail();
email.setSmtpPort(587);
email.setAuthenticator(new DefaultAuthenticator(myEmailId, myPassword));
email.setDebug(true);
email.setHostName("smtp.mail.yahoo.com");
email.addTo(senderId);
email.setFrom(myEmailId);
email.setSubject("The picture");
email.setMsg("<font face='verdana' size='3'>Here is the picture you wanted "
+ "<table>"
+ "<tr><th>id</th><th>Name</th></tr>"
+ "<tr><th>1</th><th>Name 1</th></tr>"
+ "<tr><th>2</th><th>Name 2</th></tr>"
+ "<tr><th>3</th><th>Name 3</th></tr>"
+ "<tr><th>4</th><th>Name 4</th></tr>"
+ "</table>"
+ "</font>");
// add the attachment
EmailAttachment attachment = new EmailAttachment();
attachment.setPath("/Users/alkandari/Desktop/SMART/Fahim/test_small.pdf");
attachment.setDisposition(EmailAttachment.ATTACHMENT);
email.attach(attachment);
attachment = new EmailAttachment();
attachment.setPath("/Users/alkandari/Desktop/SMART/Fahim/test.pdf");
attachment.setDisposition(EmailAttachment.ATTACHMENT);
email.attach(attachment);
// send the email
email.send();
System.out.println("Mail sent!");
} catch (Exception e) {
System.out.println("Exception :: " + e);
}
All is working fine EXCEPT, the HTML code is displaying as it is.
In Email what I get is
<font face='verdana' size='3'>Here is the picture you wanted <table><tr><th>id</th><th>Name</th></tr><tr><th>1</th><th>Name 1</th></tr><tr><th>2</th><th>Name 2</th></tr><tr><th>3</th><th>Name 3</th></tr><tr><th>4</th><th>Name 4</th></tr></table></font>
Is there any parameter, email that I will receive will have proper HTML formatted data.
Note :
Actually I was using Email email = new SimpleEmail(); and doing above stuff where HTML part is working perfectly. However when I had to switch to attachment, I had to use MultiPartEmail email = new MultiPartEmail();.
I want to provide my answer here such that future me (and others) can see the complete code. For whatever reason, probably just me, I found these answers incomplete, or that they did not work for me. Like OP, I was trying to send an HTML based email with a PDF attachment. Here is what I ended up with using commons-email 1.4. Any comments will be appreciated.
Imports:
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.MultiPartEmail;
import org.apache.commons.mail.EmailAttachment;
Build your email object (obviously the actual details here should be yours)
MultiPartEmail email = new MultiPartEmail();
email.setHostName("smtp.yourhosthere.com");
email.setSmtpPort(25);
// authentication not always needed depending on your environment
email.setAuthenticator(new DefaultAuthenticator("username", "password"));
email.setTo("to#yourhosthere.com");
email.setFrom("from#yourhosthere.com");
Now your message details. Note that my HTML includes the HTML and BODY tags.
email.setSubject("Your subject here");
email.addPart("<div>Your html here</div>", "text/html; charset=UTF-8");
Now the attachment
EmailAttachment attachment = new EmailAttachment();
attachment.setPath(filepath);
attachment.setDisposition(EmailAttachment.ATTACHMENT);
email.attach(attachment);
Now send the email
email.send();
I got answer.
Just changed MultiPartEmail email = new MultiPartEmail(); to MultiPartEmail email = new HtmlEmail();
You can't use email.setMsg()
But set message body as:
email.addPart( "<h1>MSG BODY</h1> <u>your</u> name", "text/html; charset=UTF-8" );

how to send url in email without encoding

I am using Amazon Simple Email Service java API to send mail to receivers.
I am sending URL in mail body inside tag.
My use case demands the user to double click on the URL received to prompt some action. (like confirmation mail)
Problem is the url gets encoded while receiving. On double clicking it gives page not found (404) error.
Original URL : http://something.com/confirm/email=abc#hotmail.com&regKey=somekey&confirm=true
When i double click on this URL on mail, the link is opened in address bar as :
http://something.com/confirm/email=abc%40hotmail.com%26regKey=somekey%26confirm=true
I am using AmazonSimpleEmailServiceClient. Code is below :
SendEmailRequest request = new SendEmailRequest().withSource(sourceAddress);
String confirmationURL="http://something.com/confirm/email=abc#hotmail.com&regKey=somekey&confirm=true";
List<String> toAddresses = new ArrayList<String>();
toAddresses.add(toEmail);
Destination dest = new Destination().withToAddresses(toAddresses);
request.setDestination(dest);
Content subjContent = new Content().withData("Confirmation Request");
Message msg = new Message().withSubject(subjContent);
// Include a body in both text and HTML formats
Content textContent = new Content().withData("Dear please go to the following URL:"+
confirmationURL+"\n\n");
Content htmlContent = new Content().withData("<p>Dear please go to the following URL:</p>"+
"<p>"+confirmationURL+"</p>");
Body body = new Body().withHtml(htmlContent).withText(textContent);
msg.setBody(body);
request.setMessage(msg)
UPDATE
Just found, this problem is occurring only when recipient email is in hotmail.com. Why microsoft always have to do something differently ? Somebody help !
Use the class java.net.URLEncoder:
String confirmationURL = URLEncoder.encode( "http://something.com/confirm/email=abc#hotmail.com&regKey=somekey& confirm=true", "UTF-8");

Categories

Resources