6

Hi i would like to send a simple mail using java.. So i downloaded mail.jar and activation.jar file and i wrote simple program to send it.

My Simple mail program compiles successfully.. But when i run it shows the following error.

javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25; nested exception is: java.net.ConnectException: Connection refused: connect

My doubt is how to find the SMTP server name for my PC? I searched in site but didnt get anything clearly..

Please make me to travel in a right direction...

With regards

Xavier KCB

Ripon Al Wasim
  • 36,924
  • 42
  • 155
  • 176
xavierkcb
  • 129
  • 1
  • 2
  • 8
  • You could try it: http://stackoverflow.com/questions/5179807/could-not-connect-to-smtp-host-localhost-port-25-nested-exception-is-java-n or http://stackoverflow.com/questions/9645578/sending-mail-from-your-computer-using-java-what-required – Vladislav Bauer Mar 10 '12 at 10:58
  • possible duplicate of [Error in Sending mail by Java](http://stackoverflow.com/questions/10853209/error-in-sending-mail-by-java) – Bolster Dec 03 '14 at 12:05

9 Answers9

2

You don't have to use SMTP server name for your PC, you have to use external email server, for example, gmail, yahoo, etc. You can set up mail server on you computer, but it is out of the question. In your case, you have to register new email in free mail system, and use it smtp server and port. You can google more about JavaMail API examples: cafeaulait, vipan

UdayKiran Pulipati
  • 6,579
  • 7
  • 67
  • 92
MikhailSP
  • 3,233
  • 1
  • 19
  • 29
0

Assuming that, you are using gmail for sending email. The details code as below:

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

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

            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();
        }
        catch(Exception e){
            e.getMessage();
        }
    }
}
Ripon Al Wasim
  • 36,924
  • 42
  • 155
  • 176
0

You need to have a email-server first. So please use some like http://www.hmailserver.com/, which is a free. Please be aware of the Auto-Ban option, that can be turned off and will ruin your day otherwise.

Install and set up, pretty easy.

When you have done that, you can write your email client App.

Check This: http://www.xmarks.com/site/www.digilife.be/quickreferences/PT/Fundamentals%2520of%2520the%2520JavaMail%2520API.pdf

it's the old "Fundamentals on the JavaMail API" website as PDF, pretty much the best source out there (don't know why it is no more online at oracle.com).

and refer to that in all matters. It's a very good tutorial and will guide you through the process. Good Reference when seeking something:

http://de.scribd.com/doc/11385837/All-About-Java-Mail

Please do not develop that with some GMail account or so - their servers will not cooperate, as you are making to much trouble (to much connections, constant getting ban cause of false login etc.).

THarms
  • 311
  • 1
  • 4
0

This is a complete short program on Tomcat 7 which uses a SMTP server as a Service (SendGrid in this case). I use it for sending emails to recover user passwords.

You can run it both, locally enabling for free a SendGrid service or just deploying it instantly on the specific PaaS, who has developed the software.

Captain Haddock
  • 488
  • 2
  • 7
0

This is the first of the errors you may face while executing an email program and may be followed by various other errors if not corrected properly.

Possible solutions to this and other such problems followed by the code I used for sending emails using my company mailbox:

  • 1) Correct host details as many other members have already mentioned. 25 the the default port, change this if not the same.
  • 2) Check if the server you are hitting mandates an authentication or not. more on this in the code.
  • 3) Do put a mail.debug in the properties to know what exactly is going on between your code and the mailserver. 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("mail.smtp.host", "mail.mycompany123.com");
// 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("sadique.khan@mycompany123.com","xxxxxxxxxxx");
                }
            });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("sadique.khan@mycompany123.com"));
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse("my.bestfriend@mycompany123.com"));
            message.setSubject("Testing Subject");
            message.setText("Dear Friend," +
                    "\n\n This is a Test mail!");

            Transport.send(message);



        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}
Sadique Khan
  • 161
  • 3
  • 13
0

send mail via local SMTP

Hello, gayz! If your application execute on server with own SMTP server (for example many UNIX distr. including those), Y can check it:

$ echo 'anytext' | mail -s 'mailSubject' recepient@example.com

Y can send a message through it:

import java.io.IOException;
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("do_not_reply@example.com", "NoReply"));
        msg.addRecipient(Message.RecipientType.TO, recepients);
        msg.setSubject(subject);
        msg.setText(body);
        Transport.send(msg);
        System.out.println("Email sent successfully...");
    }
}
Mikro Koder
  • 1,056
  • 10
  • 13
0

To send an e-mail using your Java Application is simple enough but to start with you should have JavaMail API and Java Activation Framework (JAF) installed on your machine.

You can download latest version of JavaMail and JAF from Java's standard website (or to use Maven or similar tool).

Now, to send a simple mail you will have 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's email ID needs to be mentioned.
      String to = "abcd@gmail.com";

      // Sender's email ID needs to be mentioned
      String from = "web@gmail.com";

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

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

      // Setup mail server
      properties.setProperty("mail.smtp.host", 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
         Transport.send(message);
         System.out.println("Sent message successfully....");
      } catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

Check out for more Java mail sending examples.

Johnny
  • 14,397
  • 15
  • 77
  • 118
-1
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("mail.smtp.host", 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();
        addresses.append("FROM:").append(senderAddress);
        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] + ";");
                }
                message.setReplyTo(replyToAddresses);
            }

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

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

            MimeBodyPart mimeBody = new MimeBodyPart();
            mimeBody.setText(body);
            multipart.addBodyPart(mimeBody);

            // 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));
                    mimeAttachment.setFileName(attachment);
                    multipart.addBodyPart(mimeAttachment);
                }
            }

            message.setContent(multipart);

            // Send
            //Transport.send(message);
            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());
            tr.close();
            System.out.println("sendmail success " + addresses);
        } catch (AddressException e) {
            System.out.println("sendMail failed " + addresses);
            e.printStackTrace();
        } catch (MessagingException e) {
            System.out.println("sendMail failed " + addresses);
            e.printStackTrace();
        }
    }

    public static void main(String s[]) {
        if (s.length < 3) {
            System.out.println("Usage: MailSender RelayAddress SendersAddress ToAddress [ AttachmentFileName ]");
            System.exit(-1);
        }
        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);

    }

}
-1

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

Jan Gräfen
  • 314
  • 2
  • 12
  • 1
    -1: TS needs to configure JavaMail to use the SMTP server of his ISP, not install a local SMTP server – Mark Rotteveel Mar 10 '12 at 15:43
  • If he tries to connect to localhost:25 he obviously don't want to sent emails from his ISP, but rather from his server or whatever. So your -1 is kind of random to me. – Jan Gräfen Mar 10 '12 at 18:58
  • If you don't configure JavaMail correctly (as in: don't set the server) then it defaults to localhost – Mark Rotteveel Mar 11 '12 at 11:22