Learn About Java Frameworks, Data Science and Application Development with Examples

Tuesday, 25 July 2017

How to send mail from gmail using java with customized mail body?

No comments :

Firstly, This article shows how to send a mail using java. Later, you will learn how to add a customized email body to the mail.
Step 1: This method uses the Java Mail API to send the mail. There are many protocols used in Java Mail API, Some of them are: SMTP (Simple Mail Transfer Protocol) , IMAP (Internet Message Access Protocol), POP (Post Office Protocol). This method uses SMTP to send the mail. To send the mail from gmail, password authentication is needed.
public void sendMail(ContactFormVO conFormVo) throws MessagingException { // Get the session object Properties props = new Properties(); props.put(“mail.smtp.host”, http://smtp.gmail.com”); props.put(“mail.smtp.socketFactory.port”, 465”); props.put(“mail.smtp.socketFactory.class”, javax.net.ssl.SSLSocketFactory”); props.put(“mail.smtp.auth”, true”); props.put(“mail.smtp.port”, 465”); Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("From Email Id", "Your Gmail Password"); } }); MimeMessage message = new MimeMessage(session; setMessage(message, Normal Body”); // See the set message method below Transport.send(message); // This will send the mail with normal text in the body.) sendMailWithCustomBody(session); // See this method in Step 2. } private void setMessage(MimeMessage message, String body) throws MessagingException { message.setFrom(new InternetAddress(“FROM@gmail.com”)); message.addRecipient(http://Message.RecipientType.TO, new InternetAddress(“to@some.com”)); message.setSubject(“subject”); if (body.contains(“html”)) { message.setContent(body, text/html”); // for html code } else { message.setText(body); // for normal text. } }
Step 2: 
For Customizing body, “Apache velocity” is used. To use velocity you need to download velocity-1.7 jar (go with the latest version) and include in the lib folder. You can get the jar file here — http://velocity.apache.org/downl...
You need to create a velocity template for the body of the email. velocity template will have plain html with Expression Language (EL). eg., ${name}. This name can be passed to the template using VelocityContext. Save the template with.vm extension.
Velocity Template:
<html> <body style="color: #000080;"> <h3>Hello ${name},</h3> <p style="font-weight: bold;font-family: 'Times New Roman', Times, serif;font-size: 18px;"> I am very glad to hear from you! </p> <h4 style="font-size: 16.5px;margin-top: -6px;"> What can you expect from me: </h4> <p style="margin-top: -16px;"> <ul> <li>Responsive Web Design.</li> <li>Enterprise Applications.</li> <li>Hybrid Mobile Application Development.</li> <li>Database administration and automation.</li> <li>Tutoring - <b><i>"If you have knowledge,let others light their candles in it. - Margaret Fuller"</i></b></li> </ul> </p> <p> You can find my resume by <a href="http://h4hari.in/pdfs/Updated%20Resume_Hari%20_Tummala.pdf">clicking here</a>. </p> <p> I am looking forward to work with you &#9786;. For more details you can reply back to this mail. </p> <p style=" margin: 0;"> <b><span style="font-size:10.0pt; color:maroon">Thank you ,</span></b><br> <b><span style="font-size:10.0pt; color:#1F497D">Hari Hara Kumar Tummala</span></b><br> <b><span style="font-size:10.0pt; color:#1F497D">Application Developer</span></b> <br> <b><span style="font-size:10.0pt; color:#4F6228">Cell: +91-996-223-7400 | +91-738-202-7034</span></b><br> <b><span style="font-size:10.0pt; color:#4F6228">Email : hariharakumar88@gmail.com</span></b><br> <b><span style="font-size:10.0pt; color:#1F497D">Website : www.h4hari.in</span></b><br> <!-- Start PWA Bottom Award --> <DIV ><A HREF="http://www.popularwebsiteawards.com?URL=h4hari.in" TARGET = _BLANK><IMG SRC = "http://www.popularwebsiteawards.com/images/PWA_Award.png" BORDER = 0 STYLE = "border: 0px; "></A></DIV> <!-- End PWA Top Right Award --> </p> </body>   </html>
First you need to initialize the velocity engine. Then set attributes in the template using the VelocityContext. Now, get the template and merge it to the StringWriter. use the merged string as the email body.
sendMailWithCustomBody Method:
private void sendMailWithCustomBody(Session session) throws MessagingException { VelocityEngine ve = VelocityEngineInitializer.getVelocityEngine(); /* create a context and add data */ VelocityContext context = new VelocityContext(); context.put(“name”, some name”); /* now render the template into a StringWriter */ Template t = new Template(); t = getTemplate(“emailTemplate.vm”, ve); StringWriter writer = new StringWriter(); t.merge(context, writer); MimeMessage message = new MimeMessage(session); setMessage(message, writer); Transport.send(message); }
public class VelocityEngineInitializer { private static VelocityEngine velocityEngine; public static VelocityEngine getVelocityEngine() { if (velocityEngine == null) init(); return velocityEngine; } private static void init() { velocityEngine = new VelocityEngine(); Properties velocityProperties = new Properties(); velocityProperties.put("resource.loader", "class"); velocityProperties.put("class.resource.loader.description", "Velocity Classpath Resource Loader"); velocityProperties.put("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); velocityEngine.init(velocityProperties); } }
Give a try!
If you have any questions please feel free to leave a comment here.
Thank you for reading this article so far, if you like then please share with your friends and colleagues.
If you have knowledge,let others light their candles in it. — Margaret Fuller

No comments :

Post a Comment

Recent Posts on Spring Boot