Monday, May 28, 2012

Send Mail using Java-Mail API

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class sendMail
{
public static final String MAIL_SERVER = "smtp.gmail.com";
public static final String USERNAME = "Your gmail user name should be here";
public static final String PASSWORD = "gmail password";
public static String fromAddress = null;
public static String toAddress = null;

public static void main(String[] args)
{
try
{
fromAddress = "gmail email id";
String toAddress = "xyz@psdf.com";
String subject = "This is a test Message";
String message = "Hello Hows u?";

Properties properties = System.getProperties();
properties.put("mail.smtps.host", MAIL_SERVER);
properties.put("mail.smtps.auth", "true");

Session session = Session.getInstance(properties);
MimeMessage msg = new MimeMessage(session);

msg.setFrom(new InternetAddress(fromAddress));
msg.addRecipients(Message.RecipientType.TO, toAddress);
msg.setSubject(subject);
msg.setText(message);

Transport tr = session.getTransport("smtp");
tr.connect(MAIL_SERVER, USERNAME, PASSWORD);
tr.sendMessage(msg, msg.getAllRecipients());
tr.close();

}
catch (AddressException ex)
{
System.out.println("in addressException");
System.out.println(ex.getMessage());

}
catch (MessagingException ex)
{

System.out.println(ex.getMessage());
}
System.out.println("message successfully sent");
}

}

No comments:

Post a Comment