Send Email in Java using Gmail Server

This post will show you how to send mail in java using Gmail server. For that Gmail provides SMTP host as smtp.gmail.com and SMTP port as 465.

You need to have one Gmail account and in below code you need to put that one instead of from_address@gmail.com and from_password is your Gmail account's password.
to_address can be anything i.e it can be gmail, yahoo any email address. But from_address should be your gmail account.

Here we are going to use Java Mail API. Here I am going to use Maven so add below dependency in your pom.xml. If you have other build tool then add accordingly.
<dependency>
 <groupId>javax.mail</groupId>
 <artifactId>mail</artifactId>
 <version>1.4.7</version>
</dependency>

There are 3 steps here.
1) Defining SMTP properties.
2) Creating Session object
3) Sending an email

Here is the complete code to send mail using Gmail.

package com.infybuzz.mail;

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;

public class MailSender {

 public static void main(String[] args) {
  String to = "to_address"; // to address. It can be any like gmail, yahoo etc.
  String from = "from_address@gmail.com"; // from address. As this is using Gmail SMTP your from address should be gmail
  String password = "from_password"; // password for from gmail address that you have used in above line. 

  Properties prop = new Properties();
  prop.put("mail.smtp.host", "smtp.gmail.com");
  prop.put("mail.smtp.port", "465");
  prop.put("mail.smtp.auth", "true");
  prop.put("mail.smtp.socketFactory.port", "465");
  prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

  Session session = Session.getInstance(prop, new javax.mail.Authenticator() {
   protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(from, password);
   }
  });

  try {

   Message message = new MimeMessage(session);
   message.setFrom(new InternetAddress(from));
   message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
   message.setSubject("Test Mail From Gmail Accocunt");
   message.setText("Mail From Java Code Using Gmail...");

   Transport.send(message);

   System.out.println("Mail Sent...");

  } catch (MessagingException e) {
   e.printStackTrace();
  }
 }
}

Checkout Below Useful Courses :-





0 Comments