In your code snippet, you are encountering a "Connection refused" error while attempting to send an email using the localhost SMTP server. This indicates that the SMTP server is not listening on that host or port.
To resolve this issue, you need to either:
If using a local SMTP server is not feasible, you can utilize the GoogleMail class provided in the response. This class simplifies the process of sending emails using Google's SMTP server. Here's a modified code snippet using GoogleMail:
import com.google.api.services.gmail.Gmail; import com.google.api.services.gmail.model.Message; import javax.mail.MessagingException; import java.io.IOException; public class SendEmail { public static void main(String[] args) throws IOException, MessagingException { // Replace these variables with your own information String username = "your_gmail_username"; String password = "your_gmail_password"; String recipientEmail = "recipient_email_address"; String title = "This is the Subject Line!"; String message = "This is actual message"; // Construct an authorized Gmail service Gmail service = Utils.getGmail(username, password); // Send the email GoogleMail.Send(service, recipientEmail, "", "user1@XYZ.com", title, message); System.out.println("Sent message successfully..."); } }
Note that you will need to obtain a refresh token from Google and save it to a file in order to avoid having to enter your password every time you send an email.
By addressing the SMTP connection issue or leveraging the provided GoogleMail class, you can successfully send emails using Java. Remember to adjust the code snippet to include your own email credentials and message content.
The above is the detailed content of Why Am I Getting a 'Connection Refused' Error When Sending Email in Java?. For more information, please follow other related articles on the PHP Chinese website!