Email receiving as a raw html - java

The email which I am sending through sendgrid SMTPAuthenticator is getting delivered and displayed as raw html. I am using velocity template for message content for email in java.
How should I get proper html format in email instead of raw html?
This is the code:
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.port", 587);
props.put("mail.smtp.auth", "true");
SMTPAuthenticator auth = new SMTPAuthenticator();
Session mailSession = Session.getDefaultInstance(props, auth);
mailSession.setDebug(true);
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
String text = messageContent;
message.setFrom(new InternetAddress(sendFrom));
message.setSubject(subject);
message.addRecipient(Message.RecipientType.TO, new InternetAddress(sendTo));
message.setContent(text, "text/html; charset=utf-8");
transport.connect();
transport.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
transport.close();
I have also added the mime type in vm file inside head element, below is the sample.
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
Note : The raw html email is displayed only few time and not all time.
Thanks in advance.

I believe you should also define your Mime Body parts, and initialize your text variable as a MimeBodyPart() object. Though I would strongly recommend you build a multipart message that sends both a text/plain part as well as a text/html part. It's a common thing ISPs look for in an email, since email clients that cannot render html still exist.
Multipart multipart = new MimeMultipart("alternative");
BodyPart textPart = new MimeBodyPart();
textPart.setContent(
"Everything is awesome",
"text/plain; charset=utf-8");
BodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(
"<p> Everything is awesome! </p>",
"text/html;charset=utf-8");
multipart.addBodyPart(textPart);
multipart.addBodyPart(htmlPart);
message.setContent(multipart);

Related

Why Multipart/mixed java mail content is sent as attachment in outlook?

I am sending multi part email which is having text/plain and text/html but when i am getting mail in my outlook html content is coming as attachment and text/plain is coming in the body. i want both in the body.
pom.xml configuration is this
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.2</version>
</dependency>
and java code is
public static void main(String[] args) throws Exception {
Properties props = new Properties();
props.put("mail.smtp.host", sSMTPServer);
props.put("mail.smtp.port", 25);
Session session = null;
session = Session.getInstance(props, null);
MimeMessage msg = new MimeMessage(session);
Multipart mainMultipart = new MimeMultipart("mixed");
Multipart htmlAndTextMultipart = new MimeMultipart("alternative");
MimeBodyPart BodyPart = new MimeBodyPart();
BodyPart.setText(Header);
htmlAndTextMultipart.addBodyPart(BodyPart);
MimeBodyPart BodyPart1 = new MimeBodyPart();
BodyPart1.setContent(Body, "text/html; charset=utf-8");
htmlAndTextMultipart.addBodyPart(BodyPart1);
for (int i = 0; i < htmlAndTextMultipart.getCount(); i++) {
mainMultipart.addBodyPart(htmlAndTextMultipart.getBodyPart(i));
}
msg.setContent(mainMultipart);
InternetAddress[] from = InternetAddress.parse("appdev#abc.com");
InternetAddress[] toList = InternetAddress.parse(to);
msg.addFrom(from);
msg.addRecipients(Message.RecipientType.TO, toList);
msg.setSubject("Multipart_Testing");
Transport transport = session.getTransport("smtp");
transport.connect(sSMTPServer, 25, null,
null);
transport.sendMessage(msg, toList);
System.out.println("Sent");
transport.close();
}
problem is only with outlook that html content is not coming in the body
mail snippet of gmail
and in outlook all contents are not getting rendered like gmail instead coming as attachment
mail snippet of outlook
You don't get to control how mailers display your message, and different mailers will display the same message differently. Your best bet is to put all your content into a single html part, and stick to pretty basic html.
Oh, and JavaMail 1.4.2 is very old, you should upgrade to the current version if possible.

send html page as email in java

I am trying to send html page as message.
already send html email through message.setContent("<html><body><h1>This is actual message</h1></body></html>","text/html" ); these method .Now iwant to send a html page .
like message.setContent("street.html","text/html" );
how to send these below is my full code
String to = "to#gmail.com";
String from = "from#gmail.com";
Properties properties = System.getProperties();
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("from#gmail.com", "from2013");
}});
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("This is the Subject Line!");
message.setContent("street.html","text/html" );
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
A short one-liner for this one:
StringWriter writer = new StringWriter();
IOUtils.copy(new FileInputStream(new File("home.html")), writer);
message.setContent(writer.toString(), "text/html");
NOTE:: IOUtils is available in the Apache Commons IO library
You need to read the contents of "street.html" into a string to be able to send it with the content type "text/html".
You can try with the apache commons mail api
http://commons.apache.org/proper/commons-email/apidocs/org/apache/commons/mail/HtmlEmail.html
MimeMessage.setText() method sets a default mime type of text/plain.
But i guess you need text/html. This can be done using MimeMessage.setContent().
You can make use of this code on java side.
message.setContent(someHtmlMessage, "text/html; charset=utf-8");
You Need to read the content of local file using one of DataHandler impementation. Need to use overloaded method in MiMeMessage Class API which will accept DataHandler object itself.
MiMeMessage.SetContent(Object, type);
Refer to the API link and google for few samples of usage of method will give the required sloution.
you need to change only
String mess=""// it contains html code
message.setContent(mess,"text/html");
Transport.send(message);
it will work

Issue attaching zip file in javamail

I was trying to attach a zip file using javamail and was getting the below error :
"com.sun.mail.smtp.SMTPSendFailedException: 552-5.7.0 This message was blocked because its content presents a potential
552-5.7.0 security issue. Please visit http://support.google.com/mail/bin/answe
552-5.7.0 r.py?answer=6590 to review our message content and attachment content
552 5.7.0 guidelines. vb7sm60966875pbc.13 - gsmtp"
Attaching a doc or xls has got no issues. I even believe that attaching a zip file is no different from any other file. Please let me know what is the issue here.
I have also provided the code if needed.
public class SendMail {
#Test
public static void sendFileEmail()
{
// Recipient's email ID needs to be mentioned.
String to = "*****#gmail.com";
// Sender's email ID needs to be mentioned
String from = "****#gmail.com";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.socketFactory.port", "465");
properties.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.port", "465");
properties.put("mail.debug", "false");
// Get the default Session object.
Session session = Session.getDefaultInstance(properties,
new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication("*****#gmail.com","****");
}
});
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!");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText("This is message body");
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = "XSLTReports.zip";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart);
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
I guess you have not set MIME type for the multipart attachements that you send. Try to set it and see
The standard MIME type for ZIP files is application/zip.
Also try application/octet-stream if it dosen't work
I believe the issue was some how related to content of the zip file . I changed the zip file and it is working fine
Please make sure that network access is OK, The problem seems to be network access permission
First : try to ping from your machine to mail server if ok, it's visable to you
Second : try to send simple mail (subject/content)
Third : try to attach simple doc (txt file)

Updating status with picture via email. (JavaMail)

I'm writing a standalone application in Processing and I need to publish sketch screenshots on FB page timeline via JavaMail.
So I wrote this:
void sendMail() {
String host="smtp.gmail.com";
Properties props=new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable","true");
Session session = Session.getDefaultInstance(props, new Auth());
try
{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("xxxxx#gmail.com", "xxxxx"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("xxxxxxxxxx#m.facebook.com", false));
message.setSubject("ok");
BodyPart mbp = new MimeBodyPart();
DataSource fds = new FileDataSource(file);
mbp.setDataHandler(new DataHandler(fds));
mbp.setFileName("screen.png");
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp);
message.setContent(mp);
message.setSentDate(new Date());
Transport.send(message);
println("Mail sent!");
}
catch(Exception e)
{
println(e);
}
}
Now, when I write down my gmail e-mail as recipient - method works perfectly (I receive only subject and attached photo), but when I use my FB page e-mail - only subject appears in my timeline, no photo.
I've done the same thing with PHP before and it worked. Maybe I have missed something?
Thank You in advance!:)
Well, I've looked on the content of the original message and noticed this:
Content-Type: application/octet-stream; name=screen.png
So I just added a third line to my code:
MimeBodyPart mbp = new MimeBodyPart();
mbp.attachFile(new File(file));
mbp.setHeader("Content-Type", "image/png");
Then I got:
Content-Type: image/png
and now everything works perfectly!:)
You're creating a multipart message with exactly one part and that one part isn't a text part, it's an image part. While that's perfectly legal according to the MIME spec, it's "unusual", and perhaps Facebook email isn't prepared to handle such a message.
When you did the same thing with PHP, did you create a message with the same structure?
Try NOT creating a multipart message. Instead, just set the image as the content of the message itself.
Also, try creating a multipart message with a first part that's plain text and a second part that's the image.

How Can I put a HTML link Inside an email body?

I have an application that can send mails, implemented in Java. I want to put a HTML link inside de mail, but the link appears as normal letters, not as HTML link...
How can i do to inside the HTML link into a String? I need special characters? thank you so much
Update:
HI evereybody! thanks for oyu answers! Here is my code:
public static boolean sendMail(Properties props, String to, String from,
String password, String subject, String body)
{
try
{
MimeBodyPart mbp = new MimeBodyPart();
mbp.setContent(body, "text/html");
MimeMultipart multipart = new MimeMultipart();
multipart.addBodyPart(mbp);
// Preparamos la sesion
Session session = Session.getDefaultInstance(props);
// Construimos el mensaje
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setContent(multipart);
message.addRecipient(
Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject(subject);
message.setText(body);
// Lo enviamos.
Transport t = session.getTransport("smtp");
t.connect(from, password);
t.sendMessage(message, message.getAllRecipients());
// Cierre.
t.close();
return true;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}
And here the body String:
String link = "ACTIVAR CUENTA";
But in the received message the link appears as the link string, not as HTML hyperlink! I don't understand what happens...
Any solution?
Adding the link is as simple as adding the text inside the string. You should set your email to support html (it depends on the library you are using), and you should not escape your email content before sending it.
Update: since you are using java.mail, you should set the text this way:
message.setText(body, "UTF-8", "html");
html is the mime subtype (this will result in text/html). The default value that is used by the setText(string) method is plain
I'm just going to answer in case this didn't work for someone else.
I tried Bozho's method and for some reason the email wouldn't send when I did the setText on the message as a whole.
I tried
MimeBodyPart mbp = new MimeBodyPart();
mbp.setContent(body, "text/html");
but this came as an attachment in Outlook instead of in the usual text. To fix this for me, and in Outlook, instead of doing the mbp.setContent and message.setText, I just did a single setText on the message body part. ie:
MimeBodyPart mbp = new MimeBodyPart();
mbp.setText(messageBody,"UTF-8", "html");
With my code for the message looking like this:
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
for(String str : to){
message.addRecipient(Message.RecipientType.TO, new InternetAddress(str));
}
message.setSubject(subject);
// Create the message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText(messageBody,"UTF-8","html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Put parts in message
message.setContent(multipart);
// Send the message
Transport.send(message);
Appending "http://" before the URL worked for me.
We can create html link in the email body by using java code.In my case I am developing reset password where I should create link and send to the user through the mail.you will create one string.With in a string you type all the url.If you add the http to the that .it behaves like link with in the mail.
Ex:String mailBody ="http://localhost:8080/Mail/verifytoken?token="+ token ;
you can send some value with url by adding query string.Her token has some encrypted value.
put mailBody in your mail body parameter.
ex": "Hi "+userdata.getFirstname()+
"\n\n You have requested for a new password from the X application. Please use the below Link to log in."+
"\n\n Click on Link: "+mailBody);
The above is the string that is parameter that you have to pass to your mail service.Email service takes parameters like from,to,subject,body.Here I have given body how it should be.you pass the from ,to,subject values according to your cast
you can do right way it is working for me.
public class SendEmail
{
public void getEmail(String to,String from, String userName,String password,Properties props,String subject,String messageBody)
{
MimeBodyPart mimeBodyPart=new MimeBodyPart();
mimeBodyPart.setContent(messageBody,"text/html");
MimeMultipart multipart=new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);
Session session=Session.getInstance(props,new Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(userName,password);
}
});
try{
MimeMessage message=new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setContent(multipart);
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
message.setSubject("Have You got Mail!");
message.setText(messageBody,"UTF-8","html");
Transport.send(message);
}
catch(MessagingException ex){System.out.println(ex)}
public static void main(String arg[]){
SendEmail sendEmail=new SendEmail();
String to = "XXXXXXX#gmail.com";
String from = "XXXXXXXX#gmail.com";
final String username = "XXXXX#gmail.com";
final String password = "XXXX";
String subject="Html Template";
String body = "<i> Congratulations!</i><br>";
body += "<b>Your Email is working!</b><br>";
body += "<font color=red>Thank </font>";
String host = "smtp.gmail.com";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
sendEmail.getEmail(to,from,username,password,props,subject,body);
}
}

Categories