Sending Email Via Gmail using Java Mail API

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 SendMailTLS {
 public static void main(String[] args) {
 
  // To address
  String to = "to_mail@gmail.com";
  // If any CC email ids
  String cc = "cc@mail.com";
  // If any BCC email ids
  String bcc = "bcc@mail.com";
  // Email Subject
  String subject = "Java Discover";
  // Email content
  String emailText = "Hi All, Welcome to Java Mail API";

  // Sending Email using Gmail SMTP
  sendEmail(to, cc, bcc, subject, emailText);
 }

 public static void sendEmail(String to, String cc, String bcc, String subject, String emailText) {
 
  // From address (Need Gmail ID)
  String from = "from_mail@gmail.com";
  // Password of from address
  String password = "from_password";
  // Gmail host address
  String host = "smtp.gmail.com";
 
  Properties props = System.getProperties();
  props.put("mail.smtp.host", host);
  props.put("mail.smtp.socketFactory.port", "465");
  props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.port", "465");
  props.put("mail.smtp.user", from);
  props.put("password", password);

  Session session = Session.getDefaultInstance(props, null);

  MimeMessage msg = new MimeMessage(session);
  try {
   msg.setFrom(new InternetAddress(from));
  
   // Adding To address
   msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
   // Adding CC email id
   msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
   // Adding BCC email id
   msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

   msg.setSubject(subject);
   msg.setText(emailText);
  
   Transport transport = session.getTransport("smtp");
   transport.connect(host, from, password);
   transport.sendMessage(msg, msg.getAllRecipients());
   transport.close();
  
   System.out.println("Email was sent successfully.....");
  
  } catch (AddressException e) {
   e.printStackTrace();
  } catch (MessagingException e) {
   e.printStackTrace();
  }
 }

}

Search This Blog

All the rights are reserved to this blog is belongs to me only.. Powered by Blogger.