Friday, November 6, 2015

Send Email Using Java Mail API


Lot you might find this post really handy as it has been so many instances that you find one or the other issues with the email sending using Java Mail API. Following code is working perfectly fine with no errors. Please replace placeholders with your concerned credentials, sender and recipients. Do not forget to download mail.jar and activation.jar which are part of Java Mail API and Activation framework. 

Just make sure you check the credentials you are providing for authentication have following things enabled under URL : http://myaccount.google.com/security

1. Enable "Allow less secure apps"
2. 2-Step Verification Off



import java.util.*;

import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

class SendEmail{

        public static void main(String args[]){
// Sending email start
// Recipient's email ID needs to be mentioned.
      String to= "head.teamgogetters@gmail.com"; 

      // Sender's email ID needs to be mentioned
      String from = "abc@gmail.com";

      // Assuming you are sending email from Gmail
    
      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("email_address","password");
}
});

      try{
         // Create a default MimeMessage object.
         Message message = new MimeMessage(session);

         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));

         // Set To: header field of the header.
         message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

         // Set Subject: header field
         message.setSubject("This is the Subject Line!");

         // Now set the actual message
         message.setText("This is actual message");

         // Send message
         Transport.send(message);
         System.out.println("Sent message successfully....");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }

                  }
}


Feel free to contact me in case of any issues and queries. 

No comments:

Post a Comment