0
Sponsored Links


Ad by Google
In this tutorial, I am going to share you a simple Java program to send mail using gmail server. If your account is more secured using second level of security with gmail account than to send email using application/program you have to be disabled the second level security. While sending email with below given java program if you are getting javax.mail.AuthenticationFailedException exception that means still your gmail account is more secured to disable/turn off you can follow this link,https://www.google.com/settings/security/lesssecureapps

dependency for javax.mail api
<dependency>
  <groupId>javax.mail</groupId>
  <artifactId>mail</artifactId>
  <version>1.4</version>
</dependency>

SendMailExample.java
package com.javamakeuse.dmd;

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

public class SendMailExample {

 static String fromEmail = "fromyourfriend@gmail.com";
 static String password = "******";
 static String msgBody = "Message body, body text for test mail.";

 public static void main(String[] args) {

  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");

  sendMail(props, fromEmail, password, "myfriend@friend.com", "Test mail", msgBody);

 }

 public static void sendMail(Properties properties, final String fromEmail, final String password, String toEmail,
   String subject, String msg) {

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

   Message message = new MimeMessage(session);
   message.setFrom(new InternetAddress(fromEmail));
   message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
   message.setSubject(subject);
   message.setText(msg);

   Transport.send(message);

   System.out.println("Message sent");

  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}
Output:
Message sent
Sponsored Links

0 comments:

Post a Comment