Send an email using SMTP with Java
Send Email in Java Using SMTP
Sending emails programmatically is a common requirement in Java applications. In this tutorial, we will learn how to send an email in Java using SMTP with the JavaMail API. We will cover the required dependencies, provide a step-by-step guide, and demonstrate a working example.
Before we begin, ensure that you have the following libraries installed:
These libraries are required to enable email functionality in Java.
Below is the Java program to send an email using SMTP.
import java.util.*;
import javax.mail.*;
import javax.activation.*;
import javax.mail.internet.*;
class SendHTMLEmail {
public static void main(String[] args) {
String to = "[email protected]";
String from = "[email protected]";
String host = "smtp.example.com"; // Replace with SMTP server
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
try {
MimeMessage message = new MimeMessage(session);
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Test Email via SMTP");
message.setContent("<h1>This is a test email sent via Java SMTP</h1>", "text/html");
Transport.send(message);
System.out.println("Email sent successfully...");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
javax.mail
and javax.activation
packages are used to handle email communication.properties
object.Session
instance is created using the specified properties.Transport.send()
method is used to dispatch the email.In this article, we have demonstrated how to send an email in Java using SMTP. This is a fundamental feature for applications that require email notifications, such as password resets, alerts, or transactional emails.
If you found this article helpful, follow us on Instagram, LinkedIn, Facebook, and Twitter for more updates!
Article by Developer Indian Team.