Sending Email using JAVA

Sending email in java is very simple task, as you don’t have to write as much code.  Here I am going to write a code example that send email using JavaMail API via Gmail SMTP server.

In order to run this example you will need to import Mail.jar as dependency library.


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



public class MailUtil
{
      
    public static void main(String [] args)
    {
       // Set recipient email address here
       String rec[]= {"abc@gmail.com"};
       try {
                    
           sendMail("Sample Test Email", "This is Message Body...", rec);
       }
       catch (Exception e)
       {
           e.printStackTrace();
       }
    }
      
    public static void sendMail(String subject, String message,
                     String [] recipients) throws Exception
    {
       try
       {
                    
              boolean debug = false;
              Properties props = new Properties();
              // Set the host SMTP address
              props.put("mail.smtp.starttls.enable", "true");
              props.put("mail.smtp.host", "smtp.gmail.com");
              props.put("mail.smtp.port", "587");
              // create some properties and get the default Session
              Session session = Session.getDefaultInstance(props, null);
              session.setDebug(debug);
              // create a message
              Message msg = new MimeMessage(session);
                    
              // Set Sender email address here
              InternetAddress addressFrom = new InternetAddress("xyz@gmail.com");
              msg.setFrom(addressFrom);
                    
              InternetAddress [] addressTo = new InternetAddress [recipients.length];
              for ( int i = 0 ; i < recipients.length ; i++ )
              {
                  addressTo[i] = new InternetAddress(recipients[i]);
              }
              msg.setRecipients(Message.RecipientType.TO, addressTo);
                    
              // Setting the Subject and Content Type
              msg.setSubject(subject + "  " + new Date());
              msg.setContent("\n" + message, "text/plain");
              Transport.send(msg);
                    
              System.out.println("Message has been sent successfully...");
              System.out.println("Please check your inbox...");
                    
          }
          catch (Exception e)
          {
             e.printStackTrace();
          }
    }
}

No comments:

Post a Comment