Jakarta mail example

Here is an example of using Jakarta Mail (JavaMail API) to send an email:

Step 1: Add the Jakarta Mail dependency

Add the following dependency to your pom.xml file (if you're using Maven) or your build.gradle file (if you're using Gradle):

<!-- Maven -->
<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-jakarta-mail</artifactId>
    <version>2.30</version>
</dependency>

<!-- Gradle -->
dependencies {
    implementation 'org.glassfish.jersey.containers:jersey-container-jakarta-mail:2.30'
}

Step 2: Create a Java class to send the email

Create a new Java class, for example EmailSender.java, with the following code:

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

public class EmailSender {
    public static void sendEmail(String from, String to, String subject, String body) {
        Properties props = new Properties();
        props.put("mail.smtp.host", "your-smtp-host");
        props.put("mail.smtp.port", "your-smtp-port");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");

        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("your-email-username", "your-email-password");
            }
        });

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

            Transport.send(message);
            System.out.println("Email sent successfully!");
        } catch (MessagingException e) {
            System.out.println("Error sending email: " + e.getMessage());
        }
    }
}

Step 3: Use the EmailSender class to send the email

Create a new Java class, for example Main.java, with the following code:

public class Main {
    public static void main(String[] args) {
        EmailSender.sendEmail("your-email-username", "recipient-email-username", "Hello World!", "This is a test email.");
    }
}

Step 4: Run the Main class

Run the Main class to send the email. Make sure to replace the placeholders (your-smtp-host, your-smtp-port, your-email-username, and your-email-password) with your actual email settings.

That's it! You should receive an email with the subject "Hello World!" and the body "This is a test email."