How to send mail using JAVA?

UPDATED: 05 January 2011
SMTP, Java Mail
Mail is one of the important part of any application. Mail service helps you to notify important update to your users. There are lots of mail service provider over internet now a days. Choose one that fulfill your all requirements. They all follow almost similar way for mail delivery.

//imports required in below code.
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
private static final String SMTP_HOST_NAME = "smtp.gmail.com"; //smtp URL
private static final int SMTP_HOST_PORT = 465; //port number
private static final String SMTP_AUTH_USER = "email_ID"; //email_id of sender
private static final String SMTP_AUTH_PWD = "password"; //password of sender email_id

try{
    Properties props = new Properties(); 
    props.put("mail.transport.protocol", "smtps");
    props.put("mail.smtps.host", SMTP_HOST_NAME);
    props.put("mail.smtps.auth", "true");

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

    MimeMessage message = new MimeMessage(mailSession);
    message.setSubject("Java Mail");
    message.setContent("Type_your_msg_here","text/html");
    message.addRecipient(Message.RecipientType.TO,new InternetAddress("abc@javaquery.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();
} catch (Exception e) {
    e.printStackTrace();
}
Important Note: Change your SMTP Host, SMTP port, Email ID from you want to send mail, Email Password and Message, To, Subject, Content type details in above code.

2 comments :

  1. how to use java mail api???

    ReplyDelete
  2. In the end of the article there is API download link u need to just import it to proper project and after that codding is given..in the article..

    ReplyDelete