putting HTML message into java mail api program - java

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.

Related

p7s file and javamail

I use this code to read an email String in S/Mime format in a certificated email. This is a snippet
InputStream inputStreamObj = new ByteArrayInputStream(message.getBytes());
MimeMessage mimeMessageObj = new MimeMessage(session, inputStreamObj);
Object content = mimeMessageObj.getContent();
if (content instanceof Multipart) {
Multipart multiPart = (Multipart)content;
for (int i = 0; i < multiPart.getCount(); i++) {
BodyPart part = (MimeBodyPart) multiPart.getBodyPart(i);
if (part.getFileName() != null) {
System.out.println("Filename:"+part.getFileName());
} else if (part.getContent() instanceof Multipart) {
System.out.println("Multipart");
//here there is a recursive call to this method
} else if (part.getContent() instanceof String) {
System.out.println("Message text: "+part.getContent());
} else {
System.out.println("NOT RECOGNIZED TYPE");
}
}
}
In this manner I see:
Message text: <message in html form>
Message text: <message in txt form>
File: daticert.xml
File: postacert.eml
But here "smime.p7s" file is missing
How can I find this? In the String message (message) I see it:
Content-Type: application/x-pkcs7-signature; name="smime.p7s"
Content-Disposition: attachment; filename="smime.p7s"
Where is the file???
Maybe I cannot use MimeMessage and I must use javax.mail.Message? And how can I convert the text in Message?
Solved!
The message-text received contains all (headers + bodypart). When managed, it "loose" headers parts. Adding these in the first message-text I now see all the attachments, even p7s file.
This file, infact, is nested to the main email using a code binding (printing the txt you can see it), but this link suffer of missing headers. In this manner, without headers, noone can address the p7s file.
The solution is: add headers in the form "name: value\n" at the beginning of the txt-message.

Create email (outlook format) on web-service side (Java) and send to front end and download

I want to write a service through which I can create a email message with (to, cc, bcc, subject, body) specified. Then I need to return this email message to front end and download it in ".oft" format, in such a way that when I click on this downloaded file; file should open with all the fields (to, cc, bcc, subject, body) populated.
I am using Java as backend technology and angular5 as front-end.
I have tried using javax.mail utility to create the email message and return it as byte array. Something like:
Properties prop = System.getProperties();
Session session = Session.getDefaultInstance(prop, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("emailAddr#domain.com"));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress("emailAddr#domain.com"));
msg.setSentDate(new Date());
msg.setSubject("subject");
msg.setText("text of msg");
//return it from service API as
response.getOutputStream().write(msg.toString().getBytes());
On front end (component.ts file) I am retrieving the response as :
//function gets called on button click
createEmailTemplate():void{
this.httpService.getEmail('serviceUrl')
.subscribe(
email => {
let filename = "SampleMailFile.oft";
let linkElement = document.createElement('a');
let blob = new Blob([email], { type: "message/rfc822"});
let url = window.URL.createObjectURL(blob);
linkElement.setAttribute('href', url);
linkElement.setAttribute("download", filename);
let clickEvent = new MouseEvent("click", {
"view": window,
"bubbles": true,
"cancelable": false
});
linkElement.dispatchEvent(clickEvent);
}
);
}
A MSG file is supposed to have the same format as an OFT file. If that’s true then you should be able to use jotlmsg to generate the file. You shouldn’t need to use JavaMail at all for this, since it’s intended to actually send the mail.
NOTE: I’ve not used this library before, so I can’t speak to whether this will truly work.

Embedded image visible in mailboxes other than Microsoft Outlook

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.

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" );

Categories

Resources