Gmail smtp server java

To send emails using Gmail's SMTP server 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 an example of how to add it using Maven:

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

Step 2: Set up your Gmail account

To use Gmail's SMTP server, you need to enable less secure apps 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 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 of how to send an email using Gmail's SMTP server in Java:

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 SMTP server
        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

Run the Java code to send the email. Make sure to replace the placeholders with your actual Gmail account credentials and the recipient's email address.

Note: Make sure to enable less secure apps in your Google account settings, as mentioned in Step 2. Also, be aware that using Gmail's SMTP server may have limitations and may not work if you're behind a proxy or have other network restrictions.