send html page as email in java - 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

Related

Send email with html Java

I'm sending email with HTML code inside and everything fine except some bug with charset I think.
My Java code:
public static void sendMail(String to, String from, String body, String subject) {
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", "smtp.gmail.com");
properties.setProperty("mail.smtp.socketFactory.port", "465");
properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(properties, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(GMAIL_USERNAME, GMAIL_PASSWORD);
}
});
try {
MimeMessage message = new MimeMessage(session); // email message
message.setFrom(new InternetAddress(from)); // setting header fields
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject); // subject line
message.setContent(body, "text/html");
message.setHeader("charset", "UTF-8");
Transport.send(message);
} catch (MessagingException mex) {
mex.printStackTrace();
}
My html content:
String htmlCode =
"<h2>ZDelivery<h2>"+
"<br/><button><a href='"+confirmString+"'>Активировать аккаунт</a></button>";
And email which I got:
What I've missed?
The encoding is transferred by the email header field Content-Type, which is set by the mime type argument of the setContent() method:
message.setContent(body, "text/html; charset=UTF-8");
By not setting the charset in the mime type, java will set it for text/html to ISO-8859-1 (which is the default value defined in RFC-2854).
Your are setting the email header field charset. This is not a officially email header field and thats why it is ignored by the email client.

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)

Sending HTML text message to a phone in java

I currently have a program that sends users an email based on their information in my database. The email is built out in html and sends to the users email as a content type text/html. I want to try and see if I could somehow send this message to their phone using the email format ###########domain.com.
Obviously phones cant receive an HTML message, so I tried this:
-Removed the html and sent pure text, this did work, however for Verizon (the only service provider I tested) the text got cut off and the full message never sent. I only received the first part of the message.
Then I wondered if it was possible to somehow "screenshot" the html message and simply send the picture of the html display to the phone.
Here is my current code to send an email:
public static void email(String content, String address) {
final String username = "email";
final String password = "password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
Address[] a = InternetAddress.parse("myemail");
message.setReplyTo(a);
message.setHeader("From: ", "Movie Alert");
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(address));
if (ShowFinder.showsFound > 1) message.setSubject("Movie Alert: " + ShowFinder.showsFound + " New Shows Found!");
else if (ShowFinder.showsFound == 1) message.setSubject("Movie Alert: " + ShowFinder.showsFound + " New Show Found!");
else message.setSubject("Unsubscribed");
StringBuilder sb = new StringBuilder();
sb.append(content);
message.setContent(sb.toString(), "text/html");
Transport.send(message);
System.out.println("Sent Email");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
So in conclusion I have the following questions:
-Is the reason the text got cut off because I am not sending the email properly, or because of the service provider?
-Is it possible to send a screenshot of the html display based on the html code through a text message?
Thanks!
I found a solution to send an html message to a phone! There is a jar called HTML2Image that will convert your html code into an image: https://code.google.com/p/java-html2image/
To make an image of the html you would do something like this:
HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
imageGenerator.loadHtml("<b>Hello World!</b> Please goto <a title=\"Goto Google\" href=\"http://www.google.com\">Google</a>.");
imageGenerator.saveAsImage("hello-world.png");
Then you could send this new image like so:
Multipart mp = new MimeMultipart();
Message message = new MimeMessage(session);
MimeBodyPart mbp1 = new MimeBodyPart();
MimeBodyPart mbp2 = new MimeBodyPart();
message.setFrom(new InternetAddress("email"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(toEmail));
mbp1.setText(text);
mp.addBodyPart(mbp1);
DataSource source = new FileDataSource(new File("screenshot location/hello-world.png"));
mbp2.setDataHandler(new DataHandler(source));
mbp2.setFileName("Screenshot.png");
mbp2.setHeader("Content-ID", "<image_cid>");
mp.addBodyPart(mbp2);
message.setContent(mp);
Transport.send(message);
I strongly suspect the text is getting cut off because of the service provider. There's probably a limit on the size of a single text message.
If you can't fit all the text you want into a short message, you might want to send a link to a web page containing all the information.

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 to send sms alerts to mobile using java?

Im developing a simple Email Application, I have done sending email using java with following code.`
public class SendMail {
public SendMail() throws MessagingException {
String host = "smtp.gmail.com";
String Password = "mnmnn";
String from = "xyz#gmail.com";
String toAddress = "abc#gmail.com";
String filename = "C:/Users/hp/Desktop/Write.txt";
// Get system properties
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtps.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, toAddress);
message.setSubject("JavaMail Attachment");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Here's the file");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
try {
Transport tr = session.getTransport("smtps");
tr.connect(host, from, Password);
tr.sendMessage(message, message.getAllRecipients());
System.out.println("Mail Sent Successfully");
tr.close();
} catch (SendFailedException sfe) {
System.out.println(sfe);
}
}
}`
I want to develope SMSAlert application using java. I want to get sms alerts to my number whenever i get mail. Is it possible in java. Thanks in advance.
An easy and free way to accomplish this is to send an email to your sms inbox.
Each provider has a different domain, but say for sprint emails sent to [mynumber]#messaging.sprintpcs.com will be texted to me.
There doesn't seem to be much of a delay, we have monitoring processes that send out emails and texts this way on error conditions and they arrive simultaneously.
Of course if your recipients are spread across multiple networks maintaining this sort of system gets trickier, because you've got to look up the email domains.
There have been quite a lot of posts about this already.
My advice is to go through a third party provider such as aspsms.com and then to use their API (web service or wathever).
This one has a .Net API, but with Java, you should be able to use the SOAP webservice.
See this answer
This discussion thread about Kannel and SMS Gateways might be of some help.

Categories