Java Sending Email

java

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:

<!-- https://mvnrepository.com/artifact/javax.mail/javax.mail-api -->
<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>javax.mail-api</artifactId>
    <version>1.6.4</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.sun.mail/javax.mail -->
<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.4</version>
</dependency>

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("mail.smtp.host", "smtp.gmail.com");
        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));
            message.setSubject(subject);
            message.setText(body);

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

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 https://javaee.github.io/javamail/.