How to send email in java using gmail smtp server

package Demo;
import javax.mail.Message;
import javax.mail.Session;

import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MainA {
    public static void main(String[] args) throws Exception {
        String[] to = {
        String[] cc = {
        String[] bcc = {
        // This is for google
        MainA.sendMail("", "*******", "", "25", "true", "true",
            true, "", "false", to, cc, bcc,
            "hi baba don’t send virus mails..",
            "This is my style…of reply..If u send virus mails..");

    public synchronized static boolean sendMail(String userName,
        String passWord, String host, String port, String starttls,
        String auth, boolean debug, String socketFactoryClass,
        String fallback, String[] to, String[] cc, String[] bcc,
        String subject, String text) {
        Properties props = new Properties();
        props.put("mail.smtp.user", userName);
        props.put("", host);
        props.put("port", port);
        props.put("mail.smtp.starttls.enable", starttls);
        props.put("mail.smtp.auth", auth);
        props.put("", "");
        if (debug) {
            props.put("mail.smtp.debug", "true");
        } else {
            props.put("mail.smtp.debug", "false");
        try {
            Session smtpSession = Session.getDefaultInstance(props, null);
            MimeMessage msg = new MimeMessage(smtpSession);
            msg.setFrom(new InternetAddress(""));
            for (int i = 0; i < to.length; i++) {
                msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
            for (int i = 0; i < cc.length; i++) {
                msg.addRecipient(Message.RecipientType.CC, new InternetAddress(
            for (int i = 0; i < bcc.length; i++) {
                    new InternetAddress(bcc[i]));
            Transport transport = smtpSession.getTransport("smtp");
            transport.connect(host, userName, passWord);
            transport.sendMessage(msg, msg.getAllRecipients());
            return true;
        } catch (Exception mex) {
            return false;

NOTE : Before execution STEPS to be followed

1.Go to This link
2.Login to your gmail
3.Access for less secure apps select “Turn on”
4.Run the code in IDE


2 thoughts on “How to send email in java using gmail smtp server

  1. How to resolve duplicate recipients will be consolidated. ij6sm537806igb.1 – gsmtp issue while sending mail through gmail

Leave a Reply to assist you..

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s