Change String colour JavaMail - java

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

Related

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.

How to get full message body in Gmail?

I want to get full message body. So I try:
Message gmailMessage = service.users().messages().get("me", messageId).setFormat("full").execute();
That to get body, I try:
gmailMessage.getPayload().getBody().getData()
but result always null. How to get full message body?
To get the data from your gmailMessage, you can use gmailMessage.payload.parts[0].body.data. If you want to decode it into readable text, you can do the following:
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;
System.out.println(StringUtils.newStringUtf8(Base64.decodeBase64(gmailMessage.payload.parts[0].body.data)));
I tried this way, since message.getPayload().getBody().getParts() was always null
import com.google.api.client.repackaged.org.apache.commons.codec.binary.Base64;
import com.google.api.client.repackaged.org.apache.commons.codec.binary.StringUtils;
(...)
Message message = service.users().messages().get(user, m.getId()).execute();
MessagePart part = message.getPayload();
System.out.println(StringUtils.newStringUtf8(Base64.decodeBase64(part.getBody().getData())));
And the result is pure HTML String
I found more interesting way how to resolve a full body message (and not only body):
System.out.println(StringUtils.newStringUtf8( Base64.decodeBase64 (message.getRaw())));
here is the solution in c# code gmail API v1 to read the email body content:
var request = _gmailService.Users.Messages.Get("me", mail.Id);
request.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Full;
and to solve the data error
var res = message.Payload.Body.Data.Replace("-", "+").Replace("_", "/");
byte[] bodyBytes = Convert.FromBase64String(res);
string val = Encoding.UTF8.GetString(bodyBytes);
If you have the message (com.google.api.services.gmail.model.Message) you could use the following methods:
public String getContent(Message message) {
StringBuilder stringBuilder = new StringBuilder();
try {
getPlainTextFromMessageParts(message.getPayload().getParts(), stringBuilder);
byte[] bodyBytes = Base64.decodeBase64(stringBuilder.toString());
String text = new String(bodyBytes, StandardCharsets.UTF_8);
return text;
} catch (UnsupportedEncodingException e) {
logger.error("UnsupportedEncoding: " + e.toString());
return message.getSnippet();
}
}
private void getPlainTextFromMessageParts(List<MessagePart> messageParts, StringBuilder stringBuilder) {
for (MessagePart messagePart : messageParts) {
if (messagePart.getMimeType().equals("text/plain")) {
stringBuilder.append(messagePart.getBody().getData());
}
if (messagePart.getParts() != null) {
getPlainTextFromMessageParts(messagePart.getParts(), stringBuilder);
}
}
}
It combines all message parts with the mimeType "text/plain" and returns it as one string.
When we get full message. The message body is inside Parts.
This is an example in which message headers (Date, From, To and Subject) are displayed and Message Body as a plain text is displayed. Parts in Payload returns both type of messages (plain text and formatted text). I was interested in Plain text.
Message msg = service.users().messages().get(user, message.getId()).setFormat("full").execute();
// Displaying Message Header Information
for (MessagePartHeader header : msg.getPayload().getHeaders()) {
if (header.getName().contains("Date") || header.getName().contains("From") || header.getName().contains("To")
|| header.getName().contains("Subject"))
System.out.println(header.getName() + ":" + header.getValue());
}
// Displaying Message Body as a Plain Text
for (MessagePart msgPart : msg.getPayload().getParts()) {
if (msgPart.getMimeType().contains("text/plain"))
System.out.println(new String(Base64.decodeBase64(msgPart.getBody().getData())));
}
Base on the #Tholle comment I've made something like that
Message message = service.users().messages()
.get(user, messageHolder.getId()).execute();
System.out.println(StringUtils.newStringUtf8(Base64.decodeBase64(
message.getPayload().getParts().get(0).getBody().getData())));
There is a method to decode the body:
final String body = new String(message.getPayload().getParts().get(0).getBody().decodeData());
Message message = service.users().messages().get(user, messageId).execute();
//Print email body
List<MessagePart> parts = message.getPayload().getParts();
String data = parts.get(0).getBody().getData();
String body = new String(BaseEncoding.base64Url().decode(data));

Extract Email adresses from .pst file with java-libpst

i have several .pst files and need all the mail-addresses, i sent mails to. The example code of the library allows me to traverse every mail in the file, but i can't find the right getter to extract the mail address of the receiver.
To traverse every mail, i use the code from this site:
https://code.google.com/p/java-libpst/
PSTMessage email = (PSTMessage) folder.getNextChild();
while (email != null) {
printDepth();
System.out.println("Email: " + email.getSubject());
printDepth();
System.out.println("Adress: " + email.getDisplayTo());
email = (PSTMessage) folder.getNextChild();
}
The getDisplayTo() method only displays the receivers names but not their mail addresses.
What getter do i need to use to get the addresses?
Best,
Michael
First method : : available getters
getSenderEmailAddress
getNumberOfRecipients
getRecipient(int)
Second Method : parse the header and collect the email address (a_sHeader is a string)
Session s = Session.getDefaultInstance(new Properties());
InputStream is = new ByteArrayInputStream(a_sHeader.getBytes());
try {
m_message = new MimeMessage(s, is);
m_message.getAllHeaderLines();
for (Enumeration<Header> e = m_message.getAllHeaders(); e.hasMoreElements();) {
Header h = e.nextElement();
// Recipients
if (h.getName().equalsIgnoreCase(getHeaderName(RecipientType.REC_TYPE_TO))) {
m_RecipientsTo = processAddresses(h.getValue());
}
...
}
} catch (MessagingException e1) {
...
}

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

Spring email and new line character

Can someone tell me how to insert newline characters in email content. I use this code snippet to send emails.
public boolean sendMail(final Account player, final Object tl, final String type)
{
MimeMessagePreparator preparator = new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage) throws Exception
{
MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
String msgAdmin = msgFrom;
message.setTo(player.getEmail()); // TODO: changed from msgAdmin to player.getEmail()
message.setFrom(msgFrom);
message.setSubject(type + " invitation");
Map model = new HashMap();
model.put("tl", tl);
model.put("player", player);
model.put("type", type);
String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
"com/test/mail/invite.vm", model);
logger.debug(text);
message.setText(text, true);
}
};
return sendMail(preparator);
}
I tried \r\n characters in the email content. But it doesn't seem to work. HTML markup like BR tag works, but i dont want to add html markups in the email content. Any other solution is possible?
Actually the problem is when you are invoking the message.setText, you are setting the second arguement to true. Which means the message is interpreted as HTML. In order for the emails newlines to show, just set that second argument to false.
Newline characters and velocity templates is a well-documented problem. The best workaround is to stash "\n" as a value of a property that you make available to template. Then reference that property.

Categories

Resources