How to Send Email using Java


We can send email via Java code by making use of the Jakarta Mail API.


Maven Dependency:

<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>jakarta.mail</artifactId>
    <version>2.0.1</version>
</dependency>

Gradle Dependency:

implementation group: 'com.sun.mail', name: 'jakarta.mail', version: '2.0.1'

Let's take a look at an example.

import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;

import java.util.Properties;

public class SendEmailJavaExample {

    public static void main(String[] args) {

        String senderEmail = "sender_email@code2care.org";
        String senderPassword = "password";

        String recipientEmail = "recipient_email@code2care.org";

        Properties emailProperties = new Properties();
        emailProperties.put("mail.smtp.auth", "true");
        emailProperties.put("mail.smtp.host", "smtp.code2care.org");
        emailProperties.put("mail.smtp.port", "587");
        emailProperties.put("mail.smtp.starttls.enable", "true");

        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(senderEmail, senderPassword);
            }
        });

        try {
            
            Message emailMessage = new MimeMessage(session);
            emailMessage.setFrom(new InternetAddress(senderEmail));
            emailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(recipientEmail));
            emailMessage.setSubject("Hello from Java!");
            emailMessage.setText("Hello, This is an email via Jakarta Mail Example in Java.");

            Transport.send(emailMessage);

            System.out.println("Email Sent!");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
Email as received using Java Code
-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author: Rakesh
Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

Copyright © Code2care 2023 | Privacy Policy | About Us | Contact Us | Sitemap