Thought of sharing following code with you all. It is a small code snippet that uses SMTP in Java to login into GMail and send email using ones GMail account.
String host = “smtp.gmail.com”; String from = “username”; String pass = “password”; Properties props = System.getProperties(); props.put(“mail.smtp.starttls.enable”, “true”); // added this line props.put(“mail.smtp.host”, host); props.put(“mail.smtp.user”, from); props.put(“mail.smtp.password”, pass); props.put(“mail.smtp.port”, “587”); props.put(“mail.smtp.auth”, “true”); String[] to = {“[email protected]”}; // added this line Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); InternetAddress[] toAddress = new InternetAddress[to.length]; // To get the array of addresses for( int i=0; i < to.length; i++ ) { // changed from a while loop toAddress[i] = new InternetAddress(to[i]); } System.out.println(Message.RecipientType.TO); for( int i=0; i < toAddress.length; i++) { // changed from a while loop message.addRecipient(Message.RecipientType.TO, toAddress[i]); } message.setSubject("sending in a group"); message.setText("Welcome to JavaMail"); Transport transport = session.getTransport("smtp"); transport.connect(host, from, pass); transport.sendMessage(message, message.getAllRecipients()); transport.close(); [/code] The code is pretty much self explanatory. Add your GMail username and password in line 7 and 8. [code="java"] props.put("mail.smtp.user", from); props.put("mail.smtp.password", pass); [/code] And also add the recepient email address in to array in line 12. [code="java"] String[] to = {"[email protected]"}; // added this line [/code]Code language: Java (java)
hello
hay i am patel manoj
Hai hello
Can you give us the associated JARs or the complete import statements?
Please send the jar file to my mail too: [email protected]
hey thanks for the Code dear.. its Totally workin nd onw thin is that I was lookin for this thisn since a long time but here i got the Perfect code that is Workin so that thanks a lot.. ! Take care Bye Bye
Thanks a lot for the snippet, works great. Was looking something like that for my project, you saved my time.
I’m trying to run this snippet but got the following Exception
Please help me:-
javax.servlet.ServletException: javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first. u2sm14732770pbq.9
org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:852)
org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:781)
org.apache.jsp.test_005fmail.send_jsp._jspService(send_jsp.java:133)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
com.vtr.globarena.URLCheckFilter.doFilter(URLCheckFilter.java:175)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:390)
how can i run this program using commandprompt?
how to set paths for jar files?
pls help.
Provide me the jar files used
Hi Nagaraj,
Just include mail.jar in your classpath and you will be able to compile and run the program.
Just add acitvation.jar and mail.jar
Surely u will get Proper output
search for mail.jar and activation.jar
THANKS A LOT !!!!!!!!!!
NICE JOB, THANK YOU SO MUCH,HELPED A LOT
Glad it helped, Rizwan :)
nice one pal!!!!
hey its not working for me. its getting executed but i am not receiving the mail :( any help appreciated :(
Thanks buddy…..superb code
Such a Very good Demo…. Refer this Code ….
I m getting this below error:
Exception in thread “main” java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream
at line
Session session = Session.getDefaultInstance(props, null);
Can you please look into this..
Regards
Thanks man … !!! It worked … :-)
hey the code was really useful..thank you so much
Hey could u please let me know what packages i have to import
Hey Nice post …..Working gmail sender….Cool
my mail sending code is taking 30sec-40sec for one mail.
how can i reduce this time?
how can i send mails faster using the java code?
bahut bahut thanks brother
how do i use mail functionality in my existing project and also whatever files like jar i need to run this project.
plz give a link to download them all
Nice one, It is no doubt an effective code. Thank you sooooooo much !!!! :)
You taught us something …
YOU ALL CAN DOWNLOAD THE REQUIRED 2 LIBRARIES FROM HERE :
for mail.jar click on the following link
http://www.java2s.com/Code/Jar/m/Downloadmailjar.htm
for javaee.jar
http://www.java2s.com/Code/Jar/j/Downloadjavaeejar.htm
After installation right click on your “project folder icon” which is in Package Explorer , then click on “Build Path” , then click on “configure build path” and finally click on “Import External JARs”
Hello Sir,
I am able to send email from local host but not able to send mail from server on which I host my web site.
I have used this configuration…Please check..
m_properties.put(“mail.smtp.host”, “smtp.gmail.com”);
m_properties.put(“mail.smtp.socketFactory.port”, “465”);
m_properties.put(“mail.smtp.socketFactory.class”,”javax.net.ssl.SSLSocketFactory”);
m_properties.put(“mail.smtp.auth”, “true”);
m_properties.put(“mail.smtp.port”, “465”);
i got tis error while trying it
Error 500: 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 CN=avast! Mail Scanner Root, O=avast! Mail Scanner, OU=generated by avast! antivirus for SSL scanning is not trusted; internal cause is: java.security.cert.CertPathValidatorException: Certificate chaining error
Error 500: javax.mail.MessagingException: Exception reading response; 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 [email protected], CN=FortiGate CA, OU=Certificate Authority, O=Fortinet, L=Sunnyvale, ST=California, C=US is not trusted; internal cause is: java.security.cert.CertPathValidatorException: Certificate chaining error
Exception in thread “main” javax.mail.MessagingException: Could not connect to SMTP host:
I am geeting this exception please help me
smtp.gmail.com, port: 587;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1008)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:197)
at javax.mail.Service.connect(Service.java:233)
at javax.mail.Service.connect(Service.java:134)
at com.SendMail.send(SendMail.java:58)
at com.SendMail.main(SendMail.java:66)
Hi Karthik,
I am also facing the same error. Will you please help if you have solved that one.? I spent two days over that.Your help will be most appreciated.
Lot of errors in Properties put method and showing errors for host, from, to variables.
Im beginner..
Anybody pls give some explanation to d code.. pls
Hi Girish,
Please import java.util.Properties. Your compilation will only take java.lang. Any class apart from that is being used in the class, then it must be referenced using an import statement.
You can use Ctrl+O in Eclipse to auto import the class if you have the required jars in your buildpath.
i am not able to send the mail via gmail,
The below snippent is my code:
Very informative, Thanks for sharing, But I came across another java email component by the name of Aspose.Email for Java. It enables Java applications to read and write MS Outlook MSG files from within a Java application and also support Exchange server as well. I am sure it will be helpful.
i tried your code but i am getting the following exception:
please help!!
This is really a nice article and i wanted to know that how can i send the email on specific time to the email id of the users which is stored in the database and if i can then how please help as soon as possible as i am on to the deadline of my college project….Please Help me
Thanks in Advance
Very nice, whatever the programs you add in your website’s are awesome and works as expected very nice Sir.
To
Exception in thread “main” 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 com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:1564)
at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:1551)
at com.sun.mail.smtp.SMTPTransport.ehlo(SMTPTransport.java:935)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:426)
at javax.mail.Service.connect(Service.java:288)
at javax.mail.Service.connect(Service.java:169)
at javamail.main(javamail.java:57)
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:1836)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:276)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:270)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1337)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:154)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:868)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:804)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:966)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1262)
at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:680)
at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:85)
at com.sun.mail.util.TraceOutputStream.write(TraceOutputStream.java:114)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:1562)
… 6 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:385)
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:326)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:231)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:126)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1319)
… 17 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:196)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:268)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)
… 23 more
Java Result: 1
help me i need to send the mail using java.. how can i send the mail
can u please xplain this code.
at the time sending mail its taking 60-70 seconds , please revert me if you know