Java Sending Email


To send email using Java, you can use the JavaMail API. This API provides a set of classes and interfaces for building Java programs that can send email.

To use the JavaMail API, you will need to include the following dependencies in your project:

<!-- -->

<!-- -->

You will also need to configure your email server’s hostname and port, as well as your email address and password.

Here is an example of how to send a simple email using the JavaMail API:

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

public class SendEmail {
    public static void main(String[] args) {
        String from = "[email protected]";
        String to = "[email protected]";
        String subject = "Hello, World!";
        String body = "This is a test email.";

        sendEmail(from, to, subject, body);

    public static void sendEmail(String from, String to, String subject, String body) {
        Properties properties = new Properties();
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("", "");
        properties.put("mail.smtp.port", "587");

        String username = "[email protected]";
        String password = "yourpassword";

        Session session = Session.getInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);

        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));

            System.out.println("Email sent successfully.");
        } catch (MessagingException e) {

This example uses the javax.mail.Session class to create a session with the email server, and the javax.mail.Message class to create and send the email message.

For more information on the JavaMail API, you can refer to the official documentation at