Showing posts with label JAVA Mail. Show all posts
Showing posts with label JAVA Mail. Show all posts

Monday 17 November 2014

Send Mail with multiple TO address and with Rich HTML Text

//Send Mail with multiple TO address and with Rich HTML Text

                    String from = abc@abcc.com
                  logger.debug("From Address :" +from);
                 
                  String[] to = "abcd@gmail.com,bcda@yahoo.com, xyzaa@gmail.com,vbgjg@hotmail.com";
                  String[] temp_to;
                  String delimeter = ",";
                  temp_to = to.split(delimeter);
                  for(int i =0; i < temp_to.length ; i++){
                      System.out.println(temp_to[i]);
                      System.out.println("");
                      }
                  logger.debug("To Address :"+to);
                  String host = "localhost";
                  logger.debug("SMTP Server IP Address :"+host);

                 
                  try{
                  //Session
                  Properties properties = System.getProperties(); 
                  properties.setProperty("mail.smtp.host", host); 
                  Session session = Session.getDefaultInstance(properties);
                              
                  //logger.info("Session ="+session);
                  logger.debug("Session object is created :"+session);
                 
                 
                  //Mail Part
                  MimeMessage message = new MimeMessage(session);
                  Multipart multipart = new MimeMultipart();
                  message.setFrom(new InternetAddress(from));
                  InternetAddress[] recipientAddress = new InternetAddress[temp_to.length];
                  int counter = 0;
                  for (String recipient : temp_to) {
                      recipientAddress[counter] = new InternetAddress(recipient.trim());
                      counter++;
                  }
                 // message.setRecipients(message.RecipientType.TO, recipientAddress);
                  message.setRecipients(javax.mail.Message.RecipientType.TO, recipientAddress);
                  message.setSubject("Document Uploaded:Need Approval");
                  logger.debug("Subject is created");
                 
                  BodyPart messageBodyPart = new MimeBodyPart();
         
                  String body = "<i>Dear Sir/Madam,</i><br>";
                  body += "<br><br><b>**********************ABCD**********************</b><br>";
                  body += "<br><font color=black>Sample Mail from p8programmer.</font><br>";
                  body += "<br><br><b><font color=red>Details:</font></b><br>";
                  body += "<br><table border=1><tbody>";
                  body += "<tr><td width=150 valign=top class=emailcontent style=padding:8px;>From</td><td width=200 valign=top class=emailcontent style=padding:8px;><b>"+from+"</b></td></tr>";
                  body += "<tr><td width=150 valign=top class=emailcontent style=padding:8px;>To</td><td width=200 valign=top class=emailcontent style=padding:8px;><b>"+to+"</b></td></tr>";
                  body += "</tbody></table><br><br><br>";
                  body += "<tr><td bgcolor=black height=5></td></tr>";
                  body += "<tr> <td style=padding:10px; class=emailcontent><br>Thanks &amp;Regards <br/>";
                  body += "<strong><i><font color=blue>p8programmer</font></i></strong></td>";
                  body += "<br><br></tr>";
                  body += "<td style=padding:10px; class=emailcontent>***************************************************************************************************************<br>";
                
               
                 
                  messageBodyPart.setContent(body,"text/html");
                  multipart.addBodyPart(messageBodyPart);
                 
                                  
                  logger.debug("...Body Part Created...");
                  message.setContent(multipart);
                  Transport.send(message);
                 
                  //logger.info("message sent successfully....");
                  logger.info("......Message sent successfully.....");
                  }
                  catch (MessagingException mex) {
                      mex.printStackTrace();
                      logger.error("Exception occured while sending mail :"+mex);
                  }

Send EMail reminder from Excel spreadsheet (Read TO Address from Excel sheet)

Description:  
Sending automatic mail from java code based on Date of births

1. Read Data from Excel sheet

2. Compare Date of Birth and Current Date
3. Fetch Name and mail Address  based on Date of birth and Current date (If equal)
4. Send mail to particular person (Send Mail with random images) with help of above deatils


Note :

Excel sheet content : (Date Format US English (mm/dd) )




 //Read Excel sheet compare Date of Birth and Current Date

package sample;

import java.io.File;
import java.io.IOException;

import jxl.Cell;
import jxl.CellType;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

import java.util.Calendar;
import java.util.GregorianCalendar;

import java.util.*;


public class ReadExcel {

 
  private String inputFile;
  public ArrayList<String> items = new ArrayList();

 
  public void setInputFile(String inputFile) {
    this.inputFile = inputFile;
  }

  public void read() throws IOException  {
    File inputWorkbook = new File(inputFile);
    Workbook w;
    try {
      w = Workbook.getWorkbook(inputWorkbook);
      // Get the first sheet
      Sheet sheet = w.getSheet(0);
      // Loop over first 10 column and lines

      for (int j = 0; j < sheet.getColumns(); j++) {
        for (int i = 0; i < sheet.getRows(); i++) {
          Cell cell = sheet.getCell(j, i);
          CellType type = cell.getType();
          
               
          if (type == CellType.DATE) {
              if( GetDate().equals(cell.getContents()))
                 
                      {
                 
                  System.out.println("Date Matched");
                 
                  System.out.println("Current Date "+GetDate());
                 
                  Cell a2 = sheet.getCell(j-1,i);
                //  name = a2.getContents();
                  items.add(a2.getContents());
                 
                 
                  Cell a1 = sheet.getCell(j+1,i);
                 // email = a1.getContents();
                  items.add(a1.getContents());
                    
                  System.out.println("Name  :" + a2);
                  System.out.println("Email  :"+ a1);
                     System.out.println("I got a Date " + cell.getContents());                
                 
            }else
            {
                System.out.println("Date not matched with current date");
            }
          }
         
           

        }
      }
    } catch (BiffException e) {
      e.printStackTrace();
    }
  }

 String GetDate(){
     int day, month;
     String CurrentDate;
     GregorianCalendar date = new GregorianCalendar();

     day = date.get(Calendar.DAY_OF_MONTH);
     month = date.get(Calendar.MONTH);
     CurrentDate = (month+1)+"/"+day;
 
     System.out.println("Current date is  " +CurrentDate);

    return CurrentDate;
     
  }
  public static void main(String[] args) throws IOException {
    ReadExcel test = new ReadExcel();
   // test.setInputFile("C:/Users/IBM_ADMIN/Documents/sample.xls");
    //test.GetDate();
    test.read();
    Iterator itr= test.items.iterator();
    while(itr.hasNext())
    {
        System.out.println("Name :" + itr.next() + "\n Email :" + itr.next());
 
    }
   
  }

}



//Sending Mail with Random Images 

package sample;

import java.io.IOException;
import java.util.*; 

import javax.mail.*; 
import javax.mail.internet.*; 
import javax.activation.*; 

import sample.ReadExcel;
 
public class SendEmail extends ReadExcel  

 public static void main(String [] args) throws IOException {
   
     
   
      String from = "abcde@gmail.com";//change accordingly
   
      String host = "127.0.0.1";//or IP address 
     
     
 
     //Get the session object 
      Properties properties = System.getProperties(); 
      properties.setProperty("mail.smtp.host", host); 
      Session session = Session.getDefaultInstance(properties); 
   
      String charsetNum = "123456789";
      StringBuffer image=new StringBuffer("images");
      ReadExcel test = new ReadExcel();
      test.setInputFile("C:/Users/IBM_ADMIN/Documents/sample.xls");
      test.GetDate();
      test.read();
      for(Iterator itr = test.items.iterator(); itr.hasNext();)
      {
          String name = (String)itr.next();
          String mail = (String)itr.next();
          String cc= (String) itr.next();
          System.out.println((new StringBuilder("Name :")).append(name).append("\n Email :").append(mail).append("\n CC :").append(cc).toString());
          try
          {
              java.util.Random rand = new java.util.Random(System.currentTimeMillis());

              for (int n = 1; n <2; n++) {
                  int pos = rand.nextInt(charsetNum.length());
                  image.append(charsetNum.charAt(pos));
              }
             
              String randomImageName = image.toString();
              System.out.println("randomImageName- "+randomImageName);
             
             
           
              MimeMessage message = new MimeMessage(session);
              message.setFrom(new InternetAddress(from));
              message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(mail));
              message.addRecipient(javax.mail.Message.RecipientType.CC, new InternetAddress(cc));
              message.setSubject("Wishing you a Very Happy Birthday -"+name);
             
              MimeMultipart multipart = new MimeMultipart();
              BodyPart messageBodyPart = new MimeBodyPart();
                                        
              String htmlText = "<H2 style=\"font-family:Calibri;color:red;\">Wishing you a Very Happy Birthday.. !!**.."+name+"..**!!</H2>";
              messageBodyPart.setContent(htmlText, "text/html");               
             
              multipart.addBodyPart(messageBodyPart);
            
             
              messageBodyPart = new MimeBodyPart();
              String cntent1 = "<H3 style=\"font-family:Calibri;color:green;\"><br><br>Wishes you for Healthy Long Life...</H3>";
              messageBodyPart.setContent(cntent1,"text/html");
              multipart.addBodyPart(messageBodyPart);
             
              messageBodyPart = new MimeBodyPart();
              String cntent2 = "<H4 style=\"font-family:Calibri;color:red;\"><br><br>From ABC.</H4><br><img src=\"cid:image\"><br><br>" +
                      "PLEASE DO NOT REPLY TO ALL!!!!<br><br><b>AA PMO TEAM</b>";
              messageBodyPart.setContent(cntent2, "text/html");               
              multipart.addBodyPart(messageBodyPart);               
             
              messageBodyPart = new MimeBodyPart();
              javax.activation.DataSource fds1 = new FileDataSource("C:/Users/IBM_ADMIN/Pictures/"+randomImageName+".jpg");
              messageBodyPart.setDataHandler(new DataHandler(fds1));
              messageBodyPart.addHeader("Content-ID", "<image>");
              multipart.addBodyPart(messageBodyPart);
             
             
              message.setContent(multipart);
              Transport.send(message);
              System.out.println("message sent successfully....");
          }   

        catch (MessagingException mex) {mex.printStackTrace();} 
         
   
      }
     
 
     //compose the message 
     
   }

 












Send sample Mail ( Java Code )

//Sending Mail

import java.util.*; 
import javax.mail.*; 
import javax.mail.internet.*; 
 
public class SendEmail 

 public static void main(String [] args){ 
      String to = "abcd@gmail.com";//change accordingly 
      String from = "sample@gmail.com";//change accordingly 
      String host = "localhost";//or IP address 
 
     //Get the session object 
      Properties properties = System.getProperties(); 
      properties.setProperty("mail.smtp.host", host); 
      Session session = Session.getDefaultInstance(properties); 
 
     //compose the message 
      try{ 
         MimeMessage message = new MimeMessage(session); 
         message.setFrom(new InternetAddress(from)); 
         message.addRecipient(Message.RecipientType.TO,new InternetAddress(to)); 
         message.setSubject("Ping"); 
         message.setText("Hello, Happy Birthday to u  "); 
 
         // Send message 
         Transport.send(message); 
         System.out.println("message sent successfully...."); 
 
      }catch (MessagingException mex) {mex.printStackTrace();} 
   } 
}