Wednesday 30 October 2013

Java Simple Mail API Example

 // Create simple class name with JavaMailAPI.java under  package javamailapi
// add "activation.jar" AND "mail.jar" into your Library folder

//Directory look like this


package javamailapi;

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

/**
 *
 * @author br5
 */
public class JavaMailAPI {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       final String username = "senders mail id paste here ";    //login ID Required
       final String password = "senders password paste here";    // Password Required
       Properties props = new Properties();
  props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");

Session session = Session.getDefaultInstance(props,new javax.mail.Authenticator()
{
    protected PasswordAuthentication getPasswordAuthentication()
    {
        return new  PasswordAuthentication(username,password);}
});
try
{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("senders mail id paste here"));
message.addRecipient(Message.RecipientType.TO,new InternetAddress("Recivers mail id paste here "));
message.setSubject("Testing Code For MailAPI");
message.setText("Hi dear This msg is send from my code  ");
message.setText(" hey i am tring to run my new mail API code hope working fine  ");
Transport.send(message);
System.out.println("message sent successfully");
}
catch(MessagingException e)
{
throw new RuntimeException(e);
}
}
}