How to send email in java using gmail smtp server

We know that if we have to send a mail to somebody from java code, we need to have access on some mail server credentials. Well, not always.

Google has provided free access to one of its mail server and you can use it java code.

Below written code if more like a note to my self. So, if i need it sometime, you can refer here.

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class JavaEmail
{
    Session mailSession;

    public static void main(String args[]) throws AddressException,    MessagingException
    {
        JavaEmail javaEmail = new JavaEmail();
        javaEmail.setMailServerProperties();
        javaEmail.draftEmailMessage();
        javaEmail.sendEmail();
    }

    private void setMailServerProperties()
    {
        Properties emailProperties = System.getProperties();
        emailProperties.put("mail.smtp.port", "586");
        emailProperties.put("mail.smtp.auth", "true");
        emailProperties.put("mail.smtp.starttls.enable", "true");
        mailSession = Session.getDefaultInstance(emailProperties, null);
    }

    private MimeMessage draftEmailMessage() throws AddressException, MessagingException
    {
        String[] toEmails = { "howtodoinjava@gmail.com" };
        String emailSubject = "Test email subject";
        String emailBody = "This is an email sent by http://www.howtodoinjava.com.";
        MimeMessage emailMessage = new MimeMessage(mailSession);
        /**
         * Set the mail recipients
         * */
        for (int i = 0; i < toEmails.length; i++)
        {
            emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmails[i]));
        }
        emailMessage.setSubject(emailSubject);
        /**
         * If sending HTML mail
         * */
        emailMessage.setContent(emailBody, "text/html");
        /**
         * If sending only text mail
         * */
        //emailMessage.setText(emailBody);// for a text email
        return emailMessage;
    }

    private void sendEmail() throws AddressException, MessagingException
    {
        /**
         * Sender's credentials
         * */
        String fromUser = "user-email@gmail.com";
        String fromUserEmailPassword = "*******";

        String emailHost = "smtp.gmail.com";
        Transport transport = mailSession.getTransport("smtp");
        transport.connect(emailHost, fromUser, fromUserEmailPassword);
        /**
         * Draft the message
         * */
        MimeMessage emailMessage = draftEmailMessage();
        /**
         * Send the mail
         * */
        transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
        transport.close();
        System.out.println("Email sent successfully.");
    }
}

Happy Learning !!

Comments

  1. Kapeesh Gupta says

    Sir,
    I updated my code.after updation eject error mention below.

    Thanks

    run:
    DEBUG: setDebug: JavaMail version 1.5.1
    DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
    DEBUG SMTP: useEhlo true, useAuth true
    DEBUG SMTP: trying to connect to host “host”, port 25, isSSL false
    com.sun.mail.util.MailConnectException: Couldn’t connect to host, port: host, 25; timeout -1;
    nested exception is:
    java.net.UnknownHostException: host
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1984)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:656)
    at javax.mail.Service.connect(Service.java:345)
    at javax.mail.Service.connect(Service.java:226)
    at maina.MainA.sendMail(MainA.java:92)
    at maina.MainA.main(MainA.java:32)
    Caused by: java.net.UnknownHostException: host
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:158)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:154)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:380)
    at java.net.Socket.connect(Socket.java:569)
    at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:569)
    at sun.security.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:160)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:301)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:208)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1950)
    … 5 more
    BUILD SUCCESSFUL (total time: 2 seconds)

    My 32 line and 92 line Coding is:-

    32 line no.) MainA.sendMail(“email”, “password”, “host”, “port”, “true”, “true”, true, “javax.net.ssl.SSLSocketFactory”, “false”, to, cc, bcc,
    “hi baba don’t send virus mails..”,
    “This is my style…of reply..If u send virus mails..”);

    92 line no.) msg.saveChanges();
    Transport transport = session.getTransport(“smtp”);
    transport.connect(host, userName, passWord);
    transport.sendMessage(msg, msg.getAllRecipients());
    transport.close();
    return true;
    }
    catch (Exception mex)
    {
    mex.printStackTrace();
    return false;
    }
    }

    • says

      This error is thrown to indicate that the IP address of a host could not be determined.
      Find out the IP address of mail server i.e. “blr-outlook.ibm.com” and place that IP directly into “props.put(“mail.smtp.host”, host);”

      • Kapeesh Gupta says

        Hi,
        Sorry to say sir,but message does not send in email ids.this code used in my personal machine but that is not even running.Please help me.I’ve used editor NetBeans 7.2.and i’m sending my debug after run.

        Thanks

        DEBUG: setDebug: JavaMail version 1.5.1
        DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
        DEBUG SMTP: useEhlo true, useAuth true
        DEBUG SMTP: trying to connect to host “host”, port 25, isSSL false
        BUILD SUCCESSFUL (total time: 3 seconds)

        • says

          This code works buddy. Just your machine is not able to resolve hostname. Open windows command prompt. Type “ping blr-outlook.ibm.com”. See if machine is reachable. I believe it will not and will timeout. If you can ping above from command prompt, then ONLY this code will run.

          • Kapeesh Gupta says

            Hi,
            Finally my code is mention below.I don’t know why is not message send in email ids.
            Please check my code and find my mistake and correct them.I check “ping blr-outlook.ibm.com” in cmd.

            I saw in cmd after enter this blah blah..
            Thanks

            Pinging blr-outlook.ibm.com [11.201.51.251] with 32 bytes of data:
            Reply from 11.201.51.251: bytes=32 time=93ms TTL=119
            Reply from 11.201.51.251: bytes=32 time=76ms TTL=119
            Reply from 11.201.51.251: bytes=32 time=71ms TTL=119
            Reply from 11.201.51.251: bytes=32 time=70ms TTL=119

            Ping statistics for 11.201.51.251:
            Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
            Approximate round trip times in milli-seconds:
            Minimum = 70ms, Maximum = 93ms, Average = 77ms

            /*
            * To change this template, choose Tools | Templates
            * and open the template in the editor.
            */
            package maina;

            import javax.mail.*;
            import javax.mail.internet.*;
            import java.util.*;
            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 MainA
            {
            String d_email = “KA11479G”,
            d_password = “kn@nov2014″,
            d_host = “blr-outlook.ibm.com”,
            d_port = “25”,
            m_to = “kapeesh.gupta@ibm.com”,
            m_subject = “Testing”,
            m_text = “Hey, this is the testing email using blr-outlook.ibm.com”;

            public static void main(String[] args)throws Exception
            {
            String[] to={“kapeesh.gupta@ibm.com”};
            String[] cc={“debarka.sarkar@ibm.com”};
            String[] bcc={“amit.kudale@ibm.com”};
            //This is for google
            MainA.sendMail(“email”, “password”, “host”, “port”, “true”, “true”, true, “javax.net.ssl.SSLSocketFactory”, “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();
            //Properties props=System.getProperties();
            props.put(“mail.smtp.user”, userName);
            props.put(“mail.smtp.host”,host);
            if(!””.equals(port)) {
            props.put(“25″, port);
            }
            if(!””.equals(starttls)) {
            props.put(“mail.smtp.starttls.enable”,starttls);
            }
            props.put(“mail.smtp.auth”, auth);
            if(debug) {
            props.put(“mail.smtp.debug”, “true”);
            } else {
            props.put(“mail.smtp.debug”, “false”);
            }
            if(!””.equals(port)) {
            props.put(“mail.smtp.socketFactory.port”, port);
            }
            if(!””.equals(socketFactoryClass)) {
            props.put(“mail.smtp.socketFactory.class”,socketFactoryClass);
            }
            if(!””.equals(fallback)) {
            props.put(“mail.smtp.socketFactory.fallback”, fallback);
            }
            try
            {
            Session smtpSession = Session.getDefaultInstance(props, null);
            smtpSession.setDebug(true);
            MimeMessage msg = new MimeMessage(smtpSession);
            msg.setText(text);
            msg.setSubject(subject);
            msg.setFrom(new InternetAddress(“kapeesh.gupta@ibm.com”));
            for(int i=0;i<to.length;i++) {
            msg.addRecipient(Message.RecipientType.TO,
            new InternetAddress(to[i]));
            }
            for(int i=0;i<cc.length;i++) {
            msg.addRecipient(Message.RecipientType.CC,
            new InternetAddress(cc[i]));
            }
            for(int i=0;i<bcc.length;i++) {
            msg.addRecipient(Message.RecipientType.BCC,
            new InternetAddress(bcc[i]));
            }
            msg.saveChanges();
            Transport transport = smtpSession.getTransport("smtp");
            transport.connect(host, userName, passWord);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
            return true;
            }
            catch (Exception mex)
            {
            return false;
            }
            }
            }

            • says

              I edited your code and below is working code. You must have also got an email. As I am not in IBM network, I still have used gmail SMTP. Please change SMTP Host, port, username, password in application and it should work. And from next time, please do not post any password in comments.

              import java.util.Properties;
              
              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 = { "kapeesh.gupta@ibm.com" };
              		String[] cc = { "debarka.sarkar@ibm.com" };
              		String[] bcc ={ "amit.kudale@ibm.com" };
              		// This is for google
              		MainA.sendMail("lokeshgupta1981@gmail.com", "**********", "smtp.gmail.com", "25", "true", "true",
              				true, "javax.net.ssl.SSLSocketFactory", "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("mail.smtp.host", host);
              		props.put("port", port);
              		props.put("mail.smtp.starttls.enable", starttls);
              		props.put("mail.smtp.auth", auth);
              		if (debug) {
              			props.put("mail.smtp.debug", "true");
              		} else {
              			props.put("mail.smtp.debug", "false");
              		}
              		try {
              			Session smtpSession = Session.getDefaultInstance(props, null);
              			smtpSession.setDebug(true);
              			MimeMessage msg = new MimeMessage(smtpSession);
              			msg.setText(text);
              			msg.setSubject(subject);
              			msg.setFrom(new InternetAddress("lokeshgupta1981@gmail.com"));
              			for (int i = 0; i < to.length; i++) {
              				msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
              						to[i]));
              			}
              			for (int i = 0; i < cc.length; i++) {
              				msg.addRecipient(Message.RecipientType.CC, new InternetAddress(
              						cc[i]));
              			}
              			for (int i = 0; i < bcc.length; i++) {
              				msg.addRecipient(Message.RecipientType.BCC,
              						new InternetAddress(bcc[i]));
              			}
              			msg.saveChanges();
              			Transport transport = smtpSession.getTransport("smtp");
              			transport.connect(host, userName, passWord);
              			transport.sendMessage(msg, msg.getAllRecipients());
              			transport.close();
              			return true;
              		} catch (Exception mex) {
              			mex.printStackTrace();
              			System.out.println(mex.getLocalizedMessage());
              			return false;
              		}
              	}
              }
              

              Output:

              DEBUG: setDebug: JavaMail version 1.5.2
              DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
              DEBUG SMTP: useEhlo true, useAuth true
              DEBUG SMTP: trying to connect to host “smtp.gmail.com”, port 25, isSSL false
              220 mx.google.com ESMTP wk2sm5328789pac.12 – gsmtp
              DEBUG SMTP: connected to host “smtp.gmail.com”, port: 25

              EHLO 192.168.2.6
              250-mx.google.com at your service, [14.102.107.130]
              250-SIZE 35882577
              250-8BITMIME
              250-STARTTLS
              250-ENHANCEDSTATUSCODES
              250-PIPELINING
              250-CHUNKING
              250 SMTPUTF8
              DEBUG SMTP: Found extension “SIZE”, arg “35882577”
              DEBUG SMTP: Found extension “8BITMIME”, arg “”
              DEBUG SMTP: Found extension “STARTTLS”, arg “”
              DEBUG SMTP: Found extension “ENHANCEDSTATUSCODES”, arg “”
              DEBUG SMTP: Found extension “PIPELINING”, arg “”
              DEBUG SMTP: Found extension “CHUNKING”, arg “”
              DEBUG SMTP: Found extension “SMTPUTF8″, arg “”
              STARTTLS
              220 2.0.0 Ready to start TLS
              EHLO 192.168.2.6
              250-mx.google.com at your service, [14.102.107.130]
              250-SIZE 35882577
              250-8BITMIME
              250-AUTH LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN
              250-ENHANCEDSTATUSCODES
              250-PIPELINING
              250-CHUNKING
              250 SMTPUTF8
              DEBUG SMTP: Found extension “SIZE”, arg “35882577”
              DEBUG SMTP: Found extension “8BITMIME”, arg “”
              DEBUG SMTP: Found extension “AUTH”, arg “LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN”
              DEBUG SMTP: Found extension “ENHANCEDSTATUSCODES”, arg “”
              DEBUG SMTP: Found extension “PIPELINING”, arg “”
              DEBUG SMTP: Found extension “CHUNKING”, arg “”
              DEBUG SMTP: Found extension “SMTPUTF8″, arg “”
              DEBUG SMTP: Attempt to authenticate using mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM
              DEBUG SMTP: AUTH LOGIN command trace suppressed
              DEBUG SMTP: AUTH LOGIN succeeded
              DEBUG SMTP: use8bit false
              MAIL FROM:
              250 2.1.0 OK wk2sm5328789pac.12 – gsmtp
              RCPT TO:
              250 2.1.5 OK wk2sm5328789pac.12 – gsmtp
              RCPT TO:
              250 2.1.5 OK wk2sm5328789pac.12 – gsmtp
              RCPT TO:
              250 2.1.5 OK wk2sm5328789pac.12 – gsmtp
              DEBUG SMTP: Verified Addresses
              DEBUG SMTP: kapeesh.gupta@ibm.com
              DEBUG SMTP: debarka.sarkar@ibm.com
              DEBUG SMTP: amit.kudale@ibm.com
              DATA
              354 Go ahead wk2sm5328789pac.12 – gsmtp
              From: lokeshgupta1981@gmail.com
              To: kapeesh.gupta@ibm.com
              Cc: debarka.sarkar@ibm.com
              Message-ID: <12869066.0.1419089528207.JavaMail.user@user-PC>
              Subject: =?Cp1252?Q?hi_baba_don=92t_send_virus_mails..?=
              MIME-Version: 1.0
              Content-Type: text/plain; charset=Cp1252
              Content-Transfer-Encoding: quoted-printable

              This is my style=85of reply..If u send virus mails..
              .
              250 2.0.0 OK 1419089555 wk2sm5328789pac.12 – gsmtp
              QUIT
              221 2.0.0 closing connection wk2sm5328789pac.12 – gsmtp

              • Kapeesh Gupta says

                Hello Sir,
                This time eject error in my code.username and password not accepted.Please tell me and sorry for disturbing.
                Why userName and password not accepted while i entered correct gmail id or password.Still my entries are wrong.Why??

                Line no.21 and Line no.64.are mention below.

                21) MainA.sendMail(“kapeesh1@gmail.com”, “*****”, “smtp.gmail.com”, “25”, “true”, “true”,
                true, “javax.net.ssl.SSLSocketFactory”, “false”, to, cc, bcc,

                64) transport.connect(host,userName,passWord);

                Thanks

                DEBUG SMTP: Attempt to authenticate using mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM
                DEBUG SMTP: AUTH LOGIN command trace suppressed
                DEBUG SMTP: AUTH LOGIN failed
                javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted. Learn more at
                535 5.7.8 http://support.google.com/mail/bin/answer.py?answer=14257 c9sm14915179pdj.52 – gsmtp

                535-5.7.8 Username and Password not accepted. Learn more at
                535 5.7.8 http://support.google.com/mail/bin/answer.py?answer=14257 c9sm14915179pdj.52 – gsmtp

                at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:892)
                at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:814)
                at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:728)
                at javax.mail.Service.connect(Service.java:364)
                at javax.mail.Service.connect(Service.java:245)
                at maina.MainA.sendMail(MainA.java:64)
                at maina.MainA.main(MainA.java:21)
                BUILD SUCCESSFUL (total time: 13 seconds)

  2. Kapeesh says

    Hello sir,
    Please give me right code.

    My error found is:-

    debug:
    java.lang.NoClassDefFoundError: sendmail/SendMail
    Caused by: java.lang.ClassNotFoundException: sendmail.SendMail
    at java.net.URLClassLoader$1.run(URLClassLoader.java:220)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:209)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:208)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:325)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:270)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:338)
    Error: Could not find the main class sendmail.SendMail.
    Error: A JNI error has occurred, please check your installation and try again
    Exception in thread “main” Java Result: 1
    BUILD SUCCESSFUL (total time: 0 seconds)

      • Kapeesh says

        Hello Sir,
        Thanks for give me answer.sir my code perfectly run in my system but message does not send in mail ids.

        Please see this output.and find my mistake and tell me.

        Thanks

        DEBUG: JavaMail version 1.5.1
        DEBUG: URL jar:file:/C:/Users/KA11479G/Documents/NetBeansProjects/Mail1/lib/smtp.jar!/META-INF/javamail.providers
        DEBUG: successfully loaded resource: jar:file:/C:/Users/KA11479G/Documents/NetBeansProjects/Mail1/lib/smtp.jar!/META-INF/javamail.providers
        DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
        DEBUG: Tables of loaded providers
        DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle]}
        DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]}
        DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
        DEBUG: URL jar:file:/C:/Users/KA11479G/Documents/NetBeansProjects/Mail1/lib/smtp.jar!/META-INF/javamail.address.map
        DEBUG: successfully loaded resource: jar:file:/C:/Users/KA11479G/Documents/NetBeansProjects/Mail1/lib/smtp.jar!/META-INF/javamail.address.map
        DEBUG: setDebug: JavaMail version 1.5.1
        DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
        DEBUG SMTP: need username and password for authentication
        DEBUG SMTP: useEhlo true, useAuth true
        DEBUG SMTP: trying to connect to host “smtp.ibm.com”, port 25, isSSL false
        Oops something has gone pearshaped!
        com.sun.mail.util.MailConnectException: Couldn’t connect to host, port: smtp.ibm.com, 25; timeout -1;
        nested exception is:
        java.net.UnknownHostException: smtp.ibm.com
        BUILD SUCCESSFUL (total time: 2 seconds)

                • Kapeesh Gupta says

                  Hi,
                  I discussed with admin.He told me,our Port no is “25”,Host Name is “blr-outlook.ibm.com”,userName-“KA11479G”,but message does not send in mail id.i m sending my code please see my code and find errors.And send me correct code.

                  Thanks

                  import javax.mail.*;
                  import javax.mail.internet.*;
                  import java.util.*;
                  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 Main1
                  {
                  String d_email = “KA11479G”,
                  d_password = “kn@nov2014″,
                  d_host = “blr-outlook.ibm.com”,
                  d_port = “25”,
                  m_to = “kapeesh.gupta@ibm.com”,
                  m_subject = “Testing”,
                  m_text = “Hey, this is the testing email using blr-outlook.ibm.com”;
                  public static void main(String[] args)
                  {
                  String[] to={“kapeesh.gupta@ibm.com”};
                  String[] cc={“debarka.sarkar@ibm.com”};
                  String[] bcc={“amit.kudale@ibm.com”};
                  //This is for google
                  Main1.sendMail(“email”, “password”, “host”, “port”, “true”, “true”, true, “javax.net.ssl.SSLSocketFactory”, “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();
                  //Properties props=System.getProperties();
                  props.put(“mail.smtp.user”, userName);
                  props.put(“mail.smtp.host”, host);
                  if(!””.equals(port)) {
                  props.put(“mail.smtp.port”, port);
                  }
                  if(!””.equals(starttls)) {
                  props.put(“mail.smtp.starttls.enable”,starttls);
                  }
                  props.put(“mail.smtp.auth”, auth);
                  if(debug) {
                  props.put(“mail.smtp.debug”, “true”);
                  } else {
                  props.put(“mail.smtp.debug”, “false”);
                  }
                  if(!””.equals(port)) {
                  props.put(“mail.smtp.socketFactory.port”, port);
                  }
                  if(!””.equals(socketFactoryClass)) {
                  props.put(“mail.smtp.socketFactory.class”,socketFactoryClass);
                  }
                  if(!””.equals(fallback)) {
                  props.put(“mail.smtp.socketFactory.fallback”, fallback);
                  }

                  try
                  {
                  Session session = Session.getDefaultInstance(props, null);
                  session.setDebug(debug);
                  MimeMessage msg = new MimeMessage(session);
                  msg.setText(text);
                  msg.setSubject(subject);
                  msg.setFrom(new InternetAddress(“blr-outlook.ibm.com”));
                  for(int i=0;i<to.length;i++) {
                  msg.addRecipient(Message.RecipientType.TO,
                  new InternetAddress(to[i]));
                  }
                  for(int i=0;i<cc.length;i++) {
                  msg.addRecipient(Message.RecipientType.CC,
                  new InternetAddress(cc[i]));
                  }
                  for(int i=0;i<bcc.length;i++) {
                  msg.addRecipient(Message.RecipientType.BCC,
                  new InternetAddress(bcc[i]));
                  }
                  msg.saveChanges();
                  Transport transport = session.getTransport("smtp");
                  transport.connect(host, userName, passWord);
                  transport.sendMessage(msg, msg.getAllRecipients());
                  transport.close();
                  return true;
                  }
                  catch (Exception mex)
                  {
                  return false;
                  }
                  }

                  }

                    • Kapeesh Gupta says

                      Hi,
                      I changed this,code is perfectly run but message does not send email ids.Debug is below here.

                      Thanks

                      DEBUG: setDebug: JavaMail version 1.5.1
                      DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
                      DEBUG SMTP: useEhlo true, useAuth true
                      DEBUG SMTP: trying to connect to host “host”, port 25, isSSL false
                      BUILD SUCCESSFUL (total time: 2 seconds)

                    • says

                      In your catch block, before returning false, plz print/log the error as well.

                      catch (Exception mex)
                      {
                      mex.printStackTrace(); //OR Log it
                      return false;
                      }

                      It will show you why mail is not sent.

  3. pavankumar says

    Hi Lokesh,

    I have been facing an issue with javamail sending a mail from gmail. Actually i need to send it from an smtp server starting with 10.x.x.x using port 25. My Environment is jdk 1.7/windows7 32bit/javamail 1.4.1.

    Sample Code

    String to = "foo@bar.com";//change accordingly
    
            // Sender's email ID needs to be mentioned
            String from = "example@gmail.com";//change accordingly
            
    
            // Assuming you are sending email through relay.jangosmtp.net
            String host = "10.x.x.x";
    
            Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.port", "25");
            props.put("mail.debug","true");
    
            // Get the Session object.
            Session session = Session.getInstance(props,
                    new javax.mail.Authenticator() {
                        protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(username, 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.setRecipients(Message.RecipientType.TO,
                        InternetAddress.parse(to));
    
                // Set Subject: header field
                message.setSubject("Testing Subject");
    
                // Now set the actual message
                message.setText("Hello,");
    
                // Send message
                Transport.send(message);
    
                System.out.println("Sent message successfully....");
    
            } catch (MessagingException e) {
                throw new RuntimeException(e);
            }
        }
    

    java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: 10.x.x.x, port: 25;
    nested exception is:
    java.net.SocketException: Permission denied: connect
    at
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
    at org.testng.TestRunner.privateRun(TestRunner.java:767)
    at org.testng.TestRunner.run(TestRunner.java:617)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:348)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:343)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:305)
    at org.testng.SuiteRunner.run(SuiteRunner.java:254)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
    at org.testng.TestNG.run(TestNG.java:1057)
    at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
    at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:125)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
    Caused by: javax.mail.MessagingException: Could not connect to SMTP host: 10.x.x.x, port: 25;
    nested exception is:
    java.net.SocketException: Permission denied: connect
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1391)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:412)
    at javax.mail.Service.connect(Service.java:310)
    at javax.mail.Service.connect(Service.java:169)
    at javax.mail.Service.connect(Service.java:118)
    at javax.mail.Transport.send0(Transport.java:188)
    at javax.mail.Transport.send(Transport.java:118)
    at
    … 30 more
    Caused by: java.net.SocketException: Permission denied: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:337)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:198)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:180)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
    at java.net.Socket.connect(Socket.java:579)
    at java.net.Socket.connect(Socket.java:528)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:233)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1359)
    … 37 more

    Remedies Taken:
    – I have unchecked ipv6 in Network and connections.
    – i have added preferipv4stack property also not worked.
    Notes:
    when i have used smtp.gmail.com as host and port as 587 it is working fine. but my task is to send a mail through 10.x.x.x smtp server.
    Please help me Lokesh.
    Thanks in advance.

  4. shikhar says

    Exception in thread “main” com.sun.mail.util.MailConnectException: Couldn’t connect to host, port: smtp.gmail.com, 586; timeout -1;
    nested exception is:
    java.net.ConnectException: Connection refused

    How to resolve this problem..plaese help!!!

  5. says

    hello sir,,,

    I am getting this error…how can I get rid of it…
    pls help me on this…

    I used both 468 and 586 ports…but the error is same…
    ————————————————————————————–
    Exception in thread “main” javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 586;
    nested exception is:
    java.net.ConnectException: Connection timed out: connect
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1961)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
    at javax.mail.Service.connect(Service.java:295)
    at javax.mail.Service.connect(Service.java:176)
    at one.Chjhkj.sendEmail(Chjhkj.java:69)
    at one.Chjhkj.main(Chjhkj.java:22)
    Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(Unknown Source)
    at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:321)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:237)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1927)
    … 5 more
    ————————————————————————————–

  6. says

    hey when i copy paste this code and change the userid and password in netbeans i am getting following exception please help me out….
    Exception in thread “main” javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 586;
    nested exception is:
    java.net.ConnectException: Connection timed out: connect
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1934)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:638)
    at javax.mail.Service.connect(Service.java:295)
    at javax.mail.Service.connect(Service.java:176)
    at JavaEmail.sendEmail(JavaEmail.java:67)
    at JavaEmail.main(JavaEmail.java:20)
    Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
    at java.net.Socket.connect(Socket.java:529)
    at java.net.Socket.connect(Socket.java:478)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:288)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:231)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1900)
    … 5 more

    • says

      Manjeet, Can you please tell me the exact error [stack trace].. FYI: above program runs fine on my home network.
      Also, please ensure two things before running this program.
      1) You are not behind any firewall. [Most corporate networks have them. e.g. in offices]
      2) Put correct credentials here: [i.e. your email and password]

      String fromUser = “user-email@gmail.com”;
      String fromUserEmailPassword = “*******”;

Leave a Reply

Your email address will not be published. Required fields are marked *


eight × 8 =