Sunday, July 03, 2011

Send E-Mail Using SMTP

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 = "useremailid"; // Please Add user Email Id
public static final String PASSWORD = "password"; // Please Add user's password

public static void main(String[] args)
{
try
{
String fromAddress = "fromemailId";
String toAddress = "toemdilaid";
String subject = "SMTP";
String message = "Java SMPT SERVER....";

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);
System.out.println("start mail send...");
Transport tr = session.getTransport("smtps");
tr.connect(MAIL_SERVER, USERNAME, PASSWORD);
tr.sendMessage(msg, msg.getAllRecipients());
System.out.println("mail send...");
tr.close();
}
catch (AddressException ex)
{
System.out.println(ex.getMessage());
}
catch (MessagingException ex)
{
System.out.println(ex.getMessage());
}
}
}


Note : This Program Require mail.jar file if u would like to use this program please download mail.jar from www.java2s.com

No comments:

Post a Comment