How to send mail in java using gmail

To send an email using Gmail in Java, you can use the JavaMail API. Here's a step-by-step guide:

Step 1: Add the JavaMail API to your project

You can add the JavaMail API to your project using Maven or Gradle. Here's how:

Maven:

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

Gradle:

dependencies {
    implementation 'com.sun.mail:javax.mail:1.6.2'
}

Step 2: Set up your Gmail account

To use Gmail to send emails, you need to enable "Less secure app access" in your Google Account settings. You can do this by following these steps:

  1. Go to your Google Account settings.
  2. Click on "Security" from the left-hand menu.
  3. Scroll down to the "Less secure app access" section.
  4. Toggle the switch to "On".

Step 3: Write the Java code

Here's an example Java code that sends an email using Gmail:

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 up the email properties
        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");

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

Step 4: Run the code

Compile and run the Java code. The email should be sent successfully.

Note: Make sure to replace "[email protected]" and "your-password" with your actual Gmail email and password. Also, replace "[email protected]" with the email address of the recipient.

That's it! You should now be able to send emails using Gmail in Java.