sending/ receiving email in Java

I want to send email through Java (Any email like from yahoo, gmail, or any other part).

I tried the code give here, however I get exception as

javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25; nested exception is: java.net.ConnectException: Connection refused 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:295) 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 myemailtesting.MyEmailTesting.main(MyEmailTesting.java:72) Caused by: java.net.ConnectException: Connection refused 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:432) 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:319) at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:233) at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1938) ... 7 more

Code I have is

/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package myemailtesting; /** * * @author xxxx */ 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 MyEmailTesting { public static void main(String[] args) { System.out.println("This is EMAIL testing!!!"); // Recipient's email ID needs to be mentioned. String to = "xx@gmail.com"; // Sender's email ID needs to be mentioned String from = "xx@gmail.com"; // Assuming you are sending email from localhost String host = "localhost"; // Get system properties System.out.println("test 001"); Properties properties = System.getProperties(); System.out.println("test 002"); // Setup mail server System.out.println("test 003"); properties.setProperty("mail.smtp.host", host); // Get the default Session object. System.out.println("test 004"); Session session = Session.getDefaultInstance(properties); try { // Create a default MimeMessage object. System.out.println("test 005"); MimeMessage message = new MimeMessage(session); System.out.println("test 006"); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); System.out.println("test 007"); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); System.out.println("test 008"); // Set Subject: header field message.setSubject("This is the Subject Line!"); System.out.println("test 009"); // Now set the actual message message.setText("This is actual message"); System.out.println("test 010"); // Send message Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException mex) { mex.printStackTrace(); } } }

For de-bugging I was using stateement as System.out.println("test 00X");

I got output as

This is EMAIL testing!!! test 001 test 002 test 003 test 004 test 005 test 006 test 007 test 008 test 009 test 010 javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;

I tried many codes but I am not getting any output. Getting some exception.

I see at some place, I need to keep SMTP server UP. I don't know what needs to be done. I believe apache commons will be good option.

Could someone help me in below steps

<ol> <li>jar files that are needed</li> <li>how to setup smptp</li> <li>send email (from any site i.e. from yahoo or gmail or any private email id)</li> </ol>


step by step process for sending email in java...


Try this... its working...

import org.apache.commons.mail.*; public class EmailTest { public static void main(String[] args) { try { Email email = new SimpleEmail(); email.setSmtpPort(587); email.setAuthenticator(new DefaultAuthenticator("emailid@gmail.com", "yourPassword")); email.setDebug(true); email.setHostName("smtp.gmail.com"); email.setFrom("emailid@gmail.com"); email.setSubject("Hi"); email.setMsg("This is a test mail ... :-)"); email.addTo("senderId@yahoo.co.in"); email.setTLS(true); email.send(); System.out.println("Mail sent!"); } catch (Exception e) { System.out.println("Exception :: " + e); } } }


This is not strictly speaking a Java problem. You need an outgoing SMTP server, one to which you can send the message, and which will take care to deliver it to the proper google, yahoo, aol server.

As "host" you must set that SMTP server, or install an SMTP server on your machine if you like, but is a hard task. Usually big companies and service providers have SMTP servers that accept any mail from inside their networks.

Most SMTP servers however are not open, and will not let you send emails as you like, not for free at least. You can create a gmail account, and use gmail SMTP (smtp.gmail.com), using the account username and password of your Transport to authenticate with Google's SMTP server.

Also, you cannot always specify the "from" header, it could get rewritten by the SMTP server to reflect the actual account the mail was sent from, or could be considered spam at the other end if not arriving from the right SMTP server.

I would suggest you to read about how SMTP works, it's an overcomplicated and rather old protocol, but it's worth knowing how it works.


You don't have an SMTP mail server running at localhost:25. Either your mail configuration is wrong and you should be talking to some other mail server, or else you did intend to talk to one in localhost, in which case you need to install and/or run it.


  • php mcrypt equivalent for sagepay on a windows server
  • How to configure Jenkins to send encrypted emails with gpg?
  • JavaMail base64 encoding
  • How to parse raw mime content in java?
  • Sending Email using java program [duplicate]
  • Excel VBA: search a string to find the first non-text character
  • Capturing STDOUT in RSpec
  • What exactly is the height of modalPresentationStyle - FormSheet on iPad?
  • Why does IE8 fail to resolve my JQuery selector for a checked radio option?
  • Mockery and Laravel constructor injection
  • Are there “Dynamic Playlists” of unit tests in Visual Studio?
  • Scanner nextInt() and hasNextInt() problems
  • jQuery: How to AJAXify WordPress Search?
  • Unable to send e-mail through Java
  • Who propagate bugfixes across branches (corporate development)?
  • Why use database factory in asp.net mvc?
  • Reading a file into a multidimensional array
  • App restarts from wrong activity
  • How do I access an unhandled exception in an MVC Error view?
  • preg_replace Double Spaces to tab (\\t) at the beginning of a line
  • Email verification using google app script and google forms
  • Jetty Server not starting: Unable to establish loopback connection
  • ImageMagick, replace semi-transparent white with opaque white
  • Email format validation in mvc3 view
  • req.body is undefined - nodejs
  • Validaiting emails with Net.Mail MailAddress
  • sending/ receiving email in Java
  • Cannot Parse HTML Data Using Android / JSOUP
  • How to delete a row from a dynamic generate table using jquery?
  • Proper way to use connect-multiparty with express.js?
  • JTable with a ScrollPane misbehaving
  • Java static initializers and reflection
  • Exception on Android 4.0 `android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode)`
  • unknown Exception android
  • EntityFramework adding new object to nested object collection
  • Checking variable from a different class in C#
  • Observable and ngFor in Angular 2
  • failed to connect to specific WiFi in android programmatically
  • Unable to use reactive element in my shiny app
  • How can I use threading to 'tick' a timer to be accessed by other threads?