Monday, June 23, 2014

Send mail using gmail SMTP server

First of all three libraries need to be added in the JDK,
ojdbc6_g.jar and

javax.mail.jar contains the mail server libraries

Complete working code for sending mail using gmail smtp server

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;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;

public class JavaEmail {

  Properties emailProperties;
  Session mailSession;
  MimeMessage emailMessage;

  public static void main(String args[]) throws AddressException,
      MessagingException {

    JavaEmail javaEmail = new JavaEmail();


  public void setMailServerProperties() {

    String emailPort = "587";//gmail's smtp port

    emailProperties = System.getProperties();
    emailProperties.put("", "");
    emailProperties.put("mail.smtp.port", emailPort);
    emailProperties.put("mail.smtp.auth", "true");
    emailProperties.put("mail.smtp.starttls.enable", "true");


  public void createEmailMessage() throws AddressException,
      MessagingException {
    String toEmails =  "complete_email_address_of_receiver" ;
    String emailSubject = "Java Email";
    String emailBody = "This is an email sent by <b>JavaMail</b> api.";//here we can add HTML syntax also

    mailSession = Session.getDefaultInstance(emailProperties, null);
    emailMessage = new MimeMessage(mailSession);

   // for (int i = 0; i < toEmails.length; i++) {
      emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmails));
 //   }

    emailMessage.setContent(emailBody, "text/html");//for a html email
    //emailMessage.setText(emailBody);// for a text email


  public void sendEmail() throws AddressException, MessagingException {

    String emailHost = "";
    String fromUser = "";//just the id alone without
    String fromUserEmailPassword = "password_of_the_gmail_account";

    Transport transport = mailSession.getTransport("smtp");

    transport.connect(emailHost, fromUser, fromUserEmailPassword);
    transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
    System.out.println("Email sent successfully.");


//Enjoy using gmail to make your own mail client

No comments:

Post a Comment