Quantcast
Channel: Active questions tagged email - Stack Overflow
Viewing all articles
Browse latest Browse all 29767

Sending Email via Java program

$
0
0

I am using the following code to send email using Java:

package com.company;

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

class SendEmail {
    public static void main(String[] args) {
        // Recipient's email ID needs to be mentioned.
        String to = "motse.thuto@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();
        }
    }
}

It gives me the following error:

com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 25; timeout -1;
      nested exception is:
        java.net.ConnectException: Connection refused: connect
        at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2209)
        at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:740)
        at javax.mail.Service.connect(Service.java:366)
        at javax.mail.Service.connect(Service.java:246)
        at javax.mail.Service.connect(Service.java:195)
        at javax.mail.Transport.send0(Transport.java:254)
        at javax.mail.Transport.send(Transport.java:124)
        at com.company.SendEmail.main(Main.java:47)

Process finished with exit code 0

Can anyone explain why I'm getting this error? Any help will be appreciated.


Viewing all articles
Browse latest Browse all 29767

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>