Send mail using JAVA

Hi, I would like to send a simple mail using java .. So I downloaded the mail.jar and activ.jar file and I wrote a simple program to send it.

My simple mailer compiles successfully. But when I run it, the following error appears.

javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25; Nested Exception: Connection refused: connect

My doubt is how do I find the SMTP server name for my PC? I searched the site but didn't understand anything.

Please make me go in the right direction ...


Xavier KCB


source to share

9 replies

You don't need to use the SMTP server name for your PC, you should use an external mail server like gmail, yahoo, etc. You can set up a mail server on your computer, but it is beyond the scope of the question. In your case, you need to register a new email with the free mail system and use its smtp server and port. You can read more about JavaMail API examples: cafeaulait , vipan



Assuming you are using gmail to send email. Part code as below:

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

public class SendFromGmail {
    public static void main(String args[]){
            String host = "";
            String from = "";
            String pass = "mypassword123";
            Properties props = System.getProperties();
            props.put("mail.smtp.starttls.enable", "true");
            props.put("", 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 = {""};

            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]);

            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());
        catch(Exception e){




First you need to have a mail server. So please use some , which is free. Look out for the Auto-Ban option which can be turned off and ruin your day otherwise.

Installing and configuring is pretty easy.

When you have done that, you can write your own mail client application.

Check it out:

this is the old PDF JavaMail API Basics website, pretty much the best source out there (not sure why it's no longer on

and refer to this in all questions. This is a very good tutorial and will walk you through the process. Good link when looking for something:

Please do not develop that with any GMail account or so - their servers will not communicate as you are making big problems (for many connections, getting banned all the time, reason for false logins, etc.) ..



This is a complete short program on Tomcat 7 that uses SMTP server as a service (SendGrid in this case). I am using it to send email to recover user passwords.

You can run it locally by enabling the SendGrid service for free, or simply deploying it instantly on the specific PaaS that developed the software.



This is the first of the errors you may encounter while running your email program, and other errors may follow if not corrected correctly.

Possible solutions to this and similar problems, followed by the code I used to send emails using my company's mailbox:

  • 1) Correct the host details as mentioned above. 25 is the default port, change this if not the same.
  • 2) Make sure the server you are pushing to is authenticating or not. more on this in the code.
  • 3) Put mail.debug in properties to know exactly what is going on between your code and the mail server. more on this in the code.

My code:

package com.datereminder.service;

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

     * @param args
    public static void main(String[] args) {
        Properties props = new Properties();
        props.put("", "");
// this mandates authentication at the mailserver
        props.put("mail.smtp.auth", "true");
// this is for printing debugs

        props.put("mail.debug", "true");

        Session session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("","xxxxxxxxxxx");

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(""));
            message.setSubject("Testing Subject");
            message.setText("Dear Friend," +
                    "\n\n This is a Test mail!");


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




send mail via local SMTP

Hello gaze! If your application is running on a server with its own SMTP server (like many UNIX addresses, including those), Y can check it:

$ echo 'anytext' | mail -s 'mailSubject'


Y can send a message through it:

import java.util.Date;
import java.util.Properties;

import javax.mail.*;
import javax.mail.internet.*;

public class MailSender {
void systemSender(InternetAddress recepients, String subject, String body) throws IOException, AddressException, MessagingException {

        Properties properties = new Properties();
        Session session = Session.getDefaultInstance(properties , null);

        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("", "NoReply"));
        msg.addRecipient(Message.RecipientType.TO, recepients);
        System.out.println("Email sent successfully...");




Sending email using a Java application is straightforward, but you must first have the JavaMail API and Java Activation Framework (JAF) installed on your computer.

You can download the latest JavaMail and JAF from the standard Java website (or use Maven or a similar tool).

Now, to send a simple email, you will need to do the following:

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

public class SendEmail {

   public static void main(String [] args) {    
      // Recipient email ID needs to be mentioned.
      String to = "";

      // Sender email ID needs to be mentioned
      String from = "";

      // Assuming you are sending email from localhost
      String host = "localhost";

      // Get system properties
      Properties properties = System.getProperties();

      // Setup mail server
      properties.setProperty("", host);

      // Get the default Session object.
      Session session = Session.getDefaultInstance(properties);

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

         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));

         // Set To: header field of the header.
         message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

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

         // Now set the actual message
         message.setText("This is actual message");

         // Send message
         System.out.println("Sent message successfully....");
      } catch (MessagingException mex) {


Check out other Java mail sending examples .



You need to install and run an SMTP server on your PC or server if you want to connect to localhost. There are tons of free ones available for Windows and Linux.



import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
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 MailSender {

    public final String mailServerAddress;
    public final int mailServerPort;
    public final String senderAddress;

    public MailSender(String mailServerAddress, int mailServerPort, String senderAddress) {
        this.senderAddress = senderAddress;
        this.mailServerAddress = mailServerAddress;
        this.mailServerPort = mailServerPort;

    public void sendMail(String to[], String cc[], String bcc[], String replyTo[], String subject, String body, String[] attachments) {

        if (to == null || to.length <= 0) {
            System.out.println("sendMail To address is NULL for email");

        if (subject == null || subject.length() <= 0) {
            System.out.println("sendMail Subject is NULL for email");

        if (body == null || body.length() <= 0) {
            System.out.println("sendMail Body is NULL for email");

        Properties props = new Properties();
        // Specify the desired SMTP server and port
        props.put("", mailServerAddress);
        props.put("mail.smtp.port", Integer.toString(mailServerPort));
        props.put("mail.smtp.auth", "true");

        //TODO can we create session only once, with some session validation
        Session session = Session.getInstance(props, null);

        // create a new MimeMessage object (using the Session created above)
        Message message = new MimeMessage(session);
        StringBuilder addresses = new StringBuilder();
        try {
            message.setFrom(new InternetAddress(senderAddress));

            // TO:
            InternetAddress[] toAddresses = new InternetAddress[to.length];
            addresses.append(" TO:");
            for (int i = 0; i < to.length; i++) {
                toAddresses[i] = new InternetAddress(to[i]);
                addresses.append(to[i] + ";");
            message.setRecipients(Message.RecipientType.TO, toAddresses);

            // CC:
            if (cc != null && cc.length > 0) {
                InternetAddress[] ccAddresses = new InternetAddress[cc.length];
                addresses.append(" CC:");
                for (int i = 0; i < cc.length; i++) {
                    ccAddresses[i] = new InternetAddress(cc[i]);
                    addresses.append(cc[i] + ";");
                message.setRecipients(Message.RecipientType.CC, ccAddresses);

            // BCC:
            if (bcc != null && bcc.length > 0) {
                InternetAddress[] bccAddresses = new InternetAddress[bcc.length];
                addresses.append(" BCC:");
                for (int i = 0; i < bcc.length; i++) {
                    bccAddresses[i] = new InternetAddress(bcc[i]);
                    addresses.append(bcc[i] + ";");
                message.setRecipients(Message.RecipientType.BCC, bccAddresses);

            // ReplyTo:
            if (replyTo != null && replyTo.length > 0) {
                InternetAddress[] replyToAddresses = new InternetAddress[replyTo.length];
                addresses.append(" REPLYTO:");
                for (int i = 0; i < replyTo.length; i++) {
                    replyToAddresses[i] = new InternetAddress(replyTo[i]);
                    addresses.append(replyTo[i] + ";");

            // Subject:
            addresses.append(" SUBJECT:").append(subject);

            // Body:
            Multipart multipart = new MimeMultipart();

            MimeBodyPart mimeBody = new MimeBodyPart();

            // Attachments:
            if (attachments != null && attachments.length > 0) {
                for (String attachment : attachments) {
                    MimeBodyPart mimeAttachment = new MimeBodyPart();
                    DataSource source = new FileDataSource(attachment);
                    mimeAttachment.setDataHandler(new DataHandler(source));


            // Send
            String username = "amol@postmaster";
            String password = "amol";
            Transport tr = session.getTransport("smtp");
            tr.connect(mailServerAddress, username, password);
            message.saveChanges();      // don't forget this
            tr.sendMessage(message, message.getAllRecipients());
            System.out.println("sendmail success " + addresses);
        } catch (AddressException e) {
            System.out.println("sendMail failed " + addresses);
        } catch (MessagingException e) {
            System.out.println("sendMail failed " + addresses);

    public static void main(String s[]) {
        if (s.length < 3) {
            System.out.println("Usage: MailSender RelayAddress SendersAddress ToAddress [ AttachmentFileName ]");
        int k = 0;
        String relay = s[k++];
        String sender = s[k++];
        String[] toAddresses = new String[] {s[k++]};
        String[] attachmentFileName = new String[0];

        if (s.length == 4) {
            attachmentFileName = new String[] {s[k++]};

        MailSender mailSender = new MailSender(relay, 25, sender);

        String[] mailTo = toAddresses;
        String[] mailCC = new String[] {};
        String[] mailBCC = new String[] {};
        String[] replyTo = new String[] {};

        String mailSubject = "Test Mail";
        String mailBody = "Mail sent using test utility";

        mailSender.sendMail(mailTo, mailCC, mailBCC, replyTo, mailSubject, mailBody, attachmentFileName);






All Articles