Wednesday, April 14, 2010

Send EMail by Java

This is a program used to send Email using Java with use of Gmail SMTP Server.
For using this code just change Account Settings.
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class SendMail {
  public static void main(String[] args) {
    String userName = "gdb.sci123@gmail.com";
    String passWord = "password";
    String host = "smtp.gmail.com";
    String auth = "true";
    boolean debug = false;
    String to = "gdb_sci123@rediffmail.com";
    String subject = "MySubject";
    String text = "Jai Shree Mataji, This email is send by Java Program";

    Properties props = new Properties();
    props.put("mail.smtp.user", userName);
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.auth", auth);
    props.put("mail.smtp.port", "465");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", false);
    try {
      Session session = Session.getDefaultInstance(props, null);
      session.setDebug(debug);
      
      MimeMessage msg = new MimeMessage(session);
      msg.setText(text);
      msg.setSubject(subject);
      msg.setFrom(new InternetAddress(userName));
      msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
      msg.saveChanges();
      
      Transport transport = session.getTransport("smtp");
      transport.connect(host, userName, passWord);
      transport.sendMessage(msg, msg.getAllRecipients());
      transport.close();
    } catch (Exception mex) {
      mex.printStackTrace();
    }
  }
}


For more information visit Dwij IT Solutions.


No comments:

Post a Comment

Your comments will be important to impprove this blog.
Please have some comments or doubts freely.