JavaMail API - SPLessons

JavaMail Gmail SMTP

Chapter 12

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

JavaMail Gmail SMTP

JavaMail Gmail SMTP

shape Description

Installing particular server to work with Java mail API is time consumption task so it’s better to follow easy steps. Actually in the previous chapters gone through JangoSMTP server for sending emails. But now here discussing about JavaMail Gmail SMTP. By Secured Socket Layer (SSL) through gmail SMTP server sending the email. Generally SSL represents for security while sending an email through SMTP gmail server.

shape Conceptual
figure

The setup for gmail SMTP shown below.
Here from the above figures it is clear that settings of gmail SMTP server username, password with port number for sending emails and receiving emails from pop server.

shape Example

import java.util.Properties;  
import javax.mail.*;  
import javax.mail.internet.*;  
public class SendMailSSL {  
 public static void main(String[] args) {    
 String to="venkatanaresh35@gmail.com";//change accordingly   
  //To get the session object  
  Properties props = new Properties();  
  props.put("mail.smtp.host", "smtp.gmail.com");  
  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");     
  Session session = Session.getDefaultInstance(props,  
   new javax.mail.Authenticator() {  
   protected PasswordAuthentication getPasswordAuthentication() {  
   return new PasswordAuthentication("nayuninaresh93@gmail.com","password");//change accordingly  
   }  
  });     
  //To compose message  
  try {  
   MimeMessage message = new MimeMessage(session);  
   message.setFrom(new InternetAddress("nayuninaresh93@gmail.com"));//change accordingly  
   message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));  
   message.setSubject("Hello");  
   message.setText("SPLESSONS.....");       
   //To send message  
   Transport.send(message);    
   System.out.println("Hey man,Message has been sent successfully");     
  } catch (MessagingException e) {throw new RuntimeException(e);}    
 }  
}

Output
When compile the program following out result will be come.

Hey man,Message has been sent successfully

Summary

shape Key Points

  • JavaMail Gmail SMTP – Here discussing about SMTP server for gmail.
  • JavaMail Gmail SMTP – By Secured Socket Layer (SSL) through gmail SMTP server sending the email.
  • JavaMail Gmail SMTP – Generally SSL represents for security while sending an email through SMTP gmail server.
  • JavaMail Gmail SMTP – Set up configuration of ¬†gmail SMTP server shown in above figure.