Jakarta mail maven
Jakarta Mail is a Java library for sending and receiving email messages. Here's a step-by-step guide on how to use Jakarta Mail with Maven:
Step 1: Add the Jakarta Mail dependency to your Maven project
Add the following dependency to your pom.xml
file:
<dependencies>
<dependency>
<groupId>org.glassfish.jakarta.mail</groupId>
<artifactId>jakarta.mail</artifactId>
<version>2.1.1</version>
</dependency>
</dependencies>
Step 2: Configure the mail session
Create a mail.properties
file in the root of your classpath (e.g., src/main/resources
) with the following configuration:
mail.smtp.host=localhost
mail.smtp.port=25
mail.smtp.auth=true
mail.smtp.starttls.enable=true
You can adjust the values to match your email server settings.
Step 3: Create a mail session
Create a Java class that creates a mail session:
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailSender {
public static void sendMail(String from, String to, String subject, String body) {
Properties props = new Properties();
props.put("mail.smtp.host", "localhost");
props.put("mail.smtp.port", "25");
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 {
MimeMessage 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 4: Use the mail sender class
Call the sendMail
method from your Java class:
public class Main {
public static void main(String[] args) {
MailSender.sendMail("your-email-username", "[email protected]", "Test Email", "This is a test email.");
}
}
That's it! You should now be able to send email using Jakarta Mail with Maven.