How to send mail using java

Sending mail using Java can be done using the JavaMail API. Here's a step-by-step guide:

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 sending an email using Java:

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

public class SendMail {
    public static void main(String[] args) {
        // Set up the mail server 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 mail server properties, such as the host, port, authentication, and TLS encryption.
  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's email address using the setFrom() method.
  5. We set the recipient's email address using the setRecipient() method.
  6. We set the subject and body of the email using the setSubject() and setText() methods.
  7. We send the message using the Transport.send() method.

Note: