Hi folks! For your convenience, I’ve hosted the source code for this article at GitHub. Please feel free to try out that code and drop me a line if you get any queries. You can access the repository here.
Sending email using Java is not a difficult task and it’s just about writing few lines of codes. But when you are writing such an application, you’ll end up with lot of exceptions obviously. There are lots of reasons for that, but as my opinion, wrong email configuration settings would cause the exceptions.
If you need to write a Java application to send an email, you need an outgoing mail server such as SMTP (Simple Mail Transfer Protocol) server. There are many SMTP servers out there, but in order to send an email most servers require authentication (You have to have an account in your SMTP server and you must know account credentials). There exist free SMTP servers without authentication, but I’m not sure about their reliability and Quality of Service (QoS).
At the authentication process, most developers fail due to bad configurations. There are several configuration settings should be set in your code, before you submit the message to the SMTP server.
To demonstrate this settings, I’ll create a Java application from the scratch and it will use Gmail as the outgoing SMTP server (You can use any SMTP server with valid credentials. But here I used Gmail because I’m addicted to Google!).
You can download the complete source code and required libraries here. I developed it using NetBeans IDE, but you can use any IDE to proceed.
Prerequisites
- JavaMail API (http://java.sun.com/products/javamail) libraries. (No need to download the libraries. I’ve included them in my sample application).
- Valid Gmail (http://www.google.com/gmail) account. (You must know the user name and the password)
Source Code
package com.dunithd.jmail; import javax.mail.*; import javax.mail.internet.*; import javax.mail.internet.MimeMessage.RecipientType; import java.util.*; /** * Simple Class to send an email using JavaMail API (javax.mail) and Gmail SMTP server * @author Dunith Dhanushka, dunithd@gmail.com * @version 1.0 */ public class GmailSender { private static String HOST = "smtp.gmail.com"; private static String USER = "your_username@gmail.com"; private static String PASSWORD = "put_your_password_here"; private static String PORT = "465"; private static String FROM = "put_from_address_here"; private static String TO = "put_to_address_here"; private static String STARTTLS = "true"; private static String AUTH = "true"; private static String DEBUG = "true"; private static String SOCKET_FACTORY = "javax.net.ssl.SSLSocketFactory"; private static String SUBJECT = "Testing JavaMail API"; private static String TEXT = "This is a test message from my java application. Just ignore it"; public static synchronized void send() { //Use Properties object to set environment properties Properties props = new Properties(); props.put("mail.smtp.host", HOST); props.put("mail.smtp.port", PORT); props.put("mail.smtp.user", USER); props.put("mail.smtp.auth", AUTH); props.put("mail.smtp.starttls.enable", STARTTLS); props.put("mail.smtp.debug", DEBUG); props.put("mail.smtp.socketFactory.port", PORT); props.put("mail.smtp.socketFactory.class", SOCKET_FACTORY); props.put("mail.smtp.socketFactory.fallback", "false"); try { //Obtain the default mail session Session session = Session.getDefaultInstance(props, null); session.setDebug(true); //Construct the mail message MimeMessage message = new MimeMessage(session); message.setText(TEXT); message.setSubject(SUBJECT); message.setFrom(new InternetAddress(FROM)); message.addRecipient(RecipientType.TO, new InternetAddress(TO)); message.saveChanges(); //Use Transport to deliver the message Transport transport = session.getTransport("smtp"); transport.connect(HOST, USER, PASSWORD); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { GmailSender.send(); System.out.println("Mail sent successfully!"); } }
When writing the application, you have to set some Environment Properties that are used by the JavaMail APIs. The JavaMail javadocs contain additional information on properties supported by JavaMail.
You can use java.util.Properties class to set these properties.
- mail.smtp.host: Specifies the protocol-specific default Mail server. In your application, set this property to smtp.gmail.com
- mail.smtp.user: Specifies the protocol-specific default username for connecting to the Mail server. In your application, set this property to your Gmail username.
- mail.smtp.auth: Specifies whether host requires authentication or not. In our application, set this property to true.
- mail.smtp.debug: Specifies the initial debug mode. Setting this property to true will turn on debug mode, while setting it to false turns debug mode off. If you need deeper diagnosis, set this to true.
- mail.smtp.port: Specifies the port that is used by SMTP server. In your application, set this to 465.
- mail.smtp.starttls.enable: This is the most important one. If you miss this, you’ll definitely get an error. Most SMTP servers support SSL (Secure Socket Layer) connections which can be used for secure login to the server. They use STARTTLS command (see RFC 2487 and RFC 3501) to switch the connection to be secured by TLS.
Use of the STARTTLS command is preferred in cases where the server supports both SSL and non-SSL connections. This SSL/TLS support in JavaMail works only when JavaMail is used on a version of J2SE that includes SSL support.
The STARTTLS support is available in the standard “IMAP” and “SMTP” protocols, but must be enabled by setting the appropriate property, mail.imap.starttls.enable or mail.smtp.starttls.enable, to “true”. When set, if the server supports the STARTTLS command, it will be used after making the connection and before sending any login information.
If everything goes fine, you’ll see an output like this.
Notes
This application cannot be used in a network that uses a proxy server. You must have a direct connection to the internet otherwise you’ll get UnknownHostException.
In my next post, I’m gonna explain you how to send an email with an attachment.
How do you enforce TLS? For instance, when you set mail.smtp.starttls.enable to “true” it will use the secure connection, if it’s available. Otherwise, it just sends unsecure. How do I make it so that it only sends if TLS connection is available?
Good article..please keep it….some article i have posted in gananathsun.blogspot.com
Thanks Gananath!…
Thank you very much!!! It pulled me out from bad situation. Thanks.
Very useful article. Thanks bro.
Thanks Kanishka!….
Finally smth that works! excellent ! 🙂
Nice to hear that. Thanks!
dunithd, how do we change the TO: string to specify multiple recipients?
Hey Arthur,
That can be done in this way…
first, change the TO string to contain your recipient addresses. Just concatenate the addresses with comma and a space
eg: String TO = “john@gmail.com, arthur@gmail.com, foo@ymail.com“;
Then replace the method message.addRecipient() with this(see line number 57)
message.addRecipients(RecipientType.TO, TO);
Thats it and you are done!
very very ….Thanks Mr.Dunithd
You welcome Mahendra!
budy can u post me a program which is used to retrieve the mail from the gmail account
I am trying to call your program in JSP page using following code.but it gives the error
JSP Page
Hello World!
it gives me following output in netbeans 6.8
Hello World!
com.myapp.struts.GmailSender@357bdf
it gives me following error in eclipse
org.apache.jasper.JasperException: /page4.jsp(6,1) Page directive: illegal to have multiple occurrences of contentType with different values (old: text/html; charset=ISO-8859-1, new: text/html)
org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:40)
org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:407)
org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:236)
org.apache.jasper.compiler.Validator$DirectiveVisitor.visit(Validator.java:132)
org.apache.jasper.compiler.Node$PageDirective.accept(Node.java:608)
org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2361)
org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2411)
org.apache.jasper.compiler.Node$Visitor.visit(Node.java:2417)
org.apache.jasper.compiler.Node$Root.accept(Node.java:495)
org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2361)
org.apache.jasper.compiler.Validator.validateDirectives(Validator.java:1723)
org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:182)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:347)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:327)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:314)
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:592)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:317)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
note The full stack trace of the root cause is available in the Apache Tomcat/6.0.29 logs.
this is the program i am using
JSP Page
Hello World!
it is working now.. thanks
This a nice piece. You are good.
Thanks Oc!
thanks a lot for such a useful piece of code.
Hi,
How can you change this code to work under network that uses a proxy server….?
Thanks!
Hi Chathuranga,
Please refer to my blog post https://dunithd.wordpress.com/2009/11/14/send-e-mail-using-javamail-from-behind-a-proxy-server/
extremely perfect article… keep it up
Thanks Akhtar!
Good article..please keep it…but when i sent mail to yahoo it goes to spam folder.. Plz help how to resolve..
i just modify Transport transport = session.getTransport(“smtp”); to
Transport transport = session.getTransport(“smtps”);
Thanks for this share, actually i am searching for a mail sending program with javamail api. thanks
Thanks sreejesh!
thanks for ur article u solved a big problem for me i appreciate that but please i wanna send a link in the email how i can do it??!! and thanks a lot 🙂
Adding a hyper link is a not a difficult task in JavaMail.
Say for example you want to insert a link to http://www.google.com.
Then all you have to do is place the necessary HTML in a String.
Eg: Visit Google
Note that do the String escaping.
since you are using java.mail, you should set the text this way:
message.setText(body, "UTF-8", "html");
thanks
brillant !!!! it work for me thanks u very much
Thanks daz!
i`ve got this error
DEBUG: setDebug: JavaMail version 1.4.4
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host “smtp.gmail.com”, port 465, isSSL false
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.net.SocketException: Connection reset
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1934)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:638)
at javax.mail.Service.connect(Service.java:295)
………………..
what should i do ?
thx for advice
Seems like you are having a network issue that prevents you from connecting to the Google’s SMTP server. Please check your proxy settings and adjust them accordingly.
i’ve got the same error… im not using proxy… im using 3g connection.
what should i do to solve this problem?
thanks a lot…… thank u very much
Thanks!
Thanks very much brother! This article is good.
Hi, I apriciate your article, but i got this error: 530 5.7.0 Must issue a STARTTLS command first. f17sm709927ani.25, could you help me?, please, thanks a lot
WooooW
What a great topic
thank u it is very helpful
thanx sir 4 this code………
Thanx Sir. It is very nice article. Can u tell me how to attach the multiple files while sending the mail…
Thanks mr7l1v35!
Please refer to my this blog post for attaching multiple files.
regards,
Dunith
Hi Everybody,
I have very complicated requirement.. Please share your thoughts on this..
In a java application, users has to register themeless with their email ids (could be gmail, yahoo or any other).. After registration and login, they can perform some of the activities. In a particular activity user will be accepting certain conditions by clicking a button and an email should be sent from java application.. The twist here is email should go directly from registered user gmail, yahoo or any other email ids to concerned party… i.e. after clicking a button in the java application, registered user should have the mail that has been sent from java application in their Sent Mail box ( like gmail, yahoo or any other).. Something like the registered user logging into his gmail account and sending an email..
Please need help on this..
Rgds,
Ramachandran
Thank you for the posting. Its very useful for me… Can you post a simple program for file uploading???
Thanks Venkatesh,
I’ll do a one soon.
Dear I am having javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first error when I am trying to send a mail from my office. But is is working fine with my office PC.
Should I change any setting in my home PC regarding STARTTLS.
Please let me know what should I do?
Hi, I apriciate your article, but i got this error: 530 5.7.0 Must issue a STARTTLS command first. f17sm709927ani.25, could you help me?, please, thanks a lot
i just have to say , Ummmmmmmmaahh , Love you aiya…. 🙂
thanks you very much
Thanks a lot 🙂 🙂
Great! This work perfectly. Thanks you very much.
hey thanks 🙂 i search for a working code whole day 🙂
this works well thankz alot
Thank you so much for this! 😀
Thank you.
package com.mail;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.internet.MimeMessage.RecipientType;
import java.util.*;
public class GmailSender {
private static String HOST = “smtp.gmail.com”;
private static String USER = “XXXXX@gmail.com”;
private static String PASSWORD = “**********”;
private static String PORT = “465”;
private static String FROM = “XXXXXX@gmail.com”;
private static String TO = “XXXXXXX@gmail.com”;
private static String STARTTLS = “true”;
private static String AUTH = “true”;
private static String DEBUG = “true”;
private static String SOCKET_FACTORY = “javax.net.ssl.SSLSocketFactory”;
private static String SUBJECT = “Testing JavaMail API”;
private static String TEXT = “This is a test message from my java application. Just ignore it”;
public static synchronized boolean send() {
// Use Properties object to set environment properties
Properties props = new Properties();
props.put(“mail.smtp.host”, HOST);
props.put(“mail.smtp.port”, PORT);
props.put(“mail.smtp.user”, USER);
props.put(“mail.smtp.auth”, AUTH);
props.put(“mail.smtp.starttls.enable”, STARTTLS);
props.put(“mail.smtp.debug”, DEBUG);
props.put(“mail.smtp.socketFactory.port”, PORT);
props.put(“mail.smtp.socketFactory.class”, SOCKET_FACTORY);
props.put(“mail.smtp.socketFactory.fallback”, “false”);
try {
// Obtain the default mail session
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(USER, PASSWORD);
}
});
session.setDebug(true);
// Construct the mail message
MimeMessage message = new MimeMessage(session);
message.setText(TEXT);
message.setSubject(SUBJECT);
message.setFrom(new InternetAddress(FROM));
message.addRecipient(RecipientType.TO, new InternetAddress(TO));
message.saveChanges();
// Use Transport to deliver the message
Transport transport = session.getTransport(“smtp”);
transport.connect(HOST, USER, PASSWORD);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
public static void main(String[] args) {
boolean flag = GmailSender.send();
if (flag) {
System.out.println(“Mail sent successfully!”);
} else {
System.out.println(“Mail not sent!”);
}
}
}
the above code gives the below Exception… can any one help me to resolve this issue please…….
DEBUG: setDebug: JavaMail version 1.4.4
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host “smtp.gmail.com”, port 465, isSSL false
220 mx.google.com ESMTP kt2sm4702869pbc.73
DEBUG SMTP: connected to host “smtp.gmail.com”, port: 465
EHLO desktop
250-mx.google.com at your service, [183.82.97.186]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH
250-ENHANCEDSTATUSCODES
250 PIPELINING
DEBUG SMTP: Found extension “SIZE”, arg “35882577”
DEBUG SMTP: Found extension “8BITMIME”, arg “”
DEBUG SMTP: Found extension “AUTH”, arg “LOGIN PLAIN XOAUTH”
DEBUG SMTP: Found extension “ENHANCEDSTATUSCODES”, arg “”
DEBUG SMTP: Found extension “PIPELINING”, arg “”
DEBUG SMTP: Attempt to authenticate
DEBUG SMTP: check mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM
AUTH LOGIN
334 VXNlcm5hbWU6
c3VkaGFrYXIua2FpdGhlcGFsbGlAZ21haWwuY29t
334 UGFzc3dvcmQ6
ODEyMTMxNTI0MA==
535-5.7.1 Application-specific password required. Learn more at
535 5.7.1 http://support.google.com/accounts/bin/answer.py?answer=185833 kt2sm4702869pbc.73
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host “smtp.gmail.com”, port 465, isSSL false
220 mx.google.com ESMTP ka9sm4706755pbb.59
DEBUG SMTP: connected to host “smtp.gmail.com”, port: 465
EHLO desktop
250-mx.google.com at your service, [183.82.97.186]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH
250-ENHANCEDSTATUSCODES
250 PIPELINING
DEBUG SMTP: Found extension “SIZE”, arg “35882577”
DEBUG SMTP: Found extension “8BITMIME”, arg “”
DEBUG SMTP: Found extension “AUTH”, arg “LOGIN PLAIN XOAUTH”
DEBUG SMTP: Found extension “ENHANCEDSTATUSCODES”, arg “”
DEBUG SMTP: Found extension “PIPELINING”, arg “”
DEBUG SMTP: Attempt to authenticate
DEBUG SMTP: check mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM
AUTH LOGIN
334 VXNlcm5hbWU6
c3VkaGFrYXIua2FpdGhlcGFsbGlAZ21haWwuY29t
334 UGFzc3dvcmQ6
ODEyMTMxNTI0MA==
535-5.7.1 Application-specific password required. Learn more at
535 5.7.1 http://support.google.com/accounts/bin/answer.py?answer=185833 ka9sm4706755pbb.59
javax.mail.AuthenticationFailedException: 535-5.7.1 Application-specific password required. Learn more at
535 5.7.1 http://support.google.com/accounts/bin/answer.py?answer=185833 ka9sm4706755pbb.59
Mail not sent!
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 com.mail.GmailSender.send(GmailSender.java:63)
at com.mail.GmailSender.main(GmailSender.java:75)
“535-5.7.1 Application-specific password required. Learn more at…”
Later Google has updated their security policies to support two step authentication. Because of that Google treats this code as seperate application and it requires application specific password.
Login to you gmail account, go to Account -> Security and edit Authorizing applications and sites to provide a password for this script.
I’ve read some excellent stuff here. Certainly price bookmarking for revisiting. I wonder how much attempt you put to make this sort of magnificent informative web site.
Thanks Lista!
Hey good code.. can you please help me to send an attachment to many email addresses??
can you help me?
This is the configuration of my outlook client however i can´t connect
Nombre de servidor: pod51011.outlook.com
Puerto: 587
javax.mail.MessagingException: Could not connect to SMTP host: pod51011.outlook.com, port: 587
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:855)
Tanks
Make sure you are not behind a firewall when sending email.
-Dunith
my internet is totally free
the account is created with all permissions
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG: SMTPTransport trying to connect to host “pod51011.outlook.com”, port 587
DEBUG SMTP RCVD: 220 pod51011.outlook.com Microsoft ESMTP MAIL Service ready at Fri, 15 Feb 2013 18:32:20 +0000
DEBUG: SMTPTransport connected to host “pod51011.outlook.com”, port: 587
DEBUG SMTP SENT: EHLO SECTECSISTEMAS
DEBUG SMTP RCVD: 250-pod51011.outlook.com Hello [189.203.229.110]
250-SIZE 36700160
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-STARTTLS
250-AUTH
250-8BITMIME
250-BINARYMIME
250 CHUNKING
DEBUG SMTP Found extension “SIZE”, arg “36700160”
DEBUG SMTP Found extension “PIPELINING”, arg “”
DEBUG SMTP Found extension “DSN”, arg “”
DEBUG SMTP Found extension “ENHANCEDSTATUSCODES”, arg “”
DEBUG SMTP Found extension “STARTTLS”, arg “”
DEBUG SMTP Found extension “AUTH”, arg “”
DEBUG SMTP Found extension “8BITMIME”, arg “”
DEBUG SMTP Found extension “BINARYMIME”, arg “”
DEBUG SMTP Found extension “CHUNKING”, arg “”
DEBUG SMTP: Attempt to authenticate
DEBUG SMTP: use8bit false
DEBUG SMTP SENT: MAIL FROM:
DEBUG SMTP RCVD: 530 5.7.1 Client was not authenticated
javax.mail.MessagingException: 530 5.7.1 Client was not authenticated
at com.sun.mail.smtp.SMTPTransport.issueCommand(SMTPTransport.java:879)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:599)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:319)
at mx.gob.sefiplan.Pruebas.GmailSender.send(GmailSender.java:63)
at mx.gob.sefiplan.Pruebas.GmailSender.main(GmailSender.java:73)
Right here is the perfect web site for anyone who really wants to
find out about this topic. You realize a whole lot its
almost hard to argue with you (not that I really would want to…HaHa).
You definitely put a new spin on a subject that has been written about for decades.
Great stuff, just wonderful!
Appretiate it! 🙂
The code works well.. But ive tried it in jsp using Beans.. There is a small issue in this.. I didn get any mail when i give it in html..
Could you please post your code here?
i am getting the error
javax.mail.NoSuchProviderException: smtp
at javax.mail.Session.getService(Session.java:784)
at javax.mail.Session.getTransport(Session.java:720)
at javax.mail.Session.getTransport(Session.java:660)
at javax.mail.Session.getTransport(Session.java:640)
at com.sample.dao.emailTry.send(emailTry.java:60)
at com.sample.dao.emailTry.main(emailTry.java:72)
plz tell me how to solve it
hey jar files not avail buddy:(
hello…plz send me the source code of send email with attachment….its important n urgent..thanks
id:bhoomigolaviya@gmail.com
whats the solution of this lots of errors….anyone have d solution plzz suggest me….
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:1963)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
at javax.mail.Service.connect(Service.java:345)
at javax.mail.Service.connect(Service.java:226)
at filetransfer.Main.sendmessage(Main.java:74)
at filetransfer.NewJFrame.sendActionPerformed(NewJFrame.java:196)
at filetransfer.NewJFrame.access$200(NewJFrame.java:21)
at filetransfer.NewJFrame$3.actionPerformed(NewJFrame.java:83)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6290)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6055)
at java.awt.Container.processEvent(Container.java:2039)
at java.awt.Component.dispatchEventImpl(Component.java:4653)
at java.awt.Container.dispatchEventImpl(Container.java:2097)
at java.awt.Component.dispatchEvent(Component.java:4481)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4575)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4236)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4166)
at java.awt.Container.dispatchEventImpl(Container.java:2083)
at java.awt.Window.dispatchEventImpl(Window.java:2482)
at java.awt.Component.dispatchEvent(Component.java:4481)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:648)
at java.awt.EventQueue.access$000(EventQueue.java:84)
at java.awt.EventQueue$1.run(EventQueue.java:607)
at java.awt.EventQueue$1.run(EventQueue.java:605)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
at java.awt.EventQueue$2.run(EventQueue.java:621)
at java.awt.EventQueue$2.run(EventQueue.java:619)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:618)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
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(Alerts.java:174)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1731)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:241)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:235)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1206)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:136)
at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:593)
at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:529)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:925)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1170)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1197)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1181)
at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:528)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:333)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:208)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1927)
… 43 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:323)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:217)
at sun.security.validator.Validator.validate(Validator.java:218)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:126)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:209)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:249)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1185)
… 54 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:174)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:238)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:318)
… 60 more
thank u friend u done smart work
i have got this error
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
how can i solve it?
Thanks Sir it is very useful to me.
Thanks a lot for such a good article.
how to attach files in this code
You may refer to this post https://dunithd.wordpress.com/2009/11/14/send-e-mail-with-attachments-using-javamail/
MUCHAS GRACIAS EL PROBLEMA DE :
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
ES DEBIDO A EL ANTIVIRUS O EL FIREWALL REVISAR O DESABILITAR
FUNCIONA PERFECTO!!
Sorry, my Spanish is very poor. Could you comment in English please? 🙂
Thanks,
Dunith
how can I attach files with this program
how to attach files to this program?
Hi Sinto,
Please refer my other blog post on sending emails with attachments. http://wp.me/p9Njt-1d
Regards,
Dunith
thank u very much sir
I am trying to implement a same code..but getting a error it may be tls/ssl error of cannot convert socket to tls..no target found..cud u resolve the certificate issue.
Hi, i appreciate you code but when run it, i get lots of erroring :
DEBUG: setDebug: JavaMail version 1.5.1
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host “smtp.gmail.com”, port 465, isSSL false
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
Mail sent successfully!
nested exception is:
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1986)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:656)
at javax.mail.Service.connect(Service.java:345)
at javax.mail.Service.connect(Service.java:226)
at project.Sendemail.send(Sendemail.java:58)
at project.Sendemail.main(Sendemail.java:69)
Caused by: javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
at sun.security.ssl.InputRecord.handleUnknownRecord(InputRecord.java:541)
at sun.security.ssl.InputRecord.read(InputRecord.java:374)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:927)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1328)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1355)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:532)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:337)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:208)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1950)
… 5 more
BUILD SUCCESSFUL (total time: 1 second)
I am not quite sure what it means and was wondering if you can help out. Thanks
Hi Jex,
This is due to the fact that you are talking to an HTTP server, not an HTTPS server. Did you use the correct port number for HTTPS?
Regards,
Dunith
thank you helpful article 🙂
hi Dunith,
Primarily Thanks for sharing this knowledge.
But i am getting some Error like this
In your code i just changed the name of the class
and Login Credentials only
I hope this is not affected to this error
——————————————————
Output in Netbeans :::::::::::
——————————————————-
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: trying to connect to host “smtp.gmail.com”, port 465, isSSL false
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.net.ConnectException: Connection timed out: connect
Regards::
AKHIL
thank you soooooooooooo much its working successfully sir I M VERY HAPPY ABOUT THAT