Send email in Java with gmail SMTP

Send email in Java with gmail SMTP example.

MailUtil.java
package mailtest;

import java.io.UnsupportedEncodingException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailUtil {

    private String SMTP_HOST = "smtp.gmail.com";
    private String FROM_ADDRESS = "yourname@gmail.com";
    private String PASSWORD = "yourpassword";
    private String FROM_NAME = "Sameera";

    public boolean sendMail(String[] recipients, String[] bccRecipients, String subject, String message) {
        try {
            Properties props = new Properties();
            props.put("mail.smtp.host", SMTP_HOST);
            props.put("mail.smtp.auth", "true");
            props.put("mail.debug", "false");
            props.put("mail.smtp.ssl.enable", "true");

            Session session = Session.getInstance(props, new SocialAuth());
            Message msg = new MimeMessage(session);

            InternetAddress from = new InternetAddress(FROM_ADDRESS, FROM_NAME);
            msg.setFrom(from);

            InternetAddress[] toAddresses = new InternetAddress[recipients.length];
            for (int i = 0; i < recipients.length; i++) {
                toAddresses[i] = new InternetAddress(recipients[i]);
            }
            msg.setRecipients(Message.RecipientType.TO, toAddresses);


            InternetAddress[] bccAddresses = new InternetAddress[bccRecipients.length];
            for (int j = 0; j < bccRecipients.length; j++) {
                bccAddresses[j] = new InternetAddress(bccRecipients[j]);
            }
            msg.setRecipients(Message.RecipientType.BCC, bccAddresses);

            msg.setSubject(subject);
            msg.setContent(message, "text/plain");
            Transport.send(msg);
            return true;
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(MailUtil.class.getName()).log(Level.SEVERE, null, ex);
            return false;

        } catch (MessagingException ex) {
            Logger.getLogger(MailUtil.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    }

    class SocialAuth extends Authenticator {

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {

            return new PasswordAuthentication(FROM_ADDRESS, PASSWORD);

        }
    }
}


Main.java

package mailtest;

public class Main {

    public static void main(String[] args) {
        String[] recipients = new String[]{"youremail@yahoo.com"};
        String[] bccRecipients = new String[]{"youremail@gmail.com"};
        String subject = "Hi this is test Mail";
        String messageBody = "Test Mail from codesstore.blogspot.com";

        new MailUtil().sendMail(recipients, bccRecipients, subject, messageBody);

    }
}
 
Note: mail.jar  is required.

Can add multiple recipients and BCC recipients
String[] recipients = new String[]{"youremail@yahoo.com","youremail2@yahoo.com"};

Instead of msg.setContent(message, "text/plain") you can use msg.setContent(message, "text/html") then you can add html tags to message body.

28 comments:

  1. Hello...!!! Your Code is very helpful....but i am getting this exception while running it on my machine......
    Can you help me sort this out....

    ReplyDelete
  2. Hi sameera.... How to run this code??

    ReplyDelete
  3. How to solve the javax.mail.SendFailedException: Sending failed; nested exception is: class javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25; nested exception is: java.net.ConnectException: Connection timed out: connect..
    Now am having this exception

    ReplyDelete
    Replies
    1. This is the code for sending emails using Gmail SMTP settings.You have to use your gmail account details for following variables.

      private String FROM_ADDRESS = "yourname@gmail.com";
      private String PASSWORD = "yourpassword";

      I think you have used localhost as SMTP_HOST.That's why code didn't work.

      Delete
  4. Hi
    i got this problem
    javax.mail.MessagingException: Unknown SMTP host: smtp.gmail.com;
    how to fix this.

    ReplyDelete
    Replies
    1. Check weather your internet connection is working properly, proxy or firewall not blocked gmail.
      Check whether variables and properties are set correctly.

      Delete
  5. great i found it is working.........thanks a lot man.........

    ReplyDelete
  6. Hi Sameera; Thanks for uploading the Email code,
    I need your help in this code..... I got error when i run this code.

    Oct 24, 2012 12:34:53 PM main.MailUtil sendMail
    SEVERE: null
    javax.mail.SendFailedException: Sending failed;
    nested exception is:
    javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first. gm7sm3389594wib.10

    at javax.mail.Transport.send0(Transport.java:219)
    at javax.mail.Transport.send(Transport.java:81)
    at main.MailUtil.sendMail(MainUtil.java:56)
    at main.Main.main(Main.java:17)

    Thanks alot.

    ReplyDelete
  7. Hi while i m using this code i m getting following Error.... please help me to clear this
    ERROR:
    com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. qj6sm3608658pbb.69

    at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1388)
    at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:959)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:583)
    at javax.mail.Transport.send0(Transport.java:169)
    at javax.mail.Transport.send(Transport.java:98)
    at nvnr.MailUtil.sendMail(MailUtil.java:60)
    at nvnr.Main.main(Main.java:19)

    ReplyDelete
    Replies
    1. That code works fine for me.

      Did you set the following property to 'true'
      props.put("mail.smtp.ssl.enable", "true");

      Delete
    2. yes I set the property to "true".

      Delete
  8. im using jsp with tomcat server..where should i add these java files and compile them.i want to send mail through jsp.

    ReplyDelete
    Replies
    1. You can import MailUtil.java to your jsp and add the mail sending code which is in main method to your jsp.
      add mail.jar to your libs.

      You only use JSPs? Don't you use Servlets. It is a bad practice.
      If you use servlets you can import MailUtil.java to your servlet.

      Delete
    2. i pinged smtp.gmail.com the reply was " Ping request could not find host smtp.gmail.com ". Please check the name and try a
      gain.

      Delete
    3. may be your proxy blocked smtp.gmail.com

      Delete
  9. How can i send an attachment with mail??????????

    ReplyDelete
    Replies
    1. 1)Change method and add file array

      public boolean sendMail(String[] recipients, String[] bccRecipients, String subject, String message, String files[]) {

      2)
      Remove Line 51 msg.setContent(message, "text/plain"); and add this code

      BodyPart messageBodyPart = new MimeBodyPart();
      messageBodyPart.setContent(message, "text/plain");
      Multipart multipart = new MimeMultipart();
      multipart.addBodyPart(messageBodyPart);

      for (int k = 0; k < files.length; k++) {
      String filename = files[k];
      MimeBodyPart attachmentBodyPart = new MimeBodyPart();
      DataSource source = new FileDataSource(filename);
      attachmentBodyPart.setDataHandler(new DataHandler(source));
      attachmentBodyPart.setFileName(filename);
      multipart.addBodyPart(attachmentBodyPart);
      }

      msg.setContent(multipart);

      3) add attachment to Main.java line 10

      String[] files={"C:/Users/home/Pictures/testimage.jpg"};
      new MailUtil().sendMail(recipients, bccRecipients, subject, messageBody,files);

      Delete
  10. Getting below error while running above code. Please help
    javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
    nested exception is:

    ReplyDelete
  11. this code work fine with glassfish server.

    ReplyDelete
  12. I use your code and on server i have error Could not connect to SMTP host: localhost, port: 25; nested exception is: java.net.ConnectException: Connection refused: connect
    my props is good:
    m_properties = new Properties();
    m_properties.put("mail.smtp.host", "smtp.gmail.com");
    m_properties.put("mail.smtp.socketFactory.port", "465");
    m_properties.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
    m_properties.put("mail.smtp.auth", "true");
    m_properties.put("mail.smtp.port", "465");
    m_properties.put("mail.debug", "false");
    m_properties.put("mail.smtp.ssl.enable", "true");

    and i couldn't figure out cause of this error..

    ReplyDelete
  13. Hi Sameera,

    I want to use the SMTP service which is running in the server(localhost) instead of a gmail account from the application. Help me..

    Maha

    ReplyDelete
  14. how to get rid of following error:


    javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 465; nested exception is: java.net.ConnectException: Connection refused: connect

    ReplyDelete
    Replies
    1. I think you have used localhost as SMTP_HOST.. use smtp.gmail.com

      Delete
  15. Mar 23, 2013 6:15:18 AM MailUtil sendMail
    SEVERE: null
    javax.mail.SendFailedException: Sending failed;
    nested exception is:
    javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command f
    irst. jk1sm1263378pbb.14 - gsmtp

    at javax.mail.Transport.send0(Transport.java:219)
    at javax.mail.Transport.send(Transport.java:81)
    at MailUtil.sendMail(Send.java:51)
    at Send.main(Send.java:83)

    ReplyDelete
  16. when i use above your code at that time got this exception how can i solve this exception pls help me thanks a lot

    ReplyDelete
  17. hi please give me a code to upload an image into database with text fields
    please...
    please help sameera..

    thanks in advance

    ReplyDelete
  18. Hi tried running this code i got this exception nested exception is:
    javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25;
    nested exception is:

    I dont know how to include/exclude my proxy settings...

    ReplyDelete