Wednesday, May 23, 2012

Send Mail with html content

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendEmail
{
   public static void main(String [] args) throws IOException
   {
     //  http://www.tutorialspoint.com/java/java_sending_email.htm

        String host = "smtp.gmail.com";
        final String from = "xxxxx@gmail.com";
        final String pass = "xxxx";
        Properties props = System.getProperties();
        props.put("mail.smtp.starttls.enable", "true"); // added this line
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.password", pass);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");

        String to = "xxxx@xxxx.com";
     // Get the default Session object.
        Session session = Session.getInstance(props,
                  new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(from, pass);
                    }
                  });

      try{
         // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);

         // Set From: header field of the header.
         message.setFrom(new InternetAddress("testwidgets11@gmail.com"));

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

         // Now set the actual message
         message.setText("This is actual message");
         String header = "<HTML><BODY><table border=\"2\">";
         String footer = "</table></BODY></HTML>";

         BufferedReader br = new BufferedReader(
                 new FileReader("c:\\source.html"));
         String line;
         String htmlSource = "";
         while ((line=br.readLine())!=null) {
             htmlSource = htmlSource.concat(line);
//             System.out.println(line);
         }
         System.out.println(htmlSource);
         String table = "<table border=\"1\"><tr><td style=\"background-color:red;\">Failed</td><td>Class</td><td>Test</td><td>Reason</td></tr><tr><td style=\"background-color:yellow;\">Skipped</td><td>Class</td><td>Test</td><td>Reason</td></tr></table>";
         table = htmlSource;
         message.setContent(header+table+footer, "text/html" );
         // Send message
         Transport.send(message);
         System.out.println("Sent message successfully....");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

No comments:

Post a Comment