How to Send Email using Java

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

Maven 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 = "";
        String senderPassword = "password";

        String recipientEmail = "";

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

        Session session = Session.getInstance(properties, new Authenticator() {
            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.");


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

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

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail:

Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap