Send mail from java

Here is an example of how to send an email from a Java program using the JavaMail API:

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

public class SendEmail {
    public static void main(String[] args) {
        // Set the properties for the email
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");
        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("[email protected]", "your-password");
            }
        });

        // Create a message
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress("[email protected]"));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
        message.setSubject("Test Email");
        message.setText("This is a test email sent from Java");

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

This code uses the JavaMail API to send an email from a Java program. You'll need to replace the placeholders ([email protected], your-password, and [email protected]) with your actual email address, password, and the recipient's email address.

Here's a breakdown of the code:

  1. We set the properties for the email using the Properties class. We specify the SMTP host, port, authentication, and start TLS enablement.
  2. We create a session using the Session class, passing in the properties and an authenticator that provides the email address and password.
  3. We create a message using the MimeMessage class, setting the from address, recipient address, subject, and text body.
  4. We send the message using the Transport class.

Note that you'll need to add the JavaMail API to your project's classpath. You can do this by adding the following dependency to your pom.xml file (if you're using Maven):

<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.2</version>
</dependency>

Alternatively, you can download the JavaMail API JAR file and add it to your project's classpath manually.

Also, keep in mind that this is just a basic example, and you may want to add additional features such as attachments, HTML formatting, or error handling to your email sending code.