How to send mail in gmail using java

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:

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

Gradle:

implementation 'com.sun.mail:javax.mail:1.6.2'

Step 2: Set up your Gmail account

To use Gmail with JavaMail, 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 code snippet 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 sent using JavaMail");

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

Step 4: Run the code

Compile and run the code, replacing "[email protected]" and "your-password" with your actual Gmail credentials.

Note: Make sure to replace "[email protected]" with the actual email address of the recipient.

That's it! You should receive an email at the recipient's email address.