JavaMail API – Sending email via Gmail SMTP example

email icon

In this article, we will show you how to send an email via Gmail SMTP server.

To send email in Java, we need JavaMail

pom.xml

	<dependency>
		<groupId>com.sun.mail</groupId>
		<artifactId>javax.mail</artifactId>
		<version>1.6.2</version>
	</dependency>

1. Gmail SMTP via TLS


SMTP = smtp.gmail.com 
Port = 587
SendEmailTLS.java

package com.mkyong;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class SendEmailTLS {

    public static void main(String[] args) {

        final String username = "[email protected]";
        final String password = "password";

        Properties prop = new Properties();
		prop.put("mail.smtp.host", "smtp.gmail.com");
        prop.put("mail.smtp.port", "587");
        prop.put("mail.smtp.auth", "true");
        prop.put("mail.smtp.starttls.enable", "true"); //TLS
        
        Session session = Session.getInstance(prop,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("[email protected]"));
            message.setRecipients(
                    Message.RecipientType.TO,
                    InternetAddress.parse("[email protected], [email protected]")
            );
            message.setSubject("Testing Gmail TLS");
            message.setText("Dear Mail Crawler,"
                    + "\n\n Please do not spam my email!");

            Transport.send(message);

            System.out.println("Done");

        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

}

2. Gmail via SSL

2.1 The logic is the same, just pass in different properties values.


SMTP = smtp.gmail.com 
Port = 465
SendEmailSSL.java

package com.mkyong;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class SendEmailSSL {

    public static void main(String[] args) {

        final String username = "[email protected]";
        final String password = "password";

        Properties prop = new Properties();
		prop.put("mail.smtp.host", "smtp.gmail.com");
        prop.put("mail.smtp.port", "465");
        prop.put("mail.smtp.auth", "true");
        prop.put("mail.smtp.socketFactory.port", "465");
        prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        
        Session session = Session.getInstance(prop,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("[email protected]"));
            message.setRecipients(
                    Message.RecipientType.TO,
                    InternetAddress.parse("[email protected], [email protected]")
            );
            message.setSubject("Testing Gmail SSL");
            message.setText("Dear Mail Crawler,"
                    + "\n\n Please do not spam my email!");

            Transport.send(message);

            System.out.println("Done");

        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

}

3. Application-specific password required

3.1 If 2-Step verification is ON. We will hits the following error message :


Caused by: javax.mail.AuthenticationFailedException: 534-5.7.9 Application-specific password required. Learn more at
534 5.7.9  https://support.google.com/mail/?p=InvalidSecondFactor - gsmtp

	at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:965)
	at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:876)
	at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:780)
	at javax.mail.Service.connect(Service.java:388)
	at javax.mail.Service.connect(Service.java:246)
	at javax.mail.Service.connect(Service.java:195)
	at javax.mail.Transport.send0(Transport.java:254)
	at javax.mail.Transport.send(Transport.java:124)
	at com.mkyong.calculator.SendEmail.main(SendEmail.java:41)

3.2 To fix it, follow this guide to create an App Password

URL : https://support.google.com/accounts/answer/185833?p=InvalidSecondFactor

app password

URL : https://myaccount.google.com/security

No difference in code, just puts the newly generated app password instead.

SendEmail.java

package com.mkyong;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class SendEmail {

    public static void main(String[] args) {

        final String username = "[email protected]";
        final String password = "puts your app password here"; // update here

		// same code...
    }

}
java.net.UnknownHostException: smtp.gmail.com
Make sure firewall or proxy server didn’t block this smtp.gmail.com

References

463 comments on “JavaMail API – Sending email via Gmail SMTP example

  1. I tried using TLS but it is giving me authentication error.

    Caused by: javax.mail.AuthenticationFailedException: Error authenticating with server
    at org.apache.geronimo.javamail.transport.smtp.SMTPConnection.protocolConnect(SMTPConnection.java:157)
    at org.apache.geronimo.javamail.transport.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:165)
    at javax.mail.Service.connect(Service.java:388)
    at javax.mail.Service.connect(Service.java:246)
    at javax.mail.Service.connect(Service.java:195)
    at javax.mail.Transport.send0(Transport.java:254)
    at javax.mail.Transport.send(Transport.java:124)

    Reply
  2. I am getting following error

    javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate)

    Reply
  3. I met this bug please help me!
    Error: Unable to initialize main class javaapplication23.JavaApplication23
    Caused by: java.lang.NoClassDefFoundError: javax/mail/MessagingException
    C:\Users\HA NGUYEN\AppData\Local\NetBeans\Cache\12.3\executor-snippets\run.xml:111: The following error occurred while executing this line:
    C:\Users\HA NGUYEN\AppData\Local\NetBeans\Cache\12.3\executor-snippets\run.xml:68: Java returned: 1
    BUILD FAILED (total time: 0 seconds)

    Reply
  4. I got email from Google says: February 15, 2021 – Access to LSAs will be turned off for all G Suite accounts.

    I have to turn on LSA, and then connect Gmail SMTP server smtp.gmail.com for sending email from JAVA program using JavaMail.

    Question: will this Google’s change make “connect Gmail SMTP server smtp.gmail.com using JavaMail” impossible? and we hav eto change to use Gmail API for just send an email? Thanks!

    Reply
  5. I used your code in for a test. I have the dependency in the pom.xml, so I ran it from Intellij IDE, it worked well. But after I created the jar file, then all the dependency classes were not included inside the jar file. It did not happen to the other dependencies. Do you have any idea why the dependency classes not included?

    thank you,

    Reply
  6. Is there any way with which I will not be required to save the password in the backend? Or at least make it more secure if not remove it from the code?

    Reply
  7. Still works on 2020-May-25. I had to create the application password to get connected. If you haven’t made the application password yet and you are having trouble, check your application email [whatever account is attached to the ‘username’ getting passed into new PasswordAuthentication()], you might have a polite email from google that you might be getting hacking attempts with instructions on how to make the application password. You may need to turn on two-factor authentication to be able to generate one.

    Hope this helps!

    Reply
  8. On Avast configuration Mail Shield disabling “Scan Outbound emails (SMTP)” , allowed me to have It working.

    Reply
  9. thanks for your code
    Can you please tell how to add attachments also in mail(with code) in sendmailSSL

    Reply
  10. thanks for your code
    Can you please tell how to add attachments also in mail(with code) in sendmailSSL

    Reply
  11. Thanks a lot!!! it solved my problem

    Reply
  12. Hi mkyong,

    I get error javax.mail.MassagingException: can’t find local email address.

    Please give suggestions for this ASAP.

    Reply
  13. Thanks a lot Mkyong 🙂 ..Solution for “Caused by: javax.mail.AuthenticationFailedException: 534-5.7.9 Application-specific password required.” works for me.

    Reply
  14. When I deploy it project to sever it produces the following message “The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.”. why? and how i can solve the problem even though i implement SpringBootServletInitializer in Main class.

    Reply
  15. It was exactly what I needed. Thank you so much!

    Reply
  16. I get the following error here: Transport.send(message);

    Caused by: java.lang.NoClassDefFoundError: sun/security/ssl/EllipticCurvesExtension
    at sun.security.ssl.Handshaker.getActiveProtocols(Handshaker.java:793)
    at sun.security.ssl.Handshaker.activate(Handshaker.java:549)
    at sun.security.ssl.SSLSocketImpl.kickstartHandshake(SSLSocketImpl.java:1492)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1361)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1413)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1397)
    at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:620)
    at com.sun.mail.util.SocketFetcher.startTLS(SocketFetcher.java:547)
    at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:2150)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:752)
    at javax.mail.Service.connect(Service.java:388)
    at javax.mail.Service.connect(Service.java:246)
    at javax.mail.Service.connect(Service.java:195)
    at javax.mail.Transport.send0(Transport.java:254)
    at javax.mail.Transport.send(Transport.java:124)

    Reply
  17. but in case of sending mail through jsp code these is not running , javax.mail.Session field create error whats the reason for it.

    Reply
  18. Can you introduce about send mail with RTF? I’ve tried to add content as text/rtf, but It didn’t work

    Reply
  19. hi I am getting the error :–javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
    nested exception is:
    java.net.ConnectException: Connection timed out: connect

    Reply
  20. hi there, i’ve tried some codes including the first one this page, but it happens that my anti virus is blocking the sending. Is there a way to bypass the anti virus check, without disabling it? Some other ways of sending mail through Java? Thanks in advance

    Exception:
    Exception in thread “main” java.lang.RuntimeException: javax.mail.MessagingException: Can’t send command to SMTP host;
    nested exception is:
    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at newpackage.SendMailTLS.main(SendMailTLS.java:58)
    Caused by: javax.mail.MessagingException: Can’t send command to SMTP host;

    Reply
  21. Please help me !!!

    Exception in thread “main” java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger
    at javax.mail.Session.initLogger(Session.java:227)
    at javax.mail.Session.(Session.java:212)
    at javax.mail.Session.getDefaultInstance(Session.java:315)
    at test.SendMail.main(SendMail.java:25)
    Caused by: java.lang.ClassNotFoundException: com.sun.mail.util.MailLogger
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    … 4 more

    —–> how to fix it

    Reply
  22. The TLS connection worked like a charm for a long time for me, but now I got a javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first.

    The solution was to add props.put(“mail.smtp.EnableSSL.enable”, “true”);

    Reply
  23. javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
    nested exception is:
    java.net.ConnectException: Connection timed out: connect

    i don’t know why..

    Reply
  24. Hi…I have java SE, Where may I download javaee.jar and mail.jar? Also the package com.mkyong.common… Thanks a lot..Wald

    Reply
  25. Here how can We check invalid email address([email protected]) before Transport.send(message); I am facing this issue in my production application. Can you give me some idea!

    Reply
  26. I used both version – via TLS and via SSL. Both don’t work!

    Reply
  27. I am getting this kind of error please help on that

    Reply
  28. Exception in thread “main” java.lang.RuntimeException: javax.mail.AuthenticationFailedException: 534-5.7.14 Please log in via your web browser and
    534-5.7.14 then try again.
    534-5.7.14 Learn more at
    534 5.7.14 https://support.google.com/mail/answer/78754 y66sm6467856pfa.54 – gsmtp

    at com.jack.javaScrapper.SendMailSSL.main(SendMailSSL.java:44)
    Caused by: javax.mail.AuthenticationFailedException: 534-5.7.14 Please log in via your web browser and
    534-5.7.14 then try again.
    534-5.7.14 Learn more at
    534 5.7.14 https://support.google.com/mail/answer/78754 y66sm6467856pfa.54 – gsmtp

    at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:809)
    at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:752)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:669)
    at javax.mail.Service.connect(Service.java:317)
    at javax.mail.Service.connect(Service.java:176)
    at javax.mail.Service.connect(Service.java:125)
    at javax.mail.Transport.send0(Transport.java:194)
    at javax.mail.Transport.send(Transport.java:124)
    at com.jack.javaScrapper.SendMailSSL.main(SendMailSSL.java:39)

    Reply
  29. Can’tru showing this error please help me

    run:
    Exception in thread “main” java.lang.RuntimeException: javax.mail.MessagingException: Could not convert socket to TLS;
    nested exception is:
    javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
    at src.SendMailTLS.main(SendMailTLS.java:54)
    Caused by: javax.mail.MessagingException: Could not convert socket to TLS;
    nested exception is:
    javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
    at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1918)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:652)
    at javax.mail.Service.connect(Service.java:317)
    at javax.mail.Service.connect(Service.java:176)
    at javax.mail.Service.connect(Service.java:125)
    at javax.mail.Transport.send0(Transport.java:194)
    at javax.mail.Transport.send(Transport.java:124)
    at src.SendMailTLS.main(SendMailTLS.java:49)
    Caused by: javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:992)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387)
    at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:548)
    at com.sun.mail.util.SocketFetcher.startTLS(SocketFetcher.java:485)
    at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1913)
    … 7 more
    Caused by: java.io.EOFException: SSL peer shut down incorrectly
    at sun.security.ssl.InputRecord.read(InputRecord.java:505)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973)
    … 13 more
    Java Result: 1
    BUILD SUCCESSFUL (total time: 27 seconds)

    Reply
  30. Couldn’t connect to host, port: 127.0.0.1, 25; timeout -1

    Reply
  31. Hi dear:
    I have to use TLS and got this exception:

    Please help me.

    javax.mail.MessagingException: Could not convert socket to TLS;
    nested exception is:
    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1907)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:666)
    at javax.mail.Service.connect(Service.java:317)
    at javax.mail.Service.connect(Service.java:176)
    at javax.mail.Service.connect(Service.java:125)
    at javax.mail.Transport.send0(Transport.java:194)
    at javax.mail.Transport.send(Transport.java:124)
    at com.osict.ems.client.userinterface.utils.SendEmail.sendEmail(SendEmail.java:77)
    at com.osict.ems.client.userinterface.form.notification.EmailForm.apply_ButtonActionPerformed(EmailForm.java:412)
    at com.osict.ems.client.userinterface.form.notification.EmailForm.lambda$initComponents$2(EmailForm.java:162)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6533)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6298)
    at java.awt.Container.processEvent(Container.java:2236)
    at java.awt.Component.dispatchEventImpl(Component.java:4889)
    at java.awt.Container.dispatchEventImpl(Container.java:2294)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
    at java.awt.Container.dispatchEventImpl(Container.java:2280)
    at java.awt.Window.dispatchEventImpl(Window.java:2746)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
    Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:296)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1514)
    at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
    at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1026)
    at sun.security.ssl.Handshaker.process_record(Handshaker.java:961)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387)
    at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:549)
    at com.sun.mail.util.SocketFetcher.startTLS(SocketFetcher.java:486)
    at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1902)
    … 45 more
    Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
    at sun.security.validator.Validator.validate(Validator.java:260)
    at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1496)
    … 55 more
    Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
    … 61 more

    Reply
  32. This was very helpful as a starting point, but it would be nice if you could show an example of using OAuth to connect to the Google SMTP server as well.

    Reply
  33. how to send the link along with the above message please tell

    Reply
  34. I got this error when try to send an email:

    javax.mail.MessagingException: Can’t send command to SMTP host;
    nested exception is:
    javax.net.ssl.SSLHandshakeException: com.ibm.jsse2.util.m: PKIX path building failed: java.security.cert.CertPathBuilderException: PKIXCertPathBuilderImpl could not build a valid CertPath.; internal cause is:
    java.security.cert.CertPathValidatorException: The certificate issued by CN=GeoTrust Primary Certification Authority, O=GeoTrust Inc., C=US is not trusted; internal cause is:
    java.security.cert.CertPathValidatorException: Certificate chaining error

    Plz help me!

    Reply
    1. Hi Even i am facing this issue. Which version of JDK you are using

      Reply
  35. How can I secure my password while using the above method?
    As I know, it is not safe to use hard coded password in the app.

    Reply
  36. java.lang.RuntimeException: javax.mail.SendFailedException: Sending failed;
    nested exception is:
    javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first. r88sm144300941pfe.93 – gsmtp

    at Main.sendMail2(Main.java:57)
    at Main.main(Main.java:17)
    Caused by: javax.mail.SendFailedException: Sending failed;

    Reply
  37. Thanks you so much bro
    its working

    tell me how to send multiple email id’s bro

    Reply
  38. hello
    if I want to send multiple emails to different users simultaneously, are feasible these options?, because I see creates a new instance for each mail, which would make very slow execution of a program

    Reply
  39. am getting this error:
    javax.mail.AuthenticationFailedException: 534-5.7.14 Please log in via your web browser and
    534-5.7.14 then try again.
    534-5.7.14 Learn more at
    534 5.7.14 https://support.google.com/mail/answer/78754 i8sm12193467pao.26 – gsmtp

    at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:826)
    at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:761)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:685)
    at javax.mail.Service.connect(Service.java:317)
    at javax.mail.Service.connect(Service.java:176)
    at javax.mail.Service.connect(Service.java:125)
    at javax.mail.Transport.send0(Transport.java:194)
    at javax.mail.Transport.send(Transport.java:124)
    at com.mail.SendMail.main(SendMail.java:50)

    Reply
  40. i get this error….please help me…

    sending failed!

    Exception in thread “main” java.lang.RuntimeException: javax.mail.SendFailedException: Sending failed;

    nested exception is:

    class javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first. z4sm1429241par.6 – gsmtp

    at javagmailsendexample.Main.main(Main.java:79)

    Caused by: javax.mail.SendFailedException: Sending failed;

    nested exception is:

    class javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first. z4sm1429241par.6 – gsmtp

    at javax.mail.Transport.send0(Transport.java:218)

    at javax.mail.Transport.send(Transport.java:80)

    at javagmailsendexample.Main.main(Main.java:70)

    Java Result: 1

    BUILD SUCCESSFUL (total time: 2 seconds)

    Reply
  41. The article sound OK, but, you need write more info, same as: Step1, create a Java Class, 2) create a Servlet, 3)….. this article is not for a Begginer. thanks

    Reply
  42. i’m facing error in “protected PasswordAuthentication getPasswordAuthentication() ” and “PasswordAuthentication(username, password)” for above code gmail via TLS

    the errors are

    1)String cannot be converted to char[]

    return new PasswordAuthentication(username, password);

    2)getPasswordAuthentication() in cannot override getPasswordAuthentication() in Authenticator

    protected PasswordAuthentication getPasswordAuthentication() {

    Reply
  43. Exception in thread “main” java.lang.RuntimeException: javax.mail.AuthenticationFailedException: 534-5.7.14 Please log in via your web browser and

    534-5.7.14 then try again.

    534-5.7.14 Learn more at

    534 5.7.14 https://support.google.com/mail/answer/78754 n3sm9365265wix.1 – gsmtp

    at net.typit.emailSpamCannon.SendMailSSL.main(SendMailSSL.java:43)

    Caused by: javax.mail.AuthenticationFailedException: 534-5.7.14 Please log in via your web browser and

    534-5.7.14 then try again.

    534-5.7.14 Learn more at

    534 5.7.14 https://support.google.com/mail/answer/78754 n3sm9365265wix.1 – gsmtp

    at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:826)

    at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:761)

    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:685)

    at javax.mail.Service.connect(Service.java:317)

    at javax.mail.Service.connect(Service.java:176)

    at javax.mail.Service.connect(Service.java:125)

    at javax.mail.Transport.send0(Transport.java:194)

    at javax.mail.Transport.send(Transport.java:124)

    at net.typit.emailSpamCannon.SendMailSSL.main(SendMailSSL.java:38)

    Reply
    1. Hi, I am getting the same error. Please help on how this issue got resolved.

      Reply
  44. I’m very new to this JavaMail API, since when ran the program of TLS mailer, it given me the exception, how can I resolve this, please suggest me..

    Exception in thread “main” java.lang.RuntimeException: javax.mail.SendFailedException: Sending failed;
    nested exception is:
    javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first. ck4sm8629922pbc.67 – gsmtp

    at com.mailer.tls.TLSMailer.main(TLSMailer.java:47)
    Caused by: javax.mail.SendFailedException: Sending failed;
    nested exception is:
    javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first. ck4sm8629922pbc.67 – gsmtp

    at javax.mail.Transport.send0(Transport.java:219)
    at javax.mail.Transport.send(Transport.java:81)
    at com.mailer.tls.TLSMailer.main(TLSMailer.java:42)

    Reply
  45. I cannot found the .. javaee.jar 🙁
    Please somebody help me 🙁

    Reply
  46. It doesn’t work for me. It sticks on Transport.send(message). Could someone help me?

    Reply
      1. I have the same issue….
        com.sun.mail.util.MailConnectException: Couldn’t connect to host, port: smtp.gmail.com, 587; timeout -1;
        nested exception is:
        java.net.ConnectException: Connection refused: connect
        at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2209)
        at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:740)
        at javax.mail.Service.connect(Service.java:388)
        … the errors log goes on

        Reply
        1. I copy and pasted the above code and changed the email address to mine, and the password to my password

          Reply
        2. me too the same probleme
          how can i Make sure firewall or proxy server didn’t block this smtp.gmail.com ???

          Reply
          1. have you found the solution if yes could you tell me how I got the same error

  47. Hi, Do you have sample code for Reading email content with attachment over IMAP protocol. If so please share with me.

    Reply
  48. Hello Sir,I’m finding the below exception when im sending email out of eclipse.

    javax.mail.MessagingException: Exception reading response;
    nested exception is:
    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1764)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1523)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:453)
    at javax.mail.Service.connect(Service.java:313)
    at javax.mail.Service.connect(Service.java:172)
    at javax.mail.Service.connect(Service.java:121)
    at javax.mail.Transport.send0(Transport.java:190)
    at javax.mail.Transport.send(Transport.java:120)
    at com.airbus.fep.datatransfer.util.EmailSender.sendSSLMessage(EmailSender.java:99)
    at com.airbus.fep.datatransfer.sftp.SFTPExecutor.sendNotificationEmail(SFTPExecutor.java:208)
    at com.airbus.fep.datatransfer.sftp.SFTPExecutor.processFileTransferCancelledforOverwrite(SFTPExecutor.java:539)
    at com.airbus.fep.datatransfer.sftp.SFTPExecutor.processFileTransferOverWrite(SFTPExecutor.java:619)
    at com.airbus.fep.datatransfer.sftp.SFTPExecutor.run(SFTPExecutor.java:164)
    at java.util.TimerThread.mainLoop(Unknown Source)
    at java.util.TimerThread.run(Unknown Source)
    Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(Unknown Source)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(Unknown Source)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(Unknown Source)
    at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Unknown Source)
    at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readDataRecord(Unknown Source)
    at com.sun.net.ssl.internal.ssl.AppInputStream.read(Unknown Source)
    at com.sun.mail.util.TraceInputStream.read(TraceInputStream.java:106)
    at java.io.BufferedInputStream.fill(Unknown Source)
    at java.io.BufferedInputStream.read(Unknown Source)
    at com.sun.mail.util.LineInputStream.readLine(LineInputStream.java:84)
    at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1742)
    … 14 more
    Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(Unknown Source)
    at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
    at sun.security.validator.Validator.validate(Unknown Source)
    at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.validate(Unknown Source)
    at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
    at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
    … 27 more
    Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)
    at java.security.cert.CertPathBuilder.build(Unknown Source)
    … 33 more

    Reply
  49. I am getting following problem and code is not running :

    javax.mail.MessagingException: Could not convert socket to TLS;

    nested exception is:

    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

    at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1907)

    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:666)

    at javax.mail.Service.connect(Service.java:317)

    at javax.mail.Service.connect(Service.java:176)

    at javax.mail.Service.connect(Service.java:125)

    at javax.mail.Transport.send0(Transport.java:194)

    at javax.mail.Transport.send(Transport.java:124)

    at module.Mail.main(Mail.java:42)

    Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

    at sun.security.ssl.Alerts.getSSLException(Unknown Source)

    at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)

    at sun.security.ssl.Handshaker.fatalSE(Unknown Source)

    at sun.security.ssl.Handshaker.fatalSE(Unknown Source)

    at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)

    at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)

    at sun.security.ssl.Handshaker.processLoop(Unknown Source)

    at sun.security.ssl.Handshaker.process_record(Unknown Source)

    at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)

    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)

    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)

    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)

    at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:549)

    at com.sun.mail.util.SocketFetcher.startTLS(SocketFetcher.java:486)

    at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1902)

    … 7 more

    Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

    at sun.security.validator.PKIXValidator.doBuild(Unknown Source)

    at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)

    at sun.security.validator.Validator.validate(Unknown Source)

    at sun.security.ssl.X509TrustManagerImpl.validate(Unknown Source)

    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(Unknown Source)

    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)

    … 18 more

    Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)

    at java.security.cert.CertPathBuilder.build(Unknown Source)

    … 24 more

    Reply
    1. now i am getting same exception in production ….. any Solution for this ??

      Reply
  50. Thank u very much! it works very fine with the another app security access settings on gmail.

    Reply
  51. Hi i am getting connection error using port number so can anybody help me regarding this.

    Thanks
    Sailendra

    Reply
  52. 10-19 01:24:43.304: E/NativeCrypto(16749): ssl=0x63db6678 cert_verify_callback x509_store_ctx=0x5fb5b938 arg=0x0

    10-19 01:24:43.304: E/NativeCrypto(16749): ssl=0x63db6678 cert_verify_callback calling verifyCertificateChain authMethod=ECDHE_RSA

    10-19 01:24:45.003: E/MailApp(16749): Could not send email

    10-19 01:24:45.003: E/MailApp(16749): javax.mail.AuthenticationFailedException

    10-19 01:24:45.003: E/MailApp(16749): at javax.mail.Service.connect(Service.java:319)

    10-19 01:24:45.003: E/MailApp(16749): at javax.mail.Service.connect(Service.java:169)

    10-19 01:24:45.003: E/MailApp(16749): at javax.mail.Service.connect(Service.java:118)

    10-19 01:24:45.003: E/MailApp(16749): at javax.mail.Transport.send0(Transport.java:188)

    10-19 01:24:45.003: E/MailApp(16749): at javax.mail.Transport.send(Transport.java:118)

    10-19 01:24:45.003: E/MailApp(16749): at com.example.fetchusetaccount.Mail.send(Mail.java:121)

    10-19 01:24:45.003: E/MailApp(16749): at com.example.fetchusetaccount.MainActivity$email_1.doInBackground(MainActivity.java:100)

    10-19 01:24:45.003: E/MailApp(16749): at com.example.fetchusetaccount.MainActivity$email_1.doInBackground(MainActivity.java:1)

    10-19 01:24:45.003: E/MailApp(16749): at android.os.AsyncTask$2.call(AsyncTask.java:288)

    10-19 01:24:45.003: E/MailApp(16749): at java.util.concurrent.FutureTask.run(FutureTask.java:237)

    10-19 01:24:45.003: E/MailApp(16749): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)

    10-19 01:24:45.003: E/MailApp(16749): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)

    10-19 01:24:45.003: E/MailApp(16749): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)

    10-19 01:24:45.003: E/MailApp(16749): at java.lang.Thread.run(Thread.java:841)

    Reply
  53. Thanks for the code, this works perfectly, thanks for sharing.

    Reply
  54. Facing issue with the code. It gives below given exception. Please suggest solution for the same :

    javax.mail.AuthenticationFailedException
    at javax.mail.Service.connect(Service.java:306)
    at javax.mail.Service.connect(Service.java:156)
    at javax.mail.Service.connect(Service.java:105)
    at javax.mail.Transport.send0(Transport.java:168)
    at javax.mail.Transport.send(Transport.java:98)
    at com.bullbeardevice.util.MailSender.sendMail(MailSender.java:65)

    Reply
  55. Hello…
    I have used both the codes but each time i’m getting Exception saying…

    Exception in thread “main” java.lang.RuntimeException: javax.mail.AuthenticationFailedException: failed to connect at com.mkyong.common.SendMailTLS.main(SendMailTLS.java:44)
    Caused by: javax.mail.AuthenticationFailedException: failed to connect
    at javax.mail.Service.connect(Service.java:322)
    at javax.mail.Service.connect(Service.java:172)
    at javax.mail.Service.connect(Service.java:121)
    at javax.mail.Transport.send0(Transport.java:190)
    at javax.mail.Transport.send(Transport.java:120)
    at com.mkyong.common.SendMailTLS.main(SendMailTLS.java:41)

    what to do..? any suggestions..?

    Thanks in Advance…

    Reply
  56. Exception in thread “main” java.lang.RuntimeException: javax.mail.AuthenticationFailedException
    at emailproject.Emailproject.main(Emailproject.java:53)
    Caused by: javax.mail.AuthenticationFailedException
    at javax.mail.Service.connect(Service.java:319)
    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 emailproject.Emailproject.main(Emailproject.java:48)

    Reply
    1. How did you solved this Problem…? I’m getting the same…

      Reply
  57. I want to send a file and not a message how u can help me plz ???

    Reply
  58. i’m sending automatic email from my app but i need two jars: mailapi.jar and smtp.jar My question is are these jar files really necessary? Here is my code (actually working):

    try {

    Properties props = System.getProperties();

    props.put(“mail.transport.protocol”,”smtp”);

    props.put(“mail.smtp.starttls.enable”,”false”);

    props.put(“mail.smtp.host”,host);

    props.put(“mail.smtp.auth”,”true”);

    props.put(“mail.smtp.user”,userid);

    props.put(“mail.smtp.password”,password);

    props.put(“mail.smtp.from”,userid);

    Session session = Session.getInstance(props, new SMTPAuthenticator(props));

    MimeMessage message = new MimeMessage(session);

    InternetAddress fromAddress = null;

    InternetAddress toAddress = null;

    try {

    fromAddress = new InternetAddress(from);

    toAddress = new InternetAddress(to);

    } catch (AddressException e) {

    e.printStackTrace();

    }

    message.setFrom(fromAddress);

    message.setRecipient(RecipientType.TO, toAddress);

    message.setSubject(subject);

    message.setText(text);

    message.setSentDate(new Date());

    // SMTPSSLTransport transport

    // =(SMTPSSLTransport)session.getTransport(“smtps”);

    Transport transport = session.getTransport(“smtp”);

    transport.connect(host, userid, password);

    transport.sendMessage(message, message.getAllRecipients());

    transport.close();

    } catch (MessagingException e) {

    e.printStackTrace();

    }

    Reply
    1. SMTPAuthenticator on the Session session line is underlined in red by eclipse. Any ideas why? Not an import issue

      Reply
    2. i was facing the same problem solve it by just trying another email address
      and its work fine…….

      Reply
  59. Thank you very much! It is really working and it is well explained! Thanks again and keep up the good work!

    Reply
  60. Hi yong..
    thanks for the code…

    I am facing a unexpected issue at my server, above Code is working perfectly from my windows machine. Now i have deployed that code on Ubuntu server. I am not able to send email from there.
    I am getting following error, please suggest me what to do now…

    [java] java.lang.RuntimeException: javax.mail.AuthenticationFailedException
    [java] at com.icycllic.common.EmailService.sendEmail(EmailService.java:75)
    [java] at com.icycllic.common.EmailService.setMessageAndSendEmail(EmailService.java:39)
    [java] at com.icycllic.dao.AmazonServiceDao.generateXml(AmazonServiceDao.java:244)
    [java] at com.icycllic.manager.AmazonService.main(AmazonService.java:17)
    [java] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    [java] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    [java] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    [java] at java.lang.reflect.Method.invoke(Method.java:597)
    [java] at org.apache.tools.ant.taskdefs.ExecuteJava.run(ExecuteJava.java:217)

    [java] Caused by: javax.mail.AuthenticationFailedException
    [java] at javax.mail.Service.connect(Service.java:267)
    [java] at javax.mail.Service.connect(Service.java:137)
    [java] at javax.mail.Service.connect(Service.java:86)
    [java] at javax.mail.Transport.send0(Transport.java:150)
    [java] at javax.mail.Transport.send(Transport.java:80)
    [java] at com.icycllic.common.EmailService.sendEmail(EmailService.java:70)
    [java] … 29 more

    Reply
  61. following exception occured.
    Exception in thread “main” java.lang.RuntimeException: javax.mail.SendFailedException: Sending failed;
    nested exception is:
    class javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
    nested exception is:
    java.net.ConnectException: Connection refused: connect
    at com.cts.email.SendEmail.createEmailMessage(SendEmail.java:62)
    at com.cts.email.SendEmail.main(SendEmail.java:21)
    Caused by: javax.mail.SendFailedException: Sending failed;
    nested exception is:
    class javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
    nested exception is:
    java.net.ConnectException: Connection refused: connect
    at javax.mail.Transport.send0(Transport.java:218)
    at javax.mail.Transport.send(Transport.java:80)
    at com.cts.email.SendEmail.createEmailMessage(SendEmail.java:55)
    … 1 more

    Reply
  62. You are just awesome dude. You solved my lots of lots of problem. Big fan of yours. Thanks.

    Reply
  63. i get this error 🙁

    Exception in thread “main” java.lang.NoClassDefFoundError: SendMailSSL (

    me: com/mkyong/common/SendMailSSL)

    at java.lang.ClassLoader.defineClass1(Native Method)

    at java.lang.ClassLoader.defineClass(Unknown Source)

    at java.security.SecureClassLoader.defineClass(Unknown Source)

    at java.net.URLClassLoader.defineClass(Unknown Source)

    at java.net.URLClassLoader.access$100(Unknown Source)

    at java.net.URLClassLoader$1.run(Unknown Source)

    at java.net.URLClassLoader$1.run(Unknown Source)

    at java.security.AccessController.doPrivileged(Native Method)

    at java.net.URLClassLoader.findClass(Unknown Source)

    at java.lang.ClassLoader.loadClass(Unknown Source)

    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)

    at java.lang.ClassLoader.loadClass(Unknown Source)

    at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)

    Reply
  64. i get an error runtime error “Error: Could not find or load main class SendMailTLS” please help me

    Reply
  65. Hello, I have tried your example in SSL mode. Thank you for the example I always try your examples for my leaning. But I had to disable my Avast Antivirus Mail Shield. I have a question over here is if I want to upload this send email to my webpage, how can I overcome disabling of mail shield. I am very much confused.

    Reply
  66. Why do people insist on doing this by hand?? Just use something like Simple Java Mail, a thin API on top of the javax.mail API, which does this for you:

    https://code.google.com/p/simple-java-mail/

    smtp: new Mailer(“smtp.host.com”, 25, “username”, “password”)
    smtps: new Mailer(“smtp.host.com”, 25, “username”, “password”, TransportStrategy.SMTP_SSL)
    smtps tls: new Mailer(“smtp.host.com”, 25, “username”, “password”, TransportStrategy.SMTP_TLS)

    Reply
  67. Why do people insist on doing this by hand?? Just use something like Simple Java Mail (a thin API on top of the javax.mail API: https://code.google.com/p/simple-java-mail/), which does this for you:

    smtp: new Mailer(“smtp.host.com”, 25, “username”, “password”)
    smtps: new Mailer(“smtp.host.com”, 25, “username”, “password”, TransportStrategy.SMTP_SSL)
    smtps tls: new Mailer(“smtp.host.com”, 25, “username”, “password”, TransportStrategy.SMTP_TLS)

    Reply
  68. Hello,

    Very nicely explained but I need few inputs how to set proxy properties to break through the firewall. I am getting java.net.UnknownHostException: smtp.gmail.com error due to proxy enabled.

    Regards,
    Dibyendu

    Reply
  69. hi facing issues while sending ™ in email content using Email class in java.can you please help me in this

    Reply
  70. hello
    I have an error, I am sending several different senders mail the problem is that when sending a mail to the sender that your email is wrong or there is entered
    short, non-continuous flow sending, how I can fix this? thanks

    com.sun.mail.smtp.SMTPAddressFailedException: 550 5.1.1 .

    Reply
  71. Your SMTP TLS code does not work. I used the same credentials for SMTP SSL and that works:

    Exception in thread “main” java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
    nested exception is:
    java.net.ConnectException: Connection timed out: connect
    at SMTP_TLS.main(SMTP_TLS.java:48)
    Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
    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:317)
    at javax.mail.Service.connect(Service.java:176)
    at javax.mail.Service.connect(Service.java:125)
    at javax.mail.Transport.send0(Transport.java:253)
    at javax.mail.Transport.send(Transport.java:124)
    at SMTP_TLS.main(SMTP_TLS.java:43)
    Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
    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:299)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:234)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1927)
    … 7 more

    Reply
    1. It means the port 587 is disabled in your systems. Check with system administrator to enable that port.

      Reply
  72. Thanks a lot……….
    wow I’ve been looking for such a code since 2 weeks!
    Great job mkyong, you are the best…

    Reply
  73. Great one!!! Works fine.
    But, Here We’ve hard-coded the plain password. So, I want to know how to use encrypted password in the program.

    Could you please tell me?

    Reply
  74. I got this exception how can i handle this Exception : ” PKIX path building failed”

    Reply
  75. Hi all! I have a funny problem: it work perfectly the code using the server of my company….. except for hotmail users that don’t receive my emails.

    Have u solutions?

    Reply
  76. Hi,

    In this, since you are using SMTP server protocol, this can be broken at the network layer when we will be using it in an application. Then how can me make it secure?

    Any suggestions?

    Reply
  77. This is one of the few examples online that actually works, with a good explanation.

    Also, +1 for providing an SSL implementation! Great job.

    Reply
  78. hello
    if I want to send multiple emails to different users simultaneously, are feasible these options?, because I see creates a new instance for each mail, which would make very slow execution of a program

    bye.

    Reply
  79. Working great.Thanks.

    Gmail refuses to send mails again if the created account is new assuming it is a spam account. Using the old account will work.Thanks again.

    Reply
  80. Not sending email and getting following error.
    Could plz help on this.

    Exception in thread “main” java.lang.RuntimeException: javax.mail.MessagingException: Unknown SMTP host: smtp.gmail.com;
    nested exception is:
    java.net.UnknownHostException: smtp.gmail.com
    at view.SendMailTLS.main(SendMailTLS.java:45)
    Caused by: javax.mail.MessagingException: Unknown SMTP host: smtp.gmail.com;
    nested exception is:
    java.net.UnknownHostException: smtp.gmail.com
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1389)
    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 view.SendMailTLS.main(SendMailTLS.java:39)
    Caused by: java.net.UnknownHostException: smtp.gmail.com
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:195)
    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:233)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)

    Reply
    1. Try typing ping smtp.gmail.com in a command window and see if you can reach it. If the ping doesn’t respond something is blocking your connection.

      Reply
  81. Hello,

    thanks for giving the example, it works for me.
    But I need to know, if I want to send an email from outlook instead of gmail yahoo then how to do that.
    Can anybody tell me with clear example.

    Thanks in advance

    Reply
  82. The mail server works once. After that I get the following exception. then i have to restart my glassfish server again to get it work.

    WARNING: StandardWrapperValve[MailServlet]: PWC1406: Servlet.service() for servlet MailServlet threw exception
    java.lang.SecurityException: Access to default session denied
    at javax.mail.Session.getDefaultInstance(Session.java:320)
    at control.MailServlet.processRequest(MailServlet.java:49)
    at control.MailServlet.doPost(MailServlet.java:106)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:688)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:770)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:722)

    Reply
  83. I just wanted to thank you for the great example. I have been trying to figure this out for awhile now. This was a really big help. ^_^

    Reply
  84. Hi, I think I’m getting the same exception both on TSL and SSL, I already ping smtp.gmail.com but its still the same, here’s what I get:

    Exception in thread “main” java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
    nested exception is:
    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at ext.CE.SendMailSSL.main(SendMailSSL.java:45)
    Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
    nested exception is:
    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    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:317)
    at javax.mail.Service.connect(Service.java:176)
    at javax.mail.Service.connect(Service.java:125)
    at javax.mail.Transport.send0(Transport.java:194)
    at javax.mail.Transport.send(Transport.java:124)
    at ext.CE.SendMailSSL.main(SendMailSSL.java:40)
    Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.ssl.Alerts.getSSLException(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
    at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
    at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
    at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
    at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
    at sun.security.ssl.Handshaker.processLoop(Unknown Source)
    at sun.security.ssl.Handshaker.process_record(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:507)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:238)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1900)
    … 7 more
    Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(Unknown Source)
    at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
    at sun.security.validator.Validator.validate(Unknown Source)
    at sun.security.ssl.X509TrustManagerImpl.validate(Unknown Source)
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(Unknown Source)
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
    … 18 more
    Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)
    at java.security.cert.CertPathBuilder.build(Unknown Source)
    … 24 more

    Reply
    1. Try to telnet the smtp host.

      telnet smtp.gmail.com 465

      and see if it’s getting connected from your network. Most probably,this will not work in VPN.

      Thanks mkyong for this code.

      Reply
      1. I am connected to telnet smtp.host.com 465 still i am getting error like that please help as soon as possible thanks….

        Reply
      1. try “mail.host” instead of “smtp.mail.host”

        Reply
  85. To run this example required only one library – mail.jar.
    Thanks for the post!

    Reply
  86. I want to create a form on my website through which user can send email to two OUTLOOK email-ids.
    The form is just like user enters his/her email-id, name, subject, message and send mail to outlook ids.
    The users id an be gmail, yahoo etc. What should be the port number, host etc.

    Reply
  87. Getting below error —>
    Exception in thread “main” java.lang.RuntimeException: javax.mail.AuthenticationFailedException
    at SendMailTLS.main(SendMailTLS.java:46)
    Caused by: javax.mail.AuthenticationFailedException
    at javax.mail.Service.connect(Service.java:319)
    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 SendMailTLS.main(SendMailTLS.java:41)

    Reply
    1. are you solved this problem?i am facing the same problem………

      Reply
        1. yes i done it by just try another email address and its work fine….

          Reply
    2. Hi I am facing same issue please suggest the solution

      Reply
      1. Thank you! I couldn’t resolve it during two days=(
        And changing the settings of gmail help me!

        Reply
        1. What do you mean with: javax.mail.SendFailedException occures ??

          Reply
      2. Thanks a lot Nick, I think this is a very important point which the author should mention….

        Reply
  88. Hello to all my brother.pls i’m new to restful web service and also new in using the new apache TomeePlus .My aim of using restful webservice is to integrate it in my web e-comerce websit.

    FIRST:
    My IDE is Netbeans 7.3.1,
    In my sql ,I built a database called oko which is made up on table with ID,firstname and Lastname, this is just for testing purposes.
    in My netbeans i built a web app called AGAIN
    in thsi AGAIN I built entity beans from my Mysql database,”entity class = Oko.java”
    i built restful web service from entity class “Oko.java”;
    i used glassfish server 3.2.
    when i tested the restful webservice it work pretty well.
    i was very happy with this !!.

    SECOND :
    Now i tried to do thesame thing with my apache TomeePlus server ,
    but it is not working .
    i included “mysql driver jar file ” to TomeePlus /lib,
    i Fololwed the step on FIRST:
    it gave me an error which has kept me one week trying to resolve.

    ERROR :
    SEVERE: Servlet.service() for servlet [ServletAdaptor] in context with path [/AGAIN] threw exception
    java.lang.NullPointerException
    at service.AbstractFacade.findAll(AbstractFacade.java:40)
    at service.OkoFacadeREST.findAll(OkoFacadeREST.java:66)
    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:606)
    at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
    at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
    at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
    at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1480)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1411)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1360)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1350)
    at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:538)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:716)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:724)

    WEB.XML:
    My web.xml file looks like this

    ServletAdaptor
    com.sun.jersey.spi.container.servlet.ServletContainer

    Multiple packages, separated by semicolon(;), can be specified in param-value
    com.sun.jersey.config.property.packages
    service

    com.sun.jersey.api.json.POJOMappingFeature
    true

    1

    ServletAdaptor
    /webresources/*

    30

    CONTEXT.XML:

    My context.xml file looks like this

    PERSISTENCE.XML:

    My persistence .xml file looks like this

    org.eclipse.persistence.jpa.PersistenceProvider
    PAC.Oko
    false

    .Please brothers this has kept me almost a week of nigthless sleep.
    i need your help and support pleas.
    You can also contact me via E-mail :[email protected]
    THANKS FOR YOUR HELP!!

    Reply
  89. Your example works prefect! Thank you very much!
    I already wrote a wrapper class where I just pass source email and password and a sendTo() method with destination mail, subject and message arguments. Also added possibility to choose between TLS and SSL. This is all done based on your example, thank you very much!

    Reply
  90. fantastic code, works very fine, remember all to add mail.jar to your classpath!

    Reply
  91. Maybe it’s just old but doesn’t seem to work at all with either of them just error messages.

    Exception in thread “main” java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
    nested exception is:
    java.net.SocketException: Unrecognized Windows Sockets error: 87: create
    at sendMail.main(sendMail.java:47)
    Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
    nested exception is:
    java.net.SocketException: Unrecognized Windows Sockets error: 87: create
    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:317)
    at javax.mail.Service.connect(Service.java:176)
    at javax.mail.Service.connect(Service.java:125)
    at javax.mail.Transport.send0(Transport.java:194)
    at javax.mail.Transport.send(Transport.java:124)
    at sendMail.main(sendMail.java:42)
    Caused by: java.net.SocketException: Unrecognized Windows Sockets error: 87: create
    at java.net.Socket.createImpl(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)
    … 7 more

    Reply
    1. I think you have a firewall problem, are you sure port 587 is open for outside connection? Otherwise, first try with a mail client like Thunderbird and test whether it works or not (basically it’s the same).

      Reply
    2. Try using port number 465 for smtp connection. If you are using SSL connection use port number 465 and if TSL use port number 587

      Reply
  92. Hello Sir!
    I’ve used your ssl code but i have this exception:

    Exception in thread “main” java.lang.RuntimeException: javax.mail.MessagingException: Exception reading response;
    nested exception is:
    java.net.SocketException: Connection reset
    at com.servlets.SendMailSSL.main(SendMailSSL.java:45)
    Caused by: javax.mail.MessagingException: Exception reading response;
    nested exception is:
    java.net.SocketException: Connection reset
    at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1764)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1523)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:453)
    at javax.mail.Service.connect(Service.java:313)
    at javax.mail.Service.connect(Service.java:172)
    at javax.mail.Service.connect(Service.java:121)
    at javax.mail.Transport.send0(Transport.java:190)
    at javax.mail.Transport.send(Transport.java:120)
    at com.servlets.SendMailSSL.main(SendMailSSL.java:40)
    Caused by: java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at sun.security.ssl.InputRecord.readFully(Unknown Source)
    at sun.security.ssl.InputRecord.read(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.readDataRecord(Unknown Source)
    at sun.security.ssl.AppInputStream.read(Unknown Source)
    at com.sun.mail.util.TraceInputStream.read(TraceInputStream.java:106)
    at java.io.BufferedInputStream.fill(Unknown Source)
    at java.io.BufferedInputStream.read(Unknown Source)
    at com.sun.mail.util.LineInputStream.readLine(LineInputStream.java:84)
    at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1742)
    … 8 more

    please can you help me!

    Reply
  93. Hi, can anyone resolve this problem
    i am running SMTP program.

    package netexmp;

    import java.util.Properties;

    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 SimpleMail {

    public static void main(String[] args) {
    //final String username = “[email protected]”;
    //final String password = “xyz”;

    System.out.println(“hello”);

    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”);
    props.put(“mail.smtp.debug”, “true”);

    Session session = Session.getDefaultInstance(props,
    new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(“[email protected]”,”xyz”);
    }
    });
    session.setDebug(true);
    try {

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(“[email protected]”));
    message.setRecipients(Message.RecipientType.TO,
    InternetAddress.parse(“[email protected]”));
    message.setSubject(“Testing Subject”);
    message.setText(“Dear Mail Crawler,” +
    “\n\n No spam to my email, please!”);

    Transport.send(message);

    System.out.println(“Done”);

    } catch (MessagingException e) {
    e.printStackTrace();
    System.out.println(e);
    throw new RuntimeException(e);
    }
    }
    }

    above program output :
    hello
    DEBUG: setDebug: JavaMail version 1.4.7
    DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
    DEBUG SMTP: useEhlo true, useAuth true
    DEBUG SMTP: useEhlo true, useAuth true
    DEBUG SMTP: trying to connect to host “smtp.gmail.com”, port 465, isSSL false

    It is going in try block but not printing “Done” and taking to much time(around 10 mints).

    But when i am using port” 25 ”

    Output is :
    hello
    DEBUG: setDebug: JavaMail version 1.4.7
    DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
    DEBUG SMTP: useEhlo true, useAuth true
    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 xu10sm58096388pab.3 – gsmtp
    DEBUG SMTP: connected to host “smtp.gmail.com”, port: 25

    EHLO 192.168.1.186
    250-mx.google.com at your service, [122.160.172.136]
    250-SIZE 35882577
    250-8BITMIME
    250-STARTTLS
    250 ENHANCEDSTATUSCODES
    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: use8bit false
    MAIL FROM:
    530 5.7.0 Must issue a STARTTLS command first. xu10sm58096388pab.3 – gsmtp
    DEBUG SMTP: got response code 530, with response: 530 5.7.0 Must issue a STARTTLS command first. xu10sm58096388pab.3 – gsmtp

    RSET
    250 2.1.5 Flushed xu10sm58096388pab.3 – gsmtp
    DEBUG SMTP: MessagingException while sending, THROW:
    com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. xu10sm58096388pab.3 – gsmtp

    at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2108)
    at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1609)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1117)
    at javax.mail.Transport.send0(Transport.java:195)
    at javax.mail.Transport.send(Transport.java:124)
    at netexmp.SimpleMail.main(SimpleMail.java:56)
    QUIT
    221 2.0.0 closing connection xu10sm58096388pab.3 – gsmtp
    com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. xu10sm58096388pab.3 – gsmtp

    at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2108)
    at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1609)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1117)
    at javax.mail.Transport.send0(Transport.java:195)
    com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. xu10sm58096388pab.3 – gsmtp

    at javax.mail.Transport.send(Transport.java:124)
    at netexmp.SimpleMail.main(SimpleMail.java:56)
    Exception in thread “main” java.lang.RuntimeException: com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. xu10sm58096388pab.3 – gsmtp

    at netexmp.SimpleMail.main(SimpleMail.java:63)
    Caused by: com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. xu10sm58096388pab.3 – gsmtp

    at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2108)
    at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1609)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1117)
    at javax.mail.Transport.send0(Transport.java:195)
    at javax.mail.Transport.send(Transport.java:124)
    at netexmp.SimpleMail.main(SimpleMail.java:56)

    Please solve this error.

    Reply
    1. Rajat … did your problem solve?

      I am facing same problem. Please help.

      Reply
  94. 1.Receiving mail
    2.Attach mail
    3.Replay and forwarding

    using java

    Reply
  95. Hi,
    if if anyone is using avast antiverus he should dis-activate it .
    if any one is using gmail, try the port n° 25 .

    good chance for u all.

    Reply
    1. thanks,i tried before but i failed.after installing avast i succeded.

      Reply
  96. Thanks for your help Java mail example but with TLS its not working Showing permission denied .Thanks for All java related help like JSF,Hibernate ,Log4j etc.

    thank u thank u thank u

    Reply
  97. Hi,

    Can i execute this sample program in IBM Java.?

    If not can you tell me how can i make it work in ibm java??

    Its very urgent.

    Thanks
    Shaf

    Reply
  98. Hey, there, that works fine…but what about sending mail to multiple recipients??? please share that too..
    thanks

    Reply
  99. Can you please suggest, how to get rid of these errors? Am I missing anything?

    Exception in thread “main” java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25;
    nested exception is:
    java.net.ConnectException: Connection timed out: connect
    at SendEmail.main(SendEmail.java:47)
    Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25;
    nested exception is:
    java.net.ConnectException: Connection timed out: connect
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1282)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
    at javax.mail.Service.connect(Service.java:297)
    at javax.mail.Service.connect(Service.java:156)
    at javax.mail.Service.connect(Service.java:105)
    at javax.mail.Transport.send0(Transport.java:168)
    at javax.mail.Transport.send(Transport.java:98)
    at SendEmail.main(SendEmail.java:42)
    Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:383)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:245)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:232)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:377)
    at java.net.Socket.connect(Socket.java:539)
    at java.net.Socket.connect(Socket.java:488)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:232)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1250)
    … 7 more

    Reply
  100. I got the following error,

    javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
    nested exception is:
    java.net.ConnectException: connect: Address is invalid on local machine, or port is not valid on remote machine
    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:317)
    at javax.mail.Service.connect(Service.java:176)
    at javax.mail.Service.connect(Service.java:125)
    at javax.mail.Transport.send0(Transport.java:194)
    at javax.mail.Transport.send(Transport.java:124)
    at org.bsnl.wll.sendMail.SendMail.mailReport(SendMail.java:55)
    at org.bsnl.wll.sendMail.SendMail.prepareMailAndSend(SendMail.java:44)
    at org.bsnl.wll.trafficAnalisis.DailyTrafficAnalysis.main(DailyTrafficAnalysis.java:24)
    Caused by: java.net.ConnectException: connect: Address is invalid on local machine, or port is not valid on remote machine
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connect(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)

    I am using a Win 8 machine, java version 1.7.0.17 and java mail 1.4.7

    Can you please help

    Reply
    1. Thanks for neat solution.But
      1. Authorization credential should be used for authentication than how come form field “message.setFrom(new InternetAddress(“[email protected]”));” be different from authentication credentials?Even I kept different credentials in form and authentication,but mail is still sent to the one I mentioned in authentication.What I am missing?
      2.If I am to send a mail with no-reply option,how this can be done?

      Reply
  101. Thanks alot mkyong code works fine…..:)

    Reply
  102. Hi
    I am really thankful to you for posting this. This is wonderful. However, I have a question.

    For SSL, if we use props.put(“mail.smtp.port”, “465”); under a proxy it doesn’t work. Instead, if we use props.put(“mail.smtp.port”, “25”); i.e using port 25 it works fine. What is the difference between these two port numbers and how does proxy affects it?

    Thank you.

    Reply
  103. I have found the problem.

    The dependency for javax.mail needs to be the first in the maven build file. I am using spring and scheduler (using a previous example of MKYONG) and somehow these are interfering with the javax.mail dependency.

    All working fine now.

    Reply
  104. hello Sir How do I configure JavaMail to work through my proxy server?
    i had configured Java Network Connection in Control Panel, but i doesn’t work. can you help me Sir?

    Reply
  105. Tried the code above SendMailTLS using my gmail account and got the following error

    javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
    nested exception is:
    java.net.SocketException: Permission denied: connect

    Any ideas?

    I checked my username and password and all works fine when login to gmail account.

    Reply
  106. I GET THIS EXCEPTION WHEN TRIED TO EXECUTE THE GIVEN CODE……
    IT WORKED FINE IN MY HOME BUT …IN COMPANY I USE A VPN TO CONNECT TO A NETWORK …..WILL THIS HAVE ANY THING TO DO WITH THE EXECEPTION.

    Exception in thread “main” java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
    nested exception is:
    java.net.ConnectException: Connection timed out: connect
    at com.igate.mail.SendEmail.main(SendEmail.java:140)
    Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
    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:317)
    at javax.mail.Service.connect(Service.java:176)
    at javax.mail.Service.connect(Service.java:125)
    at javax.mail.Transport.send0(Transport.java:194)
    at javax.mail.Transport.send(Transport.java:124)
    at com.igate.mail.SendEmail.main(SendEmail.java:134)
    Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connect(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:288)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:231)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1900)
    … 7 more

    Reply
    1. props.put(“mail.smtp.port”, “25”); instead of props.put(“mail.smtp.port”, “465”);

      Reply
      1. It didn’t work, i get this exception this time.

        Exception in thread “main” java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25;
        nested exception is:
        java.net.SocketException: Network is unreachable: connect
        at com.igate.mail.SendEmail.main(SendEmail.java:136)
        Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25;
        nested exception is:
        java.net.SocketException: Network is unreachable: 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:317)
        at javax.mail.Service.connect(Service.java:176)
        at javax.mail.Service.connect(Service.java:125)
        at javax.mail.Transport.send0(Transport.java:194)
        at javax.mail.Transport.send(Transport.java:124)
        at com.igate.mail.SendEmail.main(SendEmail.java:130)
        Caused by: java.net.SocketException: Network is unreachable: connect
        at java.net.DualStackPlainSocketImpl.connect0(Native Method)
        at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
        at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
        at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
        at java.net.AbstractPlainSocketImpl.connect(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:288)
        at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:231)
        at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1900)
        … 7 more

        Reply
        1. HI,

          Even i am facing the same problem. did you resolve this?? i get error on both 25 and 465.
          Its urgent please help me.

          Thanks
          Shaff

          Reply
  107. I am a great faaaan of you. up till now up to 80% of my issues related to Struts, JavaMail API and Hibernate were resolved by your examples…
    Thanks a lot…

    Reply
  108. getting this error message while using above code .Use real server address instead of 127.0.0.1 in your account. please post how to resolve this

    Reply
  109. I have tried your code but it giving me this error can you please help me . i am using websphere 7

    javax.mail.MessagingException: Can’t send command to SMTP host;
    nested exception is:
    javax.net.ssl.SSLHandshakeException: com.ibm.jsse2.util.g: PKIX path building failed: java.security.cert.CertPathBuilderException: PKIXCertPathBuilderImpl could not build a valid CertPath.; internal cause is:
    java.security.cert.CertPathValidatorException: The certificate issued by OU=Equifax Secure Certificate Authority, O=Equifax, C=US is not trusted; internal cause is:
    java.security.cert.CertPathValidatorException: Certificate chaining error

    Reply
  110. Sir can u explain the code. It works well. But can’t understand how it works

    Reply
  111. Thank you very much,i was stuck but thanks to your code i was able to find my error

    Reply
  112. Hi mkyong,

    i have tried your code for mailing purpose but it is not working giving an error for stating the TLS.

    Kindly help me out from this error.

    Thanks and Regards,
    Aman Raikwar

    Reply
  113. error occur during the implementing java mail api then what is a solution?

    Error 500: java.lang.RuntimeException: javax.mail.MessagingException: Can’t send command to SMTP host; nested exception is: javax.net.ssl.SSLHandshakeException: com.ibm.jsse2.util.g: PKIX path building failed: java.security.cert.CertPathBuilderException: PKIXCertPathBuilderImpl could not build a valid CertPath.; internal cause is: java.security.cert.CertPathValidatorException: The certificate issued by OU=Equifax Secure Certificate Authority, O=Equifax, C=US is not trusted; internal cause is: java.security.cert.CertPathValidatorException: Certificate chaining error

    Reply
  114. Hey, I complied both codes but getting same error like as follows:

    javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
    nested exception is:
    java.net.ConnectException: Connection timed out: connect
    at com.example.mail.SendMailSSL.main(SendMailSSL.java:43)
    Caused by: javax.mail.SendFailedException: Sending failed;
    nested exception is:
    javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
    nested exception is:
    java.net.ConnectException: Connection timed out: connect
    at javax.mail.Transport.send0(Transport.java:219)
    at javax.mail.Transport.send(Transport.java:81)
    at com.example.mail.SendMailSSL.main(SendMailSSL.java:38)

    Please tell me is something missing in my code ? Actually, I did the program as you mentioned in above tutorial also used the jars that you mentioned.

    Reply
  115. i tried both codes but the same exception occurs in both cases, that is

    Exception in thread “main” java.lang.ClassFormatError: Absent Code attribute in
    method that is not native or abstract in class file javax/mail/MessagingException

    how can i fix this problem.thanks

    Reply
  116. Hi I am using
    Front End : RAD(Rational Application Development-IBM Tool)
    Back End: DB2 (IBM Tool)

    So which code should I use TLS or SSL?

    What are the prerequisites I need to install to run both the code.

    and whether we need saparate smtp server,or any smtp protocol?

    Provide me download link and give me some necessary guidance.

    Thank you

    Reply
  117. Hi I want to implement Java Mail Api in my Project.
    Front End : RAD(Rational Application Development-IBM Tool)
    Back End: DB2 (IBM Tool)

    So which code should I use TLS or SSL?

    What are the prerequisites I need to install to run both the code.

    and whether we need saparate smtp server,or any smtp protocol?

    Provide me download link and give me some necessary guidance.

    Thank you

    Reply
    1. You should use SSL connection, As it also provide seurity…:)

      Reply
  118. HELP NEEDED!!!!!!!!!!!!!!
    Above program gives following output
    A java Exception has occured.
    Exception in thread “main” java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/mail/MessagingException
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$100(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
    at java.lang.Class.getMethod0(Unknown Source)
    at java.lang.Class.getMethod(Unknown Source)
    at sun.launcher.LauncherHelper.getMainMethod(Unknown Source)
    at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)

    Reply
  119. I don’t think the javaee.jar is requried.
    I am on Tomcat 7 with just the mail.jar. There is no javaee.jar and the example still works fine.

    Reply
  120. Sir…mkyong…you are awesome..thanks for the code..it is working great…

    Reply
  121. I have created forgot password.jspx page.I am using spring roo.I want to send the password to the corresponding mail id fetching it(password)from the database.
    Please tell me how to achieve it.

    Thanks,
    Girish

    Reply
  122. Hi I want to implement Java Mail Api in my Project.
    Front End : RAD(Rational Application Development-IBM Tool)
    Back End: DB2 (IBM Tool)

    So which code should I use TLS or SSL?

    What are the prerequisites I need to install to run both the code.

    Provide me download link and give me some necessary guidance.

    Thank you

    Reply
  123. Im getting this exception, could it be because I’m using it inside a CXF project?:

    org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtp.gmail.com:465
    	at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1242)
    	at org.apache.commons.mail.Email.send(Email.java:1267)
    	at org.ruleta.email.EmailTest.main(EmailTest.java:30)
    Caused by: javax.mail.NoSuchProviderException: Unable to locate provider for protocol: smtp
    	at javax.mail.Session.getProvider(Session.java:237)
    	at javax.mail.Session.getTransport(Session.java:346)
    	at javax.mail.Session.getTransport(Session.java:376)
    	at javax.mail.Transport.send(Transport.java:67)
    	at javax.mail.Transport.send(Transport.java:48)
    	at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1232)
    	... 2 more
    Reply
  124. Dear Sir,
    i use the java send email using TLS but i meet the exception

    javax.mail.MessagingException: 502 5.5.1 Unrecognized command. d2sm31624792paw.19

    at com.sun.mail.smtp.SMTPTransport.issueCommand(SMTPTransport.java:1481)
    at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1331)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:420)
    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 sendemail.Sendemail.main(Sendemail.java:55)

    Please Help Sir.

    Reply
  125. Dear Sir,
    i use the java send email using TLS but i meet the exception

    javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1
    Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1379)
    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 sendemail.Sendemail.main(Sendemail.java:55)

    Please Help Sir.

    Reply
  126. i got the following error when i tried to run the above code u given

    plz help me !

    Exception in thread “main” java.lang.RuntimeException: javax.mail.AuthenticationFailedException: 535-5.7.1 Username and Password not accepted. Learn more at
    535 5.7.1 http://support.google.com/mail/bin/answer.py?answer=14257 yi9sm7388072pbc.39

    at examples.SendEmail.main(SendEmail.java:47)
    Caused by: javax.mail.AuthenticationFailedException: 535-5.7.1 Username and Password not accepted. Learn more at
    535 5.7.1 http://support.google.com/mail/bin/answer.py?answer=14257 yi9sm7388072pbc.39

    Reply
  127. Hi sir,

    this code is working fine.
    but it is taking 14 seconds for a mail to send.
    how can i reduce this time?
    i have to send bulk mails using smtp gmail account.
    please guide me.
    how many number of mails can i send per second using smtp.gmail.com

    Reply
    1. Hi didnt test with smtp gmail account.But it should not take 15 second to send a mail with my code. Yes if u have so many mails to send then it might take little more.

      Reply
      1. Hi shankar,

        i have just installed netbeans.
        i did not configure any javamail s/w is it ok?
        for me it is taking 15 seconds how can i solve it?
        should i install any other s/w?

        Reply
          1. Hi Shankar,

            i have mailid you the code plz check once..

        1. hi i tried this code but it’s not working

          send me full coding for java sending mail and sms

          Reply
  128. Please I designed & Implemented Java Mail Applications and I got errors.

    Reply
    1. hello

      smtp.gmail.com dont exist now

      it is an other address (googlemail ? ..)

      Reply
  129. hi,i got below exception,pls give me solution.

    Exception in thread “main” java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
    nested exception is:
    java.net.ConnectException: Connection timed out: connect
    at com.hp.it.criticalparameters.utils.Test.main(Test.java:48)
    Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
    nested exception is:
    java.net.ConnectException: Connection timed out: connect
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1282)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
    at javax.mail.Service.connect(Service.java:297)
    at javax.mail.Service.connect(Service.java:156)
    at javax.mail.Service.connect(Service.java:105)
    at javax.mail.Transport.send0(Transport.java:168)
    at javax.mail.Transport.send(Transport.java:98)
    at com.hp.it.criticalparameters.utils.Test.main(Test.java:43)
    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:232)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1250)
    … 7 more

    Reply
    1. @shankar..
      Ok Let me check all these code in Client’s Machine.
      Thanks for your help.

      Reply
      1. @Kalpna: lemme know if my code works. i am new in blogging so kindly post if u liked that. thanks in advace.

        Reply
        1. yes ..it works..your code has been successfully ran on client’s machine.
          thanks.

          Reply
          1. @kalpna: thankx alot. keep visiting my website. if u r tech geek and and like to share ur knowledge with people. thats right platform. i invite u to right some post.just login u will get author rights.

  130. I have to send mail over without using SSL.when I test my application in my machine its working fine.when i executed my application in Client’s Machine i get the following Exception.

    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed:

    sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:150)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1476)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:174)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:168)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:846)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:106)
    at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:495)
    at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:433)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:815)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1025)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1038)
    at InstallCert.main(InstallCert.java:63)
    Caused by: sun.security.validator.ValidatorException: PKIX path building failed:

    sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:221)
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:145)
    at sun.security.validator.Validator.validate(Validator.java:203)
    at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:172)
    at InstallCert$SavingTrustManager.checkServerTrusted(InstallCert.java:158)
    at com.sun.net.ssl.internal.ssl.JsseX509TrustManager.checkServerTrusted(SSLContextImpl.java:320)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:839)
    … 7 more
    Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to

    requested target
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:236)
    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:194)
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:216)
    … 13 more

    my client is using his private mail server and port no 25.

    Reply
    1. Kindly check client mail server IP and post address. my code should work. i tested on many networks.

      Reply
      1. hi,
        when i am running the above code i am getting unable to connect firsttime ,but when i run successively i am getting 404 error ,so plz let me know where is the prob.

        rishi

        Reply
  131. Hi, i am getting this kind of exception please help me. i am using jdk 1.6 but the same code is working fine in jdk1.4.

    Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingExcep
    tion: Can't send command to SMTP host;
      nested exception is:
            javax.net.ssl.SSLKeyException: RSA premaster secret error
            at SendMailTLS.main(SendMailTLS.java:47)
    Caused by: javax.mail.MessagingException: Can't send command to SMTP host;
      nested exception is:
            javax.net.ssl.SSLKeyException: RSA premaster secret error
            at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:1365)
            at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:1353)
            at com.sun.mail.smtp.SMTPTransport.ehlo(SMTPTransport.java:794)
            at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:33
    6)
            at javax.mail.Service.connect(Service.java:258)
            at javax.mail.Service.connect(Service.java:137)
            at javax.mail.Service.connect(Service.java:86)
            at javax.mail.Transport.send0(Transport.java:150)
            at javax.mail.Transport.send(Transport.java:80)
            at SendMailTLS.main(SendMailTLS.java:42)
    
    Reply
    1. and i am using windows 2008 server and jdk1.6 and the code is working in windows 2008 jdk1.4

      Reply
    2. java version : 1.6.0-rc
      Ext Dirs : C:\Program Files (x86)\Java\jdk1.6.0\jre\lib\ext;C:\Windows\Sun\Java\
      lib\ext

      Reply
  132. Hi,

    Where do I download these packages from:
    package com.mkyong.common;
    package sendEmail;

    I am trying to implement this to automatically send emails on a predetermined schedule.

    Reply
    1. ignore the “com.mkyong.common”, it’s just packaging in my development environment, not require to run above mailing program.

      Reply
  133. plz tell me how to code login page that only auntheticate gmail uname and password and redirect other page in struts2

    Reply
  134. Hey Sir,
    Thanks a lot for your tutorial and your great website in general!
    I tried this code, but got an error:
    Could not connect to SMTP host: smtp.gmail.com, port: 465;
    The error appears in the both examples (with SSL and TLS).
    Can you help me please?

    Reply
    1. Sorry, that was my fault. I used the older version of mail.jar library.
      Everything works perfectly)
      Thanks one more time!

      Reply
  135. Hello Sir,

    The codes are running successfully for Gmail vis SSL ; however on button click, the event is being fired twice; that two similar email are being sent,

    can you explain this please?

    Reply
  136. Dear friend,
    I have implemented the GMail via SSL in my project.

    The form contains a button to send notification automatically to members once directly clicking on the “SEND NOTIF” button;

    Your codes run successfully(thank you loads for that) but the problem is that the mail is being sent twice. I will be very grateful if you can help me to find the reason behind this.

    Reply
  137. I Found some Issue in the code when i’m trying to send to a particular mail id for more than 3 to 4 times , its gives a error “com.sun.mail.smtp.SMTPAddressFailedException: 554 5.7.1 ” although the id is correct and even when the mail id is not proper it doesn’t give any error.

    Any thing to highlight for this issue.

    Reply
  138. Hi sir this web site is helpful……
    I thought that this application is developed using JSF give some hints.
    Thank u in advance..

    Reply
  139. I’m getting the following error.
    Exception in thread “main” java.lang.RuntimeException: javax.mail.MessagingExcep
    tion: Could not connect to SMTP host: smtp.gmail.com, port: 465;
    Tried with the port number 587 also but no luck.
    Please help.

    Reply
    1. When I am connecting through smtp.gmail.com or my official smtp server its working fine but if Use Client’s smtp server getting the error:

      Exception in thread “main” java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: Client’s server, port: 465

      Reply
      1. When i am connecting in my localhost server in my laptop (Tomcat 7) with a web service, the unit test work fine (mail sending), but when i deployed the aplication in a WAR file in the remote server with Tomcat 7 too, getting:
        Could not connect to SMTP host: smtp.gmail.com, port: 465, response -1

        after ten minute of tried get a conection:
        DEBUG SMTP: trying to connect to host “smtp.gmail.com”, port 465, isSSL false
        DEBUG SMTP: EOF: [EOF]
        DEBUG SMTP: could not connect to host “smtp.gmail.com”, port: 465, response: -1

        I tried everything, but i don’t know what more can i do…any help?

        Reply
        1. Hi when i try the code below in ecplise i’m getting the following error:( can u help it out 🙁 the error is as following ..

          at java.security.AccessController.doPrivileged(Native Method)
          at java.net.URLClassLoader.findClass(Unknown Source)
          at java.lang.ClassLoader.loadClass(Unknown Source)
          at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
          at java.lang.ClassLoader.loadClass(Unknown Source)
          … 1 more

          and the code is ..

           
          
          package email;
          
          import java.util.Properties;
          import javax.mail.*;
          import javax.mail.internet.*;
          
          public class SendMailSSL {
           public static void main(String[] args) {
          
           String to="[email protected]";//change accordingly
          
          //Get the session object
            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 protected]","ni$haazar");//change accordingly
             }
            });
           
          //compose message
            try {
             MimeMessage message = new MimeMessage(session);
             message.setFrom(new InternetAddress("[email protected]"));//change accordingly
             message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
             message.setSubject("Hello");
             message.setText("Testing.......");
             
             //send message
             Transport.send(message);
          
             System.out.println("message sent successfully");
           
            } catch (MessagingException e) {throw new RuntimeException(e);}
           
           }
          }
          
          Reply
        2. I’m getting the following error while compiling the below code using ecplise .. 🙁

          Please help me out DEBUG: JavaMail version 1.3.2
          DEBUG: java.io.FileNotFoundException: C:\Program Files (x86)\Java\jre6\lib\javamail.providers (The system cannot find the file specified)
          DEBUG: !anyLoaded
          DEBUG: not loading resource: /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,Sun Microsystems, Inc], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc]}
          DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], 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,Sun Microsystems, Inc], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], 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: !anyLoaded
          DEBUG: not loading resource: /META-INF/javamail.address.map
          DEBUG: java.io.FileNotFoundException: C:\Program Files (x86)\Java\jre6\lib\javamail.address.map (The system cannot find the file specified)
          Exception in thread “main” java.lang.NoClassDefFoundError: com/sun/mail/util/SharedByteArrayInputStream
          at email.MailerService.sendMail(MailerService.java:38)
          at email.MailerService.main(MailerService.java:148)
          Caused by: java.lang.ClassNotFoundException: com.sun.mail.util.SharedByteArrayInputStream
          at java.net.URLClassLoader$1.run(Unknown Source)
          at java.security.AccessController.doPrivileged(Native Method)
          at java.net.URLClassLoader.findClass(Unknown Source)
          at java.lang.ClassLoader.loadClass(Unknown Source)
          at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
          at java.lang.ClassLoader.loadClass(Unknown Source)
          … 2 more

          Reply
          1. Hai friends , i made a little mistake , I unwantedly imported j2ee.jar , i got proper mail , when i removed that jar ..

            the jar to be used for this code are , mail.jar , activation.jar..

            thankyou mkyong , i’m new to java , your website is so useful for my studies 😀 ..

  140. hello Sir ur JavaMail – GMail via TLS program will run sucessfully,but want to send an email to multiple recipients,i try to modify ur code but it won’t work ,plz upload the email to multiple recipients program as soon as….

    Reply
  141. Exception in thread “main” java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
    nested exception is:
    java.net.ConnectException: Connection timed out: connect
    at org.test.FirstMail.main(FirstMail.java:48)
    Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
    nested exception is:
    java.net.ConnectException: Connection timed out: connect
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1972)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:642)
    at javax.mail.Service.connect(Service.java:317)
    at javax.mail.Service.connect(Service.java:176)
    at javax.mail.Service.connect(Service.java:125)
    at javax.mail.Transport.send0(Transport.java:194)
    at javax.mail.Transport.send(Transport.java:124)
    at org.test.FirstMail.main(FirstMail.java:43)
    Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connect(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:319)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:233)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1938)
    … 7 more

    Reply
      1. try out ssl with port number 465

        in the comment section i have added the same which can be used to send an attachment

        Reply
  142. How do i do a automated mail sending with the user’s inputted email based on user input? I receive an error. Please help.
    Form

     <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    </head>
    <body>
    	<form name ="form" action="EmailSendServlet">
    	Name:<input name ="name" type = 'text'><br>
    	Email:<input name ="email" type = 'text'><br>
    	<input type = "submit" value = "Submit">
    	</form>
    </body>
    </html>

    Email Send DB

    package sendEmail;
    import java.util.Arrays;
    import java.util.Properties;
    import java.util.Vector;
    
    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;
    import javax.mail.*;
    
    public class EmailSendDB {
    	public static void main(String[] args) {
    		EmailSend emailsend = new EmailSend();
    		String name = emailsend.getName();
    		String email = emailsend.getEmail();
    		System.out.println(Arrays.asList(args));
    		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("user","password");
    				}
    			});
     
    		try {
     
    			Message message = new MimeMessage(session);
    			message.setFrom(new InternetAddress("AecoSea"));
    			message.setRecipients(Message.RecipientType.TO,
    					InternetAddress.parse(email));
    			message.setSubject("Testing Subject");
    			message.setText("Dear "+name+"," +
    					"\n\n No spam to my email, please!");
     
    			Transport.send(message);
    			System.out.println("Done");
     
    		} catch (Exception e) {
    		}
    	}
    }

    Email Servlet

    package sendEmail;
    
    import java.io.IOException;
    import java.util.Properties;
    import java.util.Vector;
    
    //import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.mail.*;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    import javax.mail.PasswordAuthentication;
    import javax.mail.Session;
    import javax.mail.Transport;
    
    /**
     * Servlet implementation class EmailSendServlet
     */
    @WebServlet("/EmailSendServlet")
    public class EmailSendServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
           
        /**
         * @see HttpServlet#HttpServlet()
         */
        public EmailSendServlet() {
            super();
            // TODO Auto-generated constructor stub
        }
    
    	/**
    	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		String name = request.getParameter("name");
    		String email = request.getParameter("email");
    		//EmailSend emailsend = new EmailSend(name,email);
    		EmailSendDB db = new EmailSendDB();
    		String[] args={};
    		db.main(args,name,email);
    	}	
    	/**
    	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// TODO Auto-generated method stub
    	}
    
    }
    
    Reply
    1. you are using wrong architecture. Always create package from specific tasks. so here u want to send automated mails. so create a mailer class which sends a mail. test it explicitly then integrate in ur servlet code. here you created main in EmailSendDB class. that is wrong. create a mail which send a mail and except arguments like sender name, receiver name and subject and body. do not call main in servlet. this is wrong. modify ur EmailSendDB.
      I wrote on mailer service class which have mathod send mail. you can use that.
      call it like

      MailerService mail = new MailerService();
      //cc &amp; bcc are comma separated
      mail.sendMail("sender email id",
      "send to", "cc",
      "bcc", "first mail",
      "hi, this is my first mail ");//you can leave black which fields you are not using.
       

      find it here http://morwalz.com/java-mail/

      Reply
  143. Getting below error –

    Exception in thread “main” java.lang.NoClassDefFoundError: com/sun/mail/util/SharedByteArrayInputStream
    Caused by: java.lang.ClassNotFoundException: com.sun.mail.util.SharedByteArrayInputStream
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    … 1 more

    Reply
  144. Hello Sir. I implemented to send email using SSL connection over Gmail smtp server. when i give a valid receiver email-id everything works perfectly. But when i give an invalid receiver email-id it doesn’t show any exception like invalid emailid. This invalid emailid notification is sent to the sender’s email account. But i don’t get any MessagingException on my screen. Here is the code. Please help me out. Thanks in advance.
    public class SendEmail
    {
    public static int sendEmail(String toAddress,String userID)
    {
    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 protected]”,”password”);
    }
    });
    try
    {
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(“senderaddress”));
    message.setRecipients(Message.RecipientType.TO,
    InternetAddress.parse(toAddress));
    message.setSentDate(new Date());
    message.setSubject(“Account Activation for T20home”);
    message.setContent(“Hello”,”text/html”);
    Transport.send(message);
    }
    catch(MessagingException mex)
    {
    Exception ex=mex;
    if (ex instanceof SendFailedException)
    {
    SendFailedException sfex = (SendFailedException)ex;
    Address []invalid= sfex.getInvalidAddresses();
    if(invalid!=null)
    {
    return -1;
    }
    Address []valid_sent=sfex.getValidSentAddresses();
    if(valid_sent!=null)
    {
    return 1;
    }
    Address []valid_unsent=sfex.getValidUnsentAddresses();
    if(valid_unsent!=null)
    {
    return 0;
    }
    }
    }
    }
    }

    Reply
    1. That is the nature of Email. It is not possible to check for a valid receiver because the mail may be sent through many servers to eventually get to the receiving server, possibly some hours later depending on traffic.

      Only the receiving server can decide whether the email address is finally valid, and the only way it can inform you is by sending an email.

      It’s exactly the same if you use any email program .

      Reply
      1. So, how do the websites handle this junk data with invalid email-ids. They shouldn’t be kept in the database permanently ??

        Reply
      2. Before clalling sendEmail method. validate email address by writing your own method. Email will not validate the data.

        Reply
  145. Hi Mkyong,

    Thanks very much for posting these code examples. Having working examples greating accelerates learning the JavaMail API.

    One note: In my experience I only needed

    mail.jar

    , not

    javaee.jar

    . I downloaded the JavaMail-1.4.5 bundle from Oracle and that was the only jar necessary to get both of these examples working: http://www.oracle.com/technetwork/java/index-138643.html

    Reply
    1. Thanks for your input, may be javaee.jar in your classpath already, this is standard j2ee jdk jar.

      Reply
  146. Hi,

    Am trying to send the mail using ssl, but it has stucked on transport.send(message). I am not getting any error and it remain same for a long time. The method for sending mail, am using in servlet. But before using in servlet,I have tested with java compiler. It is working fine

    Kindly provide the help.

    Reply
  147. HELP ME!
    Exception in thread “main” java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.yahoo.fr, port: 465;
    nested exception is:
    java.net.ConnectException: Connection timed out: connect
    at SendMail.main(SendMail.java:40)
    Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.yahoo.fr, port: 465;
    nested exception is:
    java.net.ConnectException: Connection timed out: connect
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1972)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:642)
    at javax.mail.Service.connect(Service.java:317)
    at javax.mail.Service.connect(Service.java:176)
    at javax.mail.Service.connect(Service.java:125)
    at javax.mail.Transport.send0(Transport.java:194)
    at javax.mail.Transport.send(Transport.java:124)
    at SendMail.main(SendMail.java:35)
    Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connect(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:319)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:233)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1938)
    … 7 more

    Reply
  148. I’ve tried so many ways already but it keeps reporting this exception:

    java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/mail/MessagingException
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:621)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
    at java.net.URLClassLoader.access$000(URLClassLoader.java:56)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
    Could not find the main class: test_1.mail3. Program will exit.
    Exception in thread “main” Java Result: 1

    Reply
      1. i have both javaee.jar and also mail.jar .. the code runs fine in eclipse.. but when the same classes are run on the server, i encounter the below error.

        "C:\Program Files\Java\jre6\bin\java.exe" -classpath .\;E:\MailStrippers\util\MaWSJavaClientLibrary-1.0.jar;E:\MailStrippers\util\commons-codec-1.3.jar;E:\MailStrippers\util\commons-httpclient-3.0.1.jar;E:\MailStrippers\util\commons-logging-1.1.jar;E:\MailStrippers\util\activation2.jar;E:\MailStrippers\util\jaxb-api.jar;E:\MailStrippers\util\jaxb-impl.jar;E:\MailStrippers\util\jaxb-xjc.jar;E:\MailStrippers\util\jsr173_1.0_api.jar;E:\MailStrippers\util\log4j-1.2.14.jar;E:\MailStrippers\util\javaee-api-6.0.jar;E:\MailStrippers\util\mail.jar;E:\MailStrippers\util\jdom-1.0.jar;E:\MailStrippers\util\ojdbc14_g.jar CheckXMLInDatabase
        
        ERROR:
        Exception in thread "main" java.lang.ClassFormatError: Absent Code attribute in
        method that is not native or abstract in class file javax/mail/Authenticator
                at java.lang.ClassLoader.defineClass1(Native Method)
                at java.lang.ClassLoader.defineClassCond(Unknown Source)
                at java.lang.ClassLoader.defineClass(Unknown Source)
                at java.security.SecureClassLoader.defineClass(Unknown Source)
                at java.net.URLClassLoader.defineClass(Unknown Source)
                at java.net.URLClassLoader.access$000(Unknown Source)
                at java.net.URLClassLoader$1.run(Unknown Source)
                at java.security.AccessController.doPrivileged(Native Method)
                at java.net.URLClassLoader.findClass(Unknown Source)
                at java.lang.ClassLoader.loadClass(Unknown Source)
                at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
                at java.lang.ClassLoader.loadClass(Unknown Source)
                at CheckXMLInDatabase.parseXML(CheckXMLInDatabase.java:79)
                at CheckXMLInDatabase.forFile(CheckXMLInDatabase.java:105)
                at CheckXMLInDatabase.main(CheckXMLInDatabase.java:112)
        
        Reply
          1. how can i send mails thru hotmail or thru facebook

          2. how can i send mails thru hotmail or facebook and i want to know how can we send sms thru java prgs

  149. i tried the code on my localhost it works but wn i run in in a remote web server, it throws AccessControlException

    java.security.AccessControlException: access denied (java.net.SocketPermission 173.194.67.108:587 connect,resolve)
    	java.security.AccessControlContext.checkPermission(AccessControlContext.java:323)
    	java.security.AccessController.checkPermission(AccessController.java:546)
    	java.lang.SecurityManager.checkPermission(SecurityManager.java:532)
    	java.lang.SecurityManager.checkConnect(SecurityManager.java:1034)
    	java.net.Socket.connect(Socket.java:513)
    	java.net.Socket.connect(Socket.java:469)
    	com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:267)
    	com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:227)
    	com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1511)
    	com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:453)
    	javax.mail.Service.connect(Service.java:313)
    	javax.mail.Service.connect(Service.java:172)
    	javax.mail.Service.connect(Service.java:121)
    	javax.mail.Transport.send0(Transport.java:190)
    	javax.mail.Transport.send(Transport.java:120)
    	ContactUsServlet.sendMail(ContactUsServlet.java:139)
    	ContactUsServlet.processRequest(ContactUsServlet.java:51)
    	ContactUsServlet.doPost(ContactUsServlet.java:153)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
    	javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
    	sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    	sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    	java.lang.reflect.Method.invoke(Method.java:597)
    	org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:244)
    	java.security.AccessController.doPrivileged(Native Method)
    	javax.security.auth.Subject.doAsPrivileged(Subject.java:517)
    	org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:276)
    	org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:162
    
    Reply
  150. The code which i used:
    package com.myprogram;

    import java.util.Properties;
    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;

    class SendMailSSL {
    public static void main(String[] args) {
    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(“username”,”password”);
    }
    });

    try {

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(“[email protected]”));
    message.setRecipients(Message.RecipientType.TO,
    InternetAddress.parse(“[email protected]”));
    message.setSubject(“Testing Subject”);
    message.setText(“Dear Mail Crawler,” +
    “\n\n No spam to my email, please!”);

    Transport.send(message);

    System.out.println(“Done”);

    } catch (MessagingException e) {
    throw new RuntimeException(e);
    }
    }
    }

    —————————————————————
    I am getting these errors:

    Exception in thread “main” java.lang.RuntimeException: javax.mail.AuthenticationFailedException: 535-5.7.1 Please log in with your web browser and then try again. Learn more at
    535 5.7.1 https://support.google.com/mail/bin/answer.py?answer=78754 qd10sm7778242pbb.38

    at com.myprogram.SendMailSSL.main(SendMailSSL.java:44)
    Caused by: javax.mail.AuthenticationFailedException: 535-5.7.1 Please log in with your web browser and then try again. Learn more at
    535 5.7.1 https://support.google.com/mail/bin/answer.py?answer=78754 qd10sm7778242pbb.38

    at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:823)
    at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:756)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:673)
    at javax.mail.Service.connect(Service.java:317)
    at javax.mail.Service.connect(Service.java:176)
    at javax.mail.Service.connect(Service.java:125)
    at javax.mail.Transport.send0(Transport.java:194)
    at javax.mail.Transport.send(Transport.java:124)
    at com.myprogram.SendMailSSL.main(SendMailSSL.java:39)

    Reply
  151. Mine gives access denied error. I have the correct username, password and from field entries.

     
    Jul 23, 2012 6:00:45 PM org.springframework.scheduling.support.TaskUtils$LoggingErrorHandler handleError
    SEVERE: Unexpected error occurred in scheduled task.
    java.lang.SecurityException: Access to default session denied
    	at javax.mail.Session.getDefaultInstance(Session.java:320)
    	at com.mymeedia.mailman.GmailSSLSender.sendMail(GmailSSLSender.java:25)
    	at com.mymeedia.jobs.SendMailsJob.doJob(SendMailsJob.java:49)
    	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    	at java.lang.reflect.Method.invoke(Method.java:597)
    	at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:64)
    	at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:53)
    	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
    	at java.util.concurrent.FutureTask$Sync.innerRunAndReset(FutureTask.java:317)
    	at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:150)
    	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$101(ScheduledThreadPoolExecutor.java:98)
    	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.runPeriodic(ScheduledThreadPoolExecutor.java:180)
    	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:204)
    	at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    	at java.lang.Thread.run(Thread.java:680)
    Jul 23, 2012 6:00:45 PM com.mymeedia.jobs.FetchMailsJob doJob
    INFO: FetchMail doJob reached
    Jul 23, 2012 6:00:45 PM com.mymeedia.jobs.FetchMailsJob doJob
    INFO: End of Fetchmail reached
    Jul 23, 2012 6:00:55 PM com.mymeedia.jobs.VideoProcessingJob doJob
    INFO: VideoProcessor fixedDelay reached
    
     
    Reply
    1. I fixed it by using getInstance instead of Default Instance.

       Session session = Session.getInstance(props,
      			new javax.mail.Authenticator() {
      				protected PasswordAuthentication getPasswordAuthentication() {
      					return new PasswordAuthentication("username","password");
      
      Reply
  152. SEND AN ATTACHMENT

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

    // its not mine. but mixed codes from two programs . it finely works. thanks for MKYong and TP
    // called the method from a servlet.
    public class AttachService {

    public void sendAttachment() {
    System.out.println(“attach inside “);
    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?);

    // Get the default Session object.
    Session session = Session.getDefaultInstance(props,
    new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(“[email protected]”,”passwd”);
    }
    });

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

    // Set From: header field of the header.
    message.setFrom(new InternetAddress(“[email protected]”));//no need to change

    // Set To: header field of the header.
    message.addRecipient(Message.RecipientType.TO,
    new InternetAddress(“[email protected]”));

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

    // Create the message part
    BodyPart messageBodyPart = new MimeBodyPart();

    // Fill the message
    messageBodyPart.setText(“This is message body”);

    // Create a multipar message
    Multipart multipart = new MimeMultipart();

    // Set text message part
    multipart.addBodyPart(messageBodyPart);

    // Part two is attachment
    messageBodyPart = new MimeBodyPart();

    String filename = “d:\\file.txt”; // file name and location

    DataSource source = new FileDataSource(filename);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);

    // Send the complete message parts
    message.setContent(multipart );

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

    }

    }

    it works. All the best

    Reply
  153. I am trying to run either of sample but getting following error. Please suggest to solve this problem.

    Thanks,
    Rajesh

    Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingExcep
    tion: Could not connect to SMTP host: smtp.gmail.com, port: 587;
      nested exception is:
            java.net.ConnectException: Connection refused: connect
            at com.deloitte.utility.mail.GMailSMTP.main(GMailSMTP.java:49)
    Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.g
    mail.com, port: 587;
      nested exception is:
            java.net.ConnectException: Connection refused: connect
            at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1934)
            at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:63
    8)
            at javax.mail.Service.connect(Service.java:317)
            at javax.mail.Service.connect(Service.java:176)
            at javax.mail.Service.connect(Service.java:125)
            at javax.mail.Transport.send0(Transport.java:194)
            at javax.mail.Transport.send(Transport.java:124)
            at com.deloitte.utility.mail.GMailSMTP.main(GMailSMTP.java:44)
    Caused by: java.net.ConnectException: Connection refused: 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:288)
            at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:231)
            at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1900)
    
    Reply
  154. Hi yong.. Thanks for your code. I searched lots of sites. But none of them executed without exception. Your code is working fine without any exception for me.

    Regards..

    Reply
  155. Mkyong you are a great man….!
    I love u sooooooooooo much………..!

    Reply
  156. i getting this exception during execution of above code plz help me to solve this exception……………..

    Exception in thread “main” java.lang.RuntimeException: javax.mail.SendFailedException: Sending failed;
    nested exception is:
    javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first. hz10sm2672045pbc.32

    at com.lara.SendMail.main(SendMail.java:46)
    Caused by: javax.mail.SendFailedException: Sending failed;
    nested exception is:
    javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first. hz10sm2672045pbc.32

    at javax.mail.Transport.send0(Transport.java:219)
    at javax.mail.Transport.send(Transport.java:81)
    at com.lara.SendMail.main(SendMail.java:41)

    Reply
    1. Use below property in ur code:
      mail.smtp.starttls.enable=”true”

      Reply
  157. package com.echidna.main;
    
    import java.util.Properties;
    
    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 SendMailTLS {
     
    	public static void main(String[] args) {
     
    		final String username = "[email protected]";
    		final String password = "gayetrima";
     
    		Properties props = new Properties();
    		props.put("mail.smtp.auth", "true");
    		props.put("mail.smtp.starttls.enable", "true");
    		props.put("mail.smtp.host", "smtp.gmail.com");
    		props.put("mail.smtp.port", "587");
     
    		Session session = Session.getInstance(props,
    		  new javax.mail.Authenticator() {
    			protected PasswordAuthentication getPasswordAuthentication() {
    				return new PasswordAuthentication(username, password);
    			}
    		  });
     
    		try {
     
    			Message message = new MimeMessage(session);
    			message.setFrom(new InternetAddress("[email protected]"));
    			message.setRecipients(Message.RecipientType.TO,
    				InternetAddress.parse("[email protected]"));
    			message.setSubject("Testing Subject");
    			message.setText("Dear Mail Crawler,"
    				+ "\n\n No spam to my email, please!");
     
    			Transport.send(message);
     
    			System.out.println("Done");
     
    		} catch (MessagingException e) {
    			throw new RuntimeException(e);
    		}
    	}
    }
    
    
    //i am getting error like this
    /*
    Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
      nested exception is:
    	java.net.ConnectException: Connection timed out: connect
    	at com.echidna.main.SendMailTLS.main(SendMailTLS.java:48)
    Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
      nested exception is:
    	java.net.ConnectException: Connection timed out: connect
    	at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1972)
    	at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:642)
    	at javax.mail.Service.connect(Service.java:317)
    	at javax.mail.Service.connect(Service.java:176)
    	at javax.mail.Service.connect(Service.java:125)
    	at javax.mail.Transport.send0(Transport.java:194)
    	at javax.mail.Transport.send(Transport.java:124)
    	at com.echidna.main.SendMailTLS.main(SendMailTLS.java:43)
    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:319)
    	at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:233)
    	at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1938)
    	... 7 more
    */
    
    Reply
    1. try this command in ur system(in cmd):
      telnet smtp.gmail.com 587
      see if you are able to access this 587 port. If not then u need to open this port on ur machine.

      Reply
  158. Thanks MKyong,

    Ist source code perfectly executed, but i got error in the 2nd one..

    Any way thank u very much

    Reply
  159. Exception in thread “main” java.lang.RuntimeException: javax.mail.MessagingException: Unknown SMTP host: smtp.gmail.com;
    nested exception is:
    java.net.UnknownHostException: smtp.gmail.com
    at Mailing.main(Mailing.java:46)
    Caused by: javax.mail.MessagingException: Unknown SMTP host: smtp.gmail.com;
    nested exception is:
    java.net.UnknownHostException: smtp.gmail.com
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1543)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:453)
    at javax.mail.Service.connect(Service.java:313)
    at javax.mail.Service.connect(Service.java:172)
    at javax.mail.Service.connect(Service.java:121)
    at javax.mail.Transport.send0(Transport.java:190)
    at javax.mail.Transport.send(Transport.java:120)
    at Mailing.main(Mailing.java:41)
    Caused by: java.net.UnknownHostException: smtp.gmail.com
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:175)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:384)
    at java.net.Socket.connect(Socket.java:546)
    at java.net.Socket.connect(Socket.java:495)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:267)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:227)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1511)
    … 7 more
    please give me reply

    Reply
  160. Greetings,
    Thanks for this very useful code that works perfect.
    I just would like to ask you if you can post the same code, but with file attachment.
    Thanks a lot
    Starfix

    Reply
    1. hey did you find the way of attaching the file?

      Reply
      1. import java.util.*;
        import javax.mail.*;
        import javax.mail.internet.*;
        import javax.activation.*;

        // its not mine. but mixed codes from two programs . it finely works.
        // called the method from a servlet.
        public class AttachService {

        public void sendAttachment() {
        System.out.println(“attach inside “);
        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”);

        // Get the default Session object.
        Session session = Session.getDefaultInstance(props,
        new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(“[email protected]”,”passwd”);
        }
        });

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

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(“[email protected]”));//no need to change

        // Set To: header field of the header.
        message.addRecipient(Message.RecipientType.TO,
        new InternetAddress(“[email protected]”));

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

        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();

        // Fill the message
        messageBodyPart.setText(“This is message body”);

        // Create a multipar message
        Multipart multipart = new MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        // Part two is attachment
        messageBodyPart = new MimeBodyPart();

        String filename = “d:\\file.txt”; // file name and location

        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);
        multipart.addBodyPart(messageBodyPart);

        // Send the complete message parts
        message.setContent(multipart );

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

        }

        }

        it works. All the best

        Reply
  161. i am getting following error

    java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/mail/MessagingException
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$000(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClassInternal(Unknown Source)
    Exception in thread “main”

    Reply
  162. will i be able to send mail through esmtp server using same above code.

    Reply
  163. what is the difference b/w ssl and Tsl connection?

    Reply
  164. I am getting the following errors, HELP plz…
    Exception in thread “main” java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
    nested exception is:
    java.net.ConnectException: Connection refused: connect
    at com.smtp.test.SendMailTLS.main(SendMailTLS.java:48)
    Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
    nested exception is:
    java.net.ConnectException: Connection refused: connect
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1972)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:642)
    at javax.mail.Service.connect(Service.java:317)
    at javax.mail.Service.connect(Service.java:176)
    at javax.mail.Service.connect(Service.java:125)
    at javax.mail.Transport.send0(Transport.java:194)
    at javax.mail.Transport.send(Transport.java:124)
    at com.smtp.test.SendMailTLS.main(SendMailTLS.java:43)
    Caused by: java.net.ConnectException: Connection refused: 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:319)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:233)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1938)
    … 7 more

    Reply
  165. Thanks so much, it worked with out any issue..Great and crispy example :)..

    Reply
  166. Hi MKyong,

    I am getting follwoing error message when i try to send an email.

    javax.mail.SendFailedException: Sending failed;
    nested exception is:
    class javax.mail.MessagingException: Exception reading response;
    nested exception is:
    javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?

    I am getting this error when i use my customer’s SMTP server information (using port 25). When i use smtp.gmail.com, it is working.

    Please let me know your suggestion.

    Thank you!

    Murugesan

    Reply
  167. i dont know why but it doesn’t work if I am using proxy to connect internet otherwise it works great…………

    Reply
    1. MKyong,

      I am getting follwoing error message when i try to send an email.

      javax.mail.SendFailedException: Sending failed;
      nested exception is:
      class javax.mail.MessagingException: Exception reading response;
      nested exception is:
      javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?

      I am getting this error when i use my customer’s SMTP server information (using port 25). When i use smtp.gmail.com, it is working.

      Please let me know your suggestion.

      Thank you!

      Murugesan

      Reply
  168. Hi, im getting the;
    java.net.ConnectException: Connection refused: connect
    im trying the smtp example.

    Reply
    1. I am also getting the same error.I took the above code only and had not changed anything.

      Reply
  169. What to set for the username and password…
    Do reply me!!
    Thanks..

    Reply
    1. I am getting follwoing error message when i try to send an email.
      eskwork

      Hi mkyong,
      Exception in thread “main” java.lang.UnsupportedClassVersionError: Bad version number in .class file
      at java.lang.ClassLoader.defineClass1(Native Method)
      at java.lang.ClassLoader.defineClass(ClassLoader.java:621)
      at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
      at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
      at java.net.URLClassLoader.access$100(URLClassLoader.java:56)
      at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
      at java.security.AccessController.doPrivileged(Native Method)
      at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
      at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
      at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
      please help me

      Reply
    2. i am getting following error

      java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/mail/MessagingException
      at java.lang.ClassLoader.defineClass1(Native Method)
      at java.lang.ClassLoader.defineClass(Unknown Source)
      at java.security.SecureClassLoader.defineClass(Unknown Source)
      at java.net.URLClassLoader.defineClass(Unknown Source)
      at java.net.URLClassLoader.access$000(Unknown Source)
      at java.net.URLClassLoader$1.run(Unknown Source)
      at java.security.AccessController.doPrivileged(Native Method)
      at java.net.URLClassLoader.findClass(Unknown Source)
      at java.lang.ClassLoader.loadClass(Unknown Source)
      at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
      at java.lang.ClassLoader.loadClass(Unknown Source)
      at java.lang.ClassLoader.loadClassInternal(Unknown Source)
      Exception in thread “main”

      PasswordAuthentication(“”,””)

      Reply
  170. its unable to generate the certificate..i’m using RAD 8.0.3

    Reply
  171. please clear me

    Exception in thread “main” java.lang.RuntimeException: javax.mail.AuthenticationFailedException: failed to connect
    at mypack.SendMailTls.main(SendMailTls.java:50)
    Caused by: javax.mail.AuthenticationFailedException: failed to connect
    at javax.mail.Service.connect(Service.java:322)
    at javax.mail.Service.connect(Service.java:172)
    at javax.mail.Service.connect(Service.java:121)
    at javax.mail.Transport.send0(Transport.java:190)
    at javax.mail.Transport.send(Transport.java:120)
    at mypack.SendMailTls.main(SendMailTls.java:45)
    this error is generated why are error coming in sendmail program i am using eclipse helios please consider me next following step [email protected]

    Reply
  172. Thnks a lot for this article.

    I have juste 1 question how i get the password and username for authentification ? i would install server smtp in my machine localhost or juste using the librairie ? thanks.

    Reply
  173. Hey there!!
    thanx for the code..i tried for “JavaMail – GMail via SSL”…m getting no error…bt at the same time…m nt getting any output..i.e mail..
    plz help..

    thanx

    Reply
  174. Hi!

    I’m trying to use the URLDataSource. For some reason i cannot attach the image. I’m behind a proxy but i haven’t tried somewhere else. Can you tell me what’s wrong?

    Thanks in advance!

    javax.mail.MessagingException: IOException while sending message;
    nested exception is:
    java.net.ConnectException: Connection timed out: connect
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1141)
    at EnviarMail.enviaCorreoElectronico(EnviarMail.java:121)
    at EnviarMail.main(EnviarMail.java:59)
    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 sun.net.NetworkClient.doConnect(Unknown Source)
    at sun.net.www.http.HttpClient.openServer(Unknown Source)
    at sun.net.www.http.HttpClient.openServer(Unknown Source)
    at sun.net.www.http.HttpClient.(Unknown Source)
    at sun.net.www.http.HttpClient.New(Unknown Source)
    at sun.net.www.http.HttpClient.New(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at java.net.URL.openStream(Unknown Source)
    at javax.activation.URLDataSource.getInputStream(Unknown Source)
    at javax.activation.DataHandler.writeTo(Unknown Source)
    at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1476)
    at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:865)
    at javax.mail.internet.MimeMultipart.writeTo(MimeMultipart.java:462)
    at com.sun.mail.handlers.multipart_mixed.writeTo(multipart_mixed.java:103)
    at javax.activation.ObjectDataContentHandler.writeTo(Unknown Source)
    at javax.activation.DataHandler.writeTo(Unknown Source)
    at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1476)
    at javax.mail.internet.MimeMessage.writeTo(MimeMessage.java:1772)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1099)
    … 2 more

    my code:

     	public void enviaCorreoElectronico(String email, String nuevoPassword) {
    		BodyPart cuerpoMensaje;
    		MimeMessage message = null;
    		MimeMultipart multipart = null;
    		URL url = null;
    		DataSource ds;
    		try { 	
    			session = Session.getDefaultInstance(props, null);
    			session.setDebug(true);
    
    			message = new MimeMessage(session);
    			message.setFrom(new InternetAddress(remitente));
    			message.addRecipient(Message.RecipientType.TO, new InternetAddress(
    					email));
    			message.setSubject(subject);
    
    			multipart = new MimeMultipart("related");
    
    			cuerpoMensaje = new MimeBodyPart();
    			cuerpoMensaje.setContent(String.format(mensaje, nuevoPassword),
    					"text/html");
    
    			multipart.addBodyPart(cuerpoMensaje);
    		} catch (Exception e) {
    			System.err.println("No se pudo enviar el correo electronico"
    					+ " a la direccion:" + email);
    			e.printStackTrace();
    		}
    		cuerpoMensaje = new MimeBodyPart();
    
    		try {
    			url = new URL("http://www.google.com.mx/images/nav_logo101.png");
    		} catch (MalformedURLException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		
    		ds = new URLDataSource(url);
    		try {
    			cuerpoMensaje.setDataHandler(new DataHandler(ds));
    			cuerpoMensaje.setHeader("Content-ID", "");
    			multipart.addBodyPart(cuerpoMensaje);
    			message.setContent(multipart);
    		} catch (MessagingException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    
    		Transport t = null;
    		try {
    			t = session.getTransport(protocolo);
    		} catch (NoSuchProviderException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		
    		try {
    			t.connect(remitente, password);
    			t.sendMessage(message, message.getAllRecipients());
    			t.close();
    		} catch (MessagingException e) {
    
    			e.printStackTrace();
    		}
    		
    
    	}
    
    Reply
  175. Thanks vihor. I’ve been trying to get this working for a while and you’re code nailed it. Thanks.

    Reply
  176. Thanks a lot. It worked like charm.
    Great Work
    Thanks and Warm Regards,
    Irfan

    Reply
  177. if your code is correct , email id and password is also correct.

    and your getting google authentication exceptition.

    then open gmail using web browser enter username & password
    then gmail will ask for word verification. after word verfication you will login into account.

    then run you java code…no google authentication exceptition will come

    Reply
  178. Hi all,

    and thanks for the hints.

    However, I have a little problem;

    I’m trying example ‘JavaMail – GMail via TLS’
    and I can say it basically ‘works’.

    However, what I am finding, and perhaps I misunderstand the goal here, is that gmail hijacks my ‘from’ field.

    My goal, or intention, is to simply use gmail as a smtp relay, to send on email from my own email server, which existing on a dynamic IP range, has troubles being accepted out there in the spam jittery world.

    The actual wanted results being that email sent on, be identified as having come from :

    [email protected]

    and not,

    @gmail.com

    Yet, this is what happens.

    Any ideas? What are others experience?

    Reply
    1. Oh, and I forgot to mention;
      I have tried almost the exact same thing with my own ISP smtp server, and things come out as hoped/expected.

      Reply
  179. /* TLS also need authentication,you have to give authentication in your session value */

    import java.util.Properties;
    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 SendMailTLS {
     
    	public static void main(String[] args) {
    		String host = "smtp.gmail.com";
    		int port = 587;
    		String username = "username";
    		String password = "password";
     
    		Properties props = new Properties();
    		props.put("mail.smtp.host", "smtp.gmail.com");
    		props.put("mail.smtp.auth", "true");
    		props.put("mail.smtp.starttls.enable", "true");
     
    		Session session = Session.getInstance(props,new javax.mail.Authenticator() {
    			protected PasswordAuthentication getPasswordAuthentication() {
    				return new PasswordAuthentication("username","password");
    			}
    		});
     
    		try {
     
    			Message message = new MimeMessage(session);
    			message.setFrom(new InternetAddress("[email protected]"));
    			message.setRecipients(Message.RecipientType.TO,
    				InternetAddress.parse("[email protected]"));
    			message.setSubject("Testing Subject");
    			message.setText("Dear Mail Crawler," +
    					"\n\n No spam to my email, please!");
     
    			Transport transport = session.getTransport("smtp");
    			transport.connect(host,port,username, password);
     
    			Transport.send(message);
     
    			System.out.println("Done");
     
    		} catch (MessagingException e) {
    			throw new RuntimeException(e);
    		}
    	}
    }
    
    Reply
    1. Your program is giving javax.mail.MessagingException: Could not convert socket to TLS;

      please hint for solve it.
      thanks in Advance.

      Reply
  180. SSL worked but the TLS sample failed with this:

    Exception in thread “main” java.lang.RuntimeException: javax.mail.AuthenticationFailedException: failed to connect, no password specified?

    The password is specified but no joy. Pls advise. Thanks.

    Reply
    1. The original code is badly written. When the Transport.send is being called the authentication might still not be completed, that’s probably why you got the error. One should add ConnectionListener to the transport object and then call Transport.send when the connection is fully opened which means putting the call inside the ‘opened’ event handler of the ConnectionListener object.

      Transport transport = session.getTransport("smtp");
                  transport.addConnectionListener(new ConnectionListener() {
      
                      @Override
                      public void closed(ConnectionEvent e) {
                          
                      }
      
                      @Override
                      public void disconnected(ConnectionEvent e) {
                          
                      }
      
                      @Override
                      public void opened(ConnectionEvent e) {
                          try {
                              Transport.send(message);
                          } catch (MessagingException ex) {
                              ex.printStackTrace();
                          }
                          
                      }
                      
                  });
                  
      transport.connect(host, port, username, password);
      
      Reply
      1. Well, I must correct myself. I tried both, the original version and mine. Neither works. However, I found extremely strange that it worked for other users here. Javadoc API for Transport.send says:

        “Note that send is a static method that creates and manages its own connection. Any connection associated with any Transport instance used to invoke this method is ignored and not used.”

        So, transport.connect(host, port, username, password) is actually irrelevant and is not used at all during the invocation of Transport.send. Having in mind that, I managed to construct the following working version:

        package blah.blah;
        
        import java.util.Properties;
        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 TLSGmail {
            
            public static void send(final String username, final String password, 
                                    String sender, String destination, 
                                    String subject, String messageText) {
                
                Properties props = new Properties();
                
                props.put("mail.smtp.auth", "true");
                props.put("mail.smtp.starttls.enable", "true");
                props.put("mail.transport.protocol", "smtp");
                props.put("mail.smtp.host", "smtp.gmail.com");
                props.put("mail.smtp.port", "587");
                
                Session session = Session.getDefaultInstance(props,
                        new javax.mail.Authenticator() {
                            protected PasswordAuthentication getPasswordAuthentication() {
                                return new PasswordAuthentication(username, password);
                            }
                        });
         
                try {
         
                    Message message = new MimeMessage(session);
                    message.setFrom(new InternetAddress(sender));
                    message.setRecipients(Message.RecipientType.TO,
                        InternetAddress.parse(destination));
                    message.setSubject(subject);
                    message.setText(messageText);
                    
                    Transport.send(message);
         
                    System.out.println("Done");
         
                } catch (MessagingException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        
        Reply
  181. I tried using the script it says no password specified… which username and passowr dis it pertaining to? where do we register? tnx

    Reply
  182. I have the same exception as you. I tested this piece of code at home and it worlkd OK. Then I tried it at my work place and I got the exception (ping also times out).
    So I guess it may have something to do with the internal proxies or conf features oin my company’s intranet. Checking with my IT services.

    Any help will be welcome.

    Reply
  183. thanks, i’ve been looking for this in a lot of sites, and your code is the only, that i found that works!

    Reply
  184. sir i cannot add multiple recipients in sendmailtls as said by comment(in program).whenever i separate them by cooma i get an error

    Reply
    1. Amit,

      First, you’re an idiot…

      Second, post the actual error you’re whining about!

      Third, read the JavaDoc…

      message.addRecipient(RecipientType.TO, new InternetAddress(“[email protected]”));
      message.addRecipient(RecipientType.TO, new InternetAddress(“[email protected]”));
      message.addRecipient(RecipientType.TO, new InternetAddress(“[email protected]”));

      Reply
      1. i am getting following error
        i used my own username and password

        Caught: java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
        nested exception is:
        java.net.ConnectException: Connection refused: connect
        java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
        nested exception is:
        java.net.ConnectException: Connection refused: connect
        at Groovy.EMail.main(EMail.groovy:45)
        Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
        nested exception is:
        java.net.ConnectException: Connection refused: connect
        at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1706)
        at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:525)
        at Groovy.EMail.main(EMail.groovy:40)
        Caused by: java.net.ConnectException: Connection refused: connect
        at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:284)
        at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:227)
        at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1672)
        … 2 more

        Reply
  185. I would appritiate if ur SSL code works for connecting other smtp too.
    I am trying to connect 10.5.128.146 at port 25.
    but it is not connecting. Connection timed out msg is coming.
    plz help
    Thanks in Advance

    Reply
    1. The problem is that TCP/25 the normal , un-crypted port is. So it depends on your SMTP-server-config if it allows encrypted connection or if you have to use plain connection.
      This problem does not come from the code but rather from your server-config.

      Reply
  186. Well … now … I found the problem with TSL Method.

    Your code works as follows

    -setting up a new Transport-Connection
    -connecting the Transport-Object
    so far so good
    but then your code goes wrong
    -using the static method Transport.send(Message)
    The Doc says : this method handles its OWN connection
    So why this is the reason for failure ?
    Because there no information in the Properties wich Username nor wich Password to use. So to fix this there two ways:
    1) setting up the properties correct and delete the whole manual connection set-up
    2) using SMTPTransport.sendMessage(Message, Address[]) to send the message

    and finaly clean up the connection by invoking CLOSE()

    to use the 2nd method you need to set-up a SMTPTransport or a SMTPSSLTransport with properties wich contains the TSL information and then invoke Service.connect(String, int, String, String)

    a working example with TSL

    // simplyfied package-imports
    import java.util.*;
    import javax.mail.*;
    import javax.mail.internet.*;
    public class SendMailTLS
    {
    	// simplyfied Exception-handling by simple throwing
    	public static void main(String[] args) throws Exception
    	{
    		// setting up connection parameters
    		String host="smtp.gmail.com";
    		int port=587;
    		String user="username";
    		String pass="password";
    		
    		// setting up security properties
    		Properties props=new Properties();
    		props.put("mail.smtp.auth", "true");
    		props.put("mail.smtp.starttls.enable", "true");
    		
    		// setting up connection to SMTP-Server and connect
    		Session session=Session.getInstance(props);
    		Transport transport=session.getTransport("smtp");
    		transport.connect(host, port, user, pass);
    		
    		// building Address-Array with recipients
    		// for more than one address seperate them by simple comma
    		Address[] addresses=InternetAddress.parse("[email protected]");
    		
    		// setting up new MimeMessage
    		Message message=new MimeMessage(session);
    		
    		// setting the FROM-Header wich should equal to username
    		message.setFrom(new InternetAddress(user));
    		
    		// setting the TO-Headder
    		// CC and BCC must set with seperate setRecipents() calls
    		message.setRecipients(Message.RecipientType.TO, addresses);
    		
    		// setting subject
    		message.setSubject("TEST SUBJECT");
    		
    		// constructing text/plain body of mail
    		// for text/html mail ask google =D
    		message.setText("text/plain BODY");
    		
    		// sending message with connected Transport
    		transport.sendMessage(message, addresses);
    		
    		// printing status if success
    		System.out.println("SEND");
    		
    		// closing Transport-connection clean
    		transport.close();
    	}
    }

    hope this helps

    Reply
  187. finaly

    got it work with the other SMTP-Server web.de

    simply used TLS-version with changes as i said …

    Reply
  188. addition

    please add comment that G-Mail only works on Port 465 for SSL Method !!

    Reply
  189. Sorry … hit RETURN to fast … my bad

    what i want to say :

    SSL works fine with G-Mail … but not with some other Servers … tried 465 and 587 as port value …
    error :
    javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
    Server : web.de *germany*

    TLS doesnt work at all

    always get this

    javax.mail.AuthenticationFailedException: failed to connect, no password specified?

    i am Java-Programmer for 6 years now … and i know what these exceptions mean … but i dont know WHY they are thrown …

    any ideas ?

    Reply
    1. found a solution for TLS-Method

      simply use the SSL-Class
      BUT
      -remove the SSL-Factory-Settings
      -set Port to 587
      -add the StartTLS-line from TLS-Class to it

      DONE

      the TLS-Method seems to have bugs in the connect()-Method

      Reply
  190. Hello sir,i went to send mail in my email id with help of java.mail,for this code use by me is following

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

    public class Main {

    public static void main(String[] args) {
    String host = “smtp.gmail.com”;
    int port = 587;
    String username = “ajitsingh17985”;
    String password = “557216557216”;

    Properties props = new Properties();
    props.put(“mail.smtp.auth”, “true”);
    props.put(“mail.smtp.starttls.enable”, “true”);

    Session session = Session.getInstance(props);

    try {

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(“gmail.com”));
    message.setRecipients(Message.RecipientType.TO,
    InternetAddress.parse(“gmail.com”));
    message.setSubject(“Testing Subject”);
    message.setText(“Dear Mail Crawler,” +
    “\n\n No spam to my email, please!”);

    Transport transport = session.getTransport(“smtp”);
    transport.connect(host, port, “ajitsingh17985”, “557216557216”);

    Transport.send(message);

    System.out.println(“Done”);

    } catch (MessagingException e) {
    throw new RuntimeException(e);
    }
    }
    }

    and it not works for me error is:-

    at mail.Main.main(Main.java:43)
    Caused by: javax.mail.AuthenticationFailedException: failed to connect, no password specified?
    at javax.mail.Service.connect(Service.java:329)
    at javax.mail.Service.connect(Service.java:176)
    at javax.mail.Service.connect(Service.java:125)
    at javax.mail.Transport.send0(Transport.java:194)
    at javax.mail.Transport.send(Transport.java:124)
    at mail.Main.main(Main.java:37)
    Java Result: 1
    BUILD SUCCESSFUL (total time: 6 seconds)

    Please help me

    Reply
  191. Hi All

    Can you help me this problem?

    That is: I want send mail from any address mail to a static address mail using stmp. How can I code? Thanks!

    Reply
    1. Addition…
      That’s: Any Address From Email has not
      Authentication but it can send mail. Please help me!

      Reply
    2. You need to code it yourself, and tell me what’s your problem. Not asking others to do it for you.

      Reply
      1. Hi mkyong

        I had code as:

        Properties props = new Properties();
        props.put(“mail.smtp.host”, “mailserver.com”);
        Session s = Session.getInstance(props,null);

        InternetAddress from = new InternetAddress(dynamic_email);// get customer input
        InternetAddress to = new InternetAddress([email protected]”); //this’s my email

        MimeMessage message = new MimeMessage(s);
        message.setFrom(from);
        message.addRecipient(Message.RecipientTy

        pe.TO, to);

        message.setSubject(“Your subject”);
        message.setText(“Your text”);
        Transport.send(message);

        But it is not send mail, Please help me! thanks so much!

        Reply
          1. Error: authentication require.

            Now I want receive mail from any client will send for me, my account email is Gmail. How should I code for the correct?

          2. Hi mkyong

            I have been coding as:

             
            import java.util.Properties;
            import javax.mail.Message;
            import javax.mail.MessagingException;
            import javax.mail.Session;
            import javax.mail.Transport;
            import javax.mail.internet.InternetAddress;
            import javax.mail.internet.MimeMessage;
             
            public class SendMailTLS {
             
            	public void receiveMailFromClient(String mailclient, String subject, String content) {
            		String host = "smtp.gmail.com";
            		int port = 587;
            		String username = "[email protected]";
            		String password = "123456";
             
            		Properties props = new Properties();
            		props.put("mail.smtp.auth", "true");
            		props.put("mail.smtp.starttls.enable", "true");
             
            		Session session = Session.getInstance(props);
             
            		try {
             
            			Message message = new MimeMessage(session);
            			message.setFrom(new InternetAddress(mailclient));
            			message.setRecipients(Message.RecipientType.TO,
            				InternetAddress.parse("[email protected]"));
            			message.setSubject(subject);
            			message.setText(content);
            );
             
            			Transport transport = session.getTransport("smtp");
            			transport.connect(host, port, username, password);
             
            			Transport.send(message);
             
            			System.out.println("Done");
             
            		} catch (MessagingException e) {
            			throw new RuntimeException(e);
            		}
            	}
            }
            

            Now I call method above: receiveMailFromClient(“[email protected]”,”Hello Mydream”,”How are you?”);

            But I had not been received mail from any client sent for me. Can you help

  192. 2nd one worked for me….thanks buddy……………………………..

    Reply
  193. .. hello guys the second example works for me….
    i just get that codes and paste to my struts 2 application
    and it did fine thanks for the codes…
    I’m a 17 years old programmer ….
    Looking forward for being a good programmer surfing only in
    the internet..

    Reply
    1. Nice to meet you, wonder a 17 years old guy will interest at programming. When i was 17, I just know to use computer to play game :p

      Reply
  194. Thank you so much, the 2nd program works. The first one doesn’t seem to work.

    Reply
  195. thanks,
    mkyong
    finally i succeed thanks a lot buddy really u did a nice work i never forgot u……
    I used SSL its worked yar

    Reply
  196. Hi Mkyong,

    I am new to Java and tried your TLS version, as I need to add an email function to an existing app. I am getting the following error. I have sent the code I am using as well. Any help or comments are greatly appreciated.

    Thanks,

    Michael

    Java -cp c:/fis/jre/lib/rt.jar;/fis/lib/mail.jar;/fis/jre/lib/jsse.jar;/fis/lib/xerces.jar;/fis/jre/lib/jce.jar;/fis/jre/lib/sunrsasign.jar;/fis/lib/com.checksol.dex.gateway_v1r1m1f1.jar;/fis/lib/importscrubber.jar;/fis/lib/bcel.jar;/fis/lib/junit.jar;/fis/lib/DoxygenTask.jar;/fis/lib/jalopy-ant-bundle-0.5.2.jar;/fis/lib/jdepend.jar;/fis/lib/xalan.jar;/fis/lib/jaxen-full.jar;/fis/lib/saxpath.jar;/fis/lib/Quick4rt.jar;/fis/lib/regexp.jar;/fis/lib/mail.jar;/fis/lib/mailapi.jar;/fis/lib/activation.jar;/fis/lib/smtp.jar;/fis/lib/tools.jar; SendTLS/SendMailTLS

    DEBUG: setDebug: JavaMail version 1.3
    DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.s
    mtp.SMTPTransport,Sun Microsystems, Inc]
    DEBUG SMTP: useEhlo true, useAuth true
    DEBUG: SMTPTransport trying to connect to host “smtp.gmail.com”, port 5
    DEBUG SMTP RCVD: 220 mx.google.com ESMTP g3sm226831vce.18
    DEBUG: SMTPTransport connected to host “smtp.gmail.com”, port: 587
    DEBUG SMTP SENT: EHLO NISTEST
    DEBUG SMTP RCVD: 250-mx.google.com at your service, [4.58.28.162]
    250-SIZE 35882577
    250-8BITMIME
    250-STARTTLS
    250 ENHANCEDSTATUSCODES
    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: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.s
    mtp.SMTPTransport,Sun Microsystems, Inc]
    DEBUG SMTP: useEhlo true, useAuth true
    Exception in thread “main” java.lang.RuntimeException: javax.mail.SendF
    ption: Sending failed;
    nested exception is:
    class javax.mail.AuthenticationFailedException
    at SendTLS.SendMailTLS.main(SendMailTLS.java:47)
    Caused by: javax.mail.SendFailedException: Sending failed;
    nested exception is:
    class javax.mail.AuthenticationFailedException
    at javax.mail.Transport.send0(Transport.java:218)
    at javax.mail.Transport.send(Transport.java:80)
    at SendTLS.SendMailTLS.main(SendMailTLS.java:42)

     package SendTLS;
    
    
    
    import java.util.Properties;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    
    
    
    public class SendMailTLS {
    
    	public static void main(String[] args) {
    		String host = "smtp.gmail.com";
    		int port = 587;
    		String username = "mygmailaccount";
    		String password = "mypassword";
    
    		Properties props = new Properties();
    		props.put("mail.smtp.auth", "true");
    		props.put("mail.smtp.starttls.enable", "true");
    
    		Session session = Session.getInstance(props);
    		session.setDebug(true);
    		try {
    
    			Message message = new MimeMessage(session);
    			message.setFrom(new InternetAddress("[email protected]"));
    			message.setRecipients(Message.RecipientType.TO,
    				InternetAddress.parse("[email protected]"));
    			message.setSubject("Testing Subject");
    			message.setText("Dear Mail Crawler," +
    					"\n\n No spam to my email, please!");
    
    			Transport transport = session.getTransport("smtp");
    			transport.connect(host, port, username, password);
    
    			Transport.send(message);
    
    			System.out.println("Done");
    
    		} catch (MessagingException e) {
    			throw new RuntimeException(e);
    		}
    	}
    }
    
    Reply
  197. Hi Mkyong!
    Thanks for the SSL codes, it works for me.
    I also added a file attachment option.
    I run it in a JSP file on Tomcat 6.0 local host server. My question is “how can I publish it on a distant server? Does it require a simple configuration?”

     	package orthogonal.tags.model;
    
    	import java.util.Properties;
    	import javax.activation.DataHandler;
    	import javax.activation.DataSource;
    	import javax.activation.FileDataSource;
    	import javax.mail.BodyPart;
    	import javax.mail.Message;
    	import javax.mail.MessagingException;
    	import javax.mail.Multipart;
    	import javax.mail.PasswordAuthentication;
    	import javax.mail.Session;
    	import javax.mail.Transport;
    	import javax.mail.internet.AddressException;
    	import javax.mail.internet.InternetAddress;
    	import javax.mail.internet.MimeBodyPart;
    	import javax.mail.internet.MimeMessage;
    	import javax.mail.internet.MimeMultipart;
    	 
    	public class SendMailSSLwAttach {
    		
    		public static void main(String[] args) {
    			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("yourusername","password");
    					}
    				});
    	 
    			try {
    	 
    				Message message = new MimeMessage(session);
    				message.setFrom(new InternetAddress("[email protected]"));
    				message.setRecipients(Message.RecipientType.TO,
    						InternetAddress.parse("[email protected]"));
    				message.setSubject("Testing Subject");
    				
    				 // Create a message part to represent the body text 
    		         BodyPart messageBodyPart = new MimeBodyPart(); 
    		         messageBodyPart.setText("Dear User. Here is the attachment: "); 
    		          
    		         //use a MimeMultipart as we need to handle the file attachments 
    		         Multipart multipart = new MimeMultipart(); 
    		          
    		         //add the message body to the mime message 
    		         multipart.addBodyPart(messageBodyPart); 
    		          
    		         // add any file attachments to the message 
    	             String[] attachments = {"PATH/filename.txt"}; 
    		         addAttachments(attachments, multipart); 
    		          
    		         // Put all message parts in the message 
    		         message.setContent(multipart); 
    		          
    		         // Send the message 
    		         Transport.send(message); 
    	 
    				System.out.println("Done");
    	 
    			} catch (MessagingException e) {
    				throw new RuntimeException(e);
    			}
    		}
    		
    	    protected static void addAttachments(String[] attachments, Multipart multipart) 
             throws MessagingException, AddressException { 
    	    	 for(int i = 0; i<= attachments.length -1; i++) { 
    	    		 String filename = attachments[i]; 
    	    		 MimeBodyPart attachmentBodyPart = new MimeBodyPart(); 
      
    	    		 //use a JAF FileDataSource as it does MIME type detection 
    	    		 DataSource source = new FileDataSource(filename); 
    	    		 attachmentBodyPart.setDataHandler(new DataHandler(source)); 
      
    	    		 //assume that the filename you want to send is the same as the 
    	    		 //actual file name - could alter this to remove the file path 
    	    		 attachmentBodyPart.setFileName(filename); 
      
    	    		 //add the attachment 
    	    		 multipart.addBodyPart(attachmentBodyPart); 
    	    	 } 
    	    } 
    	
    	}// end of class 
    Reply
  198. … hello guys i have an error like this…

     javax.mail.MessagingException: 530 authentication required - for help go to http://help.yahoo.com/help/us/mail/pop/pop-11.html 
    
    Reply
    1. authentication required, obviously, make sure you are using correct username and password.

      Reply
  199. Hi, i’ve tried the both TLS and SSL, no one worked….please if you have any idea of what the problem is then please help me!
    that what i get when i run the SSL :

    Exception in thread “main” java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream
    at javax.mail.Session.loadProvidersFromStream(Session.java:928)
    at javax.mail.Session.access$000(Session.java:174)
    at javax.mail.Session$1.load(Session.java:870)
    at javax.mail.Session.loadResource(Session.java:1084)
    at javax.mail.Session.loadProviders(Session.java:889)
    at javax.mail.Session.(Session.java:210)
    at javax.mail.Session.getDefaultInstance(Session.java:299)
    at com.servlet.JavaMail.main(JavaMail.java:22)
    Caused by: java.lang.ClassNotFoundException: com.sun.mail.util.LineInputStream
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at sun.misc.Launcher$ExtClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    … 8 more

    And that’s what i get when i run the TLS:

    Exception in thread “main” java.lang.NoClassDefFoundError: com/sun/mail/util/BASE64EncoderStream
    at javax.mail.internet.MimeMessage.setSubject(MimeMessage.java:793)
    at javax.mail.internet.MimeMessage.setSubject(MimeMessage.java:757)
    at com.servlet.JavaMail.main(JavaMail.java:30)
    Caused by: java.lang.ClassNotFoundException: com.sun.mail.util.BASE64EncoderStream
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at sun.misc.Launcher$ExtClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    … 3 more

    please replay me!

    Reply
    1. The error messages are obvious…

      You need javaee.jar and mail.jar, both are available in JavaEE SDK.

      Reply
      1. i didn’t tried second method.
        but when i tried first method. it shows following exception.
        Seems like it need authontication
        i gave my mail id and password in the line
        in following variables
        String username = “my gmail id”;
        String password = “my password”;

        i m not sure why it is showing the exception.

        Exception in thread “main” java.lang.RuntimeException: javax.mail.AuthenticationFailedException: failed to connect, no password specified?
        at JavaMailTest.main(JavaMailTest.java:47)
        Caused by: javax.mail.AuthenticationFailedException: failed to connect, no password specified?
        at javax.mail.Service.connect(Service.java:329)
        at javax.mail.Service.connect(Service.java:176)
        at javax.mail.Service.connect(Service.java:125)
        at javax.mail.Transport.send0(Transport.java:194)
        at javax.mail.Transport.send(Transport.java:124)
        at JavaMailTest.main(JavaMailTest.java:42)

        Reply
          1. For the first example, use this instead in send:

            transport.sendMessage(message, message.getAllRecipients());

  200. pls help me out
    i m new to java
    what is this com.mkyong.common package??
    tls ??
    ssl??

    Reply
  201. hay..when i am trying this logic from my localhost laptop.
    it’s working well, but it is not working when i m uploading this logic on my hosting panel….:-(
    so any idea about this…

    Reply
  202. Thanks lot, i done my project through this coding

    thanks again,
    thusitha

    Reply
  203. dear sir,

    I am always getting the exception connection is timed out so could not connect!!!
    please help asap

    Reply
  204. It is not working when i put the code in my servlet (but no error is shown)

    Does this work for servlets or there is some workaround to make them work?

    Help appreciated.

    Reply
  205. hi,
    i am using ssl but i got an following error please help me

    Exception in thread “main” java.lang.RuntimeException: javax.mail.MessagingException: Unknown SMTP host: smtp.gmail.com;
    nested exception is:
    java.net.UnknownHostException: smtp.gmail.com
    at email.main(email.java:42)
    Caused by: javax.mail.MessagingException: Unknown SMTP host: smtp.gmail.com;
    nested exception is:
    java.net.UnknownHostException: smtp.gmail.com
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1389)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:412)
    at javax.mail.Service.connect(Service.java:288)
    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 email.main(email.java:37)
    Caused by: java.net.UnknownHostException: smtp.gmail.com
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:177)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
    at java.net.Socket.connect(Socket.java:520)
    at java.net.Socket.connect(Socket.java:470)
    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)
    … 7 more
    Java Result: 1
    BUILD SUCCESSFUL (total time: 9 seconds)

    Reply
    1. SSL example test at 26/feb/2011, with my gmail account, working fine.

      Try ping smtp.gmail.com and make sure your connection is able to access it.

      Reply
    1. i am a beginner in java.how to send mail from application use with java mail in j-seam framework & server is jboss

      Reply
  206. Hi Iam getting following error while executing code

    Exception in thread “main” java.lang.RuntimeException: javax.mail.MessagingException: Unknown SMTP host: smtp.gmail.com;
    nested exception is:
    java.net.UnknownHostException: smtp.gmail.com
    at emailtestapps.JavaMailApp2.main(JavaMailApp2.java:53)
    Caused by: javax.mail.MessagingException: Unknown SMTP host: smtp.gmail.com;
    nested exception is:
    java.net.UnknownHostException: smtp.gmail.com
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1280)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
    at javax.mail.Service.connect(Service.java:297)
    at javax.mail.Service.connect(Service.java:156)
    at javax.mail.Service.connect(Service.java:105)
    at javax.mail.Transport.send0(Transport.java:168)
    at javax.mail.Transport.send(Transport.java:98)
    at emailtestapps.JavaMailApp2.main(JavaMailApp2.java:48)
    Caused by: java.net.UnknownHostException: smtp.gmail.com
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:177)
    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:232)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1250)
    … 7 more
    Java Result: 1

    please suggest way ..

    Thanks
    Vijay

    Reply
    1. HI,
      i am also got same exception.
      could you find out the reason of that exception.
      how did u solve that problem?
      please give reply to me.

      thanks,

      Reply
    2. Your program cannot find the smtp.gmail.com host. You should configure DNS servers or use some DNS server configuration property in JavaMail.

      Reply
  207. Gmail TLS didn’t work for me. It gave me authentication failed exception as mention by yehia. So I added pass Anonymous instance of javgax.mail.Authenticator class as shown below.
    Session session = Session.getInstance(props,new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(username,
    password);
    }
    });

    It did resolved the issue but not I am getting SendFailureException as shown below:

    Exception in thread “main” java.lang.RuntimeException: javax.mail.SendFailedException: Invalid Addresses;
    nested exception is:
    com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay for [email protected]

    at com.mkyong.common.JavaMailApp1.main(JavaMailApp1.java:55)
    Caused by: javax.mail.SendFailedException: Invalid Addresses;
    nested exception is:
    com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay for @gmail.com

    at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1196)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:584)
    at javax.mail.Transport.send0(Transport.java:169)
    at javax.mail.Transport.send(Transport.java:98)
    at com.mkyong.common.JavaMailApp1.main(JavaMailApp1.java:50)
    Caused by: com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay for [email protected]

    at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1047)
    … 4 more

    Reply
  208. Hi Your JavaMailApp2.java works very well and thanks for proving here .
    You are great .

    Reply
  209. Sir,i would like to send mail via gmail using JAVAMAIL with JSP…

    Reply
  210. thank you mkyong;

    kindly help me in the following:

    i used the following code in a program, but it is showing error;

    props.put(“mail.smtp.host”, “mail.yourisp.com”);

    can you tell, what is the smtp host for gmail and how to find isp…. please help me…..

    Reply
      1. this is the error, it is showing.

        “Sending failed; nested exception is: javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25; nested exception is: java.net.SocketException: Network is unreachable: connect”

        and this is the coding:

        package com.test;

        import java.io.*;
        import java.util.*;
        import javax.mail.*;
        import javax.mail.event.*;
        import javax.mail.internet.*;

        public final class MailerBean extends Object implements Serializable {

        /* Bean Properties */
        private String to = null;
        private String from = null;
        private String subject = null;
        private String message = null;
        public static Properties props = null;
        public static Session session = null;

        static {
        /* Setting Properties for STMP host */

        props = System.getProperties();
        props.put(“mail.smtp.host”, “smtp.gmail.com”);
        session = Session.getDefaultInstance(props, null);
        }
        /* Setter Methods */
        public void setTo(String to) {
        this.to = to;
        }

        public void setFrom(String from) {
        this.from = from;
        }

        public void setSubject(String subject) {
        this.subject = subject;
        }

        public void setMessage(String message) {
        this.message = message;
        }
        /* Sends Email */
        public void sendMail() throws Exception {
        if(!this.everythingIsSet())
        throw new Exception(“Could not send email.”);
        try {
        MimeMessage message = new MimeMessage(session);
        message.setRecipient(Message.RecipientType.TO,
        new InternetAddress(this.to));
        message.setFrom(new InternetAddress(this.from));
        message.setSubject(this.subject);
        message.setText(this.message);
        Transport.send(message);
        } catch (MessagingException e) {
        throw new Exception(e.getMessage());
        }
        }

        /* Checks whether all properties have been set or not */
        private boolean everythingIsSet() {
        if((this.to == null) || (this.from == null) ||
        (this.subject == null) || (this.message == null))
        return false;

        if((this.to.indexOf(“@”) == -1) ||
        (this.to.indexOf(“.”) == -1))
        return false;

        if((this.from.indexOf(“@”) == -1) ||
        (this.from.indexOf(“.”) == -1))
        return false;

        return true;
        }
        }

        moreover, i am in need of a jsp code, that could send mail. can you help me.

        Reply
  211. i am a beginner in java…. can you please tell, how to compile and run this code.

    Reply
  212. This was extremely useful! I’ve been troubleshooting my code with the API and with examples. Yours solved my problem. Thanks

    Reply
  213. Thank you sir for the code but can u please publish the code for receiving the email.

    Reply
  214. thank you sir, but it dose not work witn me and give me this erroe:
    Exception in thread “main” java.lang.RuntimeException: javax.mail.AuthenticationFailedException: 535-5.7.1 Username and Password not accepted. Learn more at
    535 5.7.1 http://mail.google.com/support/bin/answer.py?answer=14257 g17sm4815100wee.5

    at com.mkyong.common.JavaMailAppl2.main(JavaMailAppl2.java:78)
    Caused by: javax.mail.AuthenticationFailedException: 535-5.7.1 Username and Password not accepted. Learn more at
    535 5.7.1 http://mail.google.com/support/bin/answer.py?answer=14257 g17sm4815100wee.5

    at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:648)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:583)
    at javax.mail.Service.connect(Service.java:313)
    at javax.mail.Service.connect(Service.java:172)
    at javax.mail.Service.connect(Service.java:121)
    at javax.mail.Transport.send0(Transport.java:190)
    at javax.mail.Transport.send(Transport.java:120)
    at com.mkyong.common.JavaMailAppl2.main(JavaMailAppl2.java:57)

    and I’m sure from username and password

    Reply
  215. Very good site thank you for all the content.

    Using the above email prog how would I go about adding in the ability to attach a file?

    Many thanks,

    Peter

    Reply
  216. thank you sir this example helped me a lot and is very useful
    it complete as you have shown the settings to be done on gmail for this
    purpose via link

    plz tell what should be done for rediffmail

    Reply
    1. Sorry, i dont have rediffmail account, you should check with rediffmail mail server setting and modify the code accordingly

      Reply
  217. TLS Failed for me? No tuts seem to work for GMail or Windows Live TLS :\

    Reply
  218. Thank you ! This example is very useful for me.

    Reply
  219. SSL works fine, and is very easier!!! Thanks man!

    Cheers!!

    Reply
  220. SSL worked but TLS did not worked it says the authentication failed so may i know the reason why it say so and thanks for the code it worked after i tried so many codes and each code failed except urs so thank u so much

    Reply
  221. Excellent article! I used SSL approach and able to send mail to gmail account. I was stuck in this for some time. Thanks for the help.

    Reply
      1. i have to send a mail from seam application.i used above code but it gave one exception i.e below i give.please give solution
        thanks,
        java.net.UnknownHostException: smtp.gmail.com
        04:46:42,407 ERROR [STDERR] javax.mail.MessagingException: Unknown SMTP host: smtp.gmail.com ;
        nested exception is:
        java.net.UnknownHostException: smtp.gmail.com
        04:46:42,407 ERROR [STDERR] at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1280)
        04:46:42,407 ERROR [STDERR] at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
        04:46:42,407 ERROR [STDERR] at javax.mail.Service.connect(Service.java:297)
        04:46:42,407 ERROR [STDERR] at javax.mail.Service.connect(Service.java:156)
        04:46:42,407 ERROR [STDERR] at javax.mail.Service.connect(Service.java:105)
        04:46:42,407 ERROR [STDERR] at javax.mail.Transport.send0(Transport.java:168)
        04:46:42,407 ERROR [STDERR] at javax.mail.Transport.send(Transport.java:98)
        04:46:42,423 ERROR [STDERR] at com.infyz.streamline.manager.session.MailAction.forgotUser(MailAction.java:273)
        04:46:42,423 ERROR [STDERR] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        04:46:42,423 ERROR [STDERR] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        04:46:42,423 ERROR [STDERR] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        04:46:42,423 ERROR [STDERR] at java.lang.reflect.Method.invoke(Method.java:597)
        04:46:42,423 ERROR [STDERR] at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:112)
        04:46:42,423 ERROR [STDERR] at org.jboss.ejb3.interceptor.InvocationContextImpl.proceed(InvocationContextImpl.java:166)
        04:46:42,423 ERROR [STDERR] at org.jboss.seam.intercept.EJBInvocationContext.proceed(EJBInvocationContext.java:44)

        Reply
    1. Hi,

      you said you could success in send mail.

      please can u send the which settings i have to do.

      i used above ssl code but it gives exception i.e

      # javax.mail.MessagingException: Unknown SMTP host: smtp.gmail.com;
      # nested exception is:
      # java.net.UnknownHostException: smtp.gmail.com

      please send the details ,

      thanks,

      pandu.v

      Reply

Leave a Comment

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