How to send mail in java code

In Java, you can send an email using the JavaMail API. Here's a step-by-step guide to help you get started:

Prerequisites:

  1. Download and install the JavaMail API from the official website: https://javaee.github.io/javamail/
  2. Add the JavaMail API jar file to your project's classpath.

Code Example:

Here's a simple example of how to send an email using JavaMail API:

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

public class SendEmail {
    public static void main(String[] args) {
        // Set up the email properties
        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");

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

        // Create a message
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress("your-email-username"));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress("recipient-email-username"));
        message.setSubject("Test Email");
        message.setText("This is a test email sent using JavaMail API.");

        // Send the message
        Transport.send(message);
    }
}

Explanation:

  1. We create a Properties object to set up the email properties, such as the SMTP host, port, authentication, and TLS enablement.
  2. We create a Session object using the Session.getInstance() method, passing the Properties object and an Authenticator object.
  3. We create a MimeMessage object using the Session object.
  4. We set the sender, recipient, subject, and body of the email using the setFrom(), setRecipient(), setSubject(), and setText() methods.
  5. We send the email using the Transport.send() method.

Note: