1

I am trying to make automatic message which will be sent on email but, when i start my program i get :

com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 25; timeout -1;

I want it to be sent from localhost not exact email with password and username. code:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*; 
import javax.mail.*; 
import javax.mail.internet.*;

import javax.activation.*; 
import javax.mail.Session; 
import javax.mail.Transport; 


public class Email  
{ 
   public static void main(String[] args) throws IOException {

       String recipient = "test@gmail.com";
       String sender = "sender@gmail.com";
       String host = "localhost";

       Properties properties = System.getProperties();
       properties.setProperty("mail.smtp.host", host);

       Session session = Session.getDefaultInstance(properties);

       try {
           MimeMessage message = new MimeMessage(session);
           message.setFrom(new InternetAddress(sender));
           message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
           message.setSubject("Test sub"); 
           message.setText("Test MSG");

           Transport.send(message);
           System.out.println("Sent."); 

       } catch (AddressException e) {
           e.printStackTrace();
       } catch (MessagingException e) {
           e.printStackTrace();
       }

   }
    }

To run this class i am using javax.mail.jar. Does somebody know where the problem is ?

Barry
  • 57
  • 4

1 Answers1

0

It's trying to connect to the mail server at localhost but you don't have one running. To send smtp emails you'll have to connect to a mail server. The default port is 25. That's why the message says:

Couldn't connect to host, port: localhost, 25

So update your host property to point to where a server is running. You can use SMTP settings from say a gmail account to do this easily.

This might help.

https://www.siteground.com/kb/google_free_smtp_server/

Josh Chappelle
  • 1,558
  • 2
  • 15
  • 37