Friday, April 17, 2009

Send mail using javamail and gmail

This is my fully tested code. You need javamail 1.4 api to run this. If u find any kind of exception check ur system firewall that is blocking to send mail.

Add mail.jar and activation.jar in ur buildpath and run the code:


import java.io.File;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SimpleSSLMail {

  private static final String SMTP_HOST_NAME = "smtp.gmail.com";
  private static final int SMTP_HOST_PORT = 465;
  private static final String SMTP_AUTH_USER = "xxxxx@gmail.com";
  private static final String SMTP_AUTH_PWD = "xxxx";

  public static void main(String[] args) throws Exception{
  new SimpleSSLMail().test();
  }

  public void test() throws Exception{
  Properties props = new Properties();

  props.put("mail.transport.protocol", "smtps");
  props.put("mail.smtps.host", SMTP_HOST_NAME);
  props.put("mail.smtps.auth", "true");
  // props.put("mail.smtps.quitwait", "false");

  Session mailSession = Session.getDefaultInstance(props);
   
  mailSession.setDebug(true);
   
  Transport transport = mailSession.getTransport();

  MimeMessage message = new MimeMessage(mailSession);
  message.setSubject("Hello Attatched world");
   
  //message.setContent("This is a test", "text/plain");
   
  // content
  MimeBodyPart mimeBodyPart = new MimeBodyPart();
   
  //mimeBodyPart.setText("Link goes here:");  
  String strLink = " Link goes here : http://www.google.com";
  mimeBodyPart.setText(strLink);
   
  // multipart is the main content holder
  Multipart multipart = new MimeMultipart();
  multipart.addBodyPart(mimeBodyPart);
   
  // Part two is attachment
  File f = new File("F:\\angel.JPG");
  if(f.exists() && f.isFile())
  {
  System.out.println("attatching file......."+f.getName());
  mimeBodyPart = new MimeBodyPart();
  DataSource source = new FileDataSource(f);  
  DataHandler handler = new DataHandler(source);
  mimeBodyPart.setDataHandler(handler);
   
  mimeBodyPart.setFileName(f.getName());
   
  multipart.addBodyPart(mimeBodyPart);
   
  }
   
  // add multipart data to message
  message.setContent(multipart);
   
   
  message.addRecipient(Message.RecipientType.TO,
  new InternetAddress("xxxx@yahoo.com"));

  transport.connect
  (SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD);

   
  transport.sendMessage(message,
  message.getRecipients(Message.RecipientType.TO));
  transport.close();
  }
}


No comments: