Send email in Java using Gmail smtp server

Today we will learn how to send email in Java using gmail. It’s very easy and it will be a very quick tutorial.

We are gonna use a library called Javax mail api. Below you can download the library based your project type.

Maven:

If your project built on maven:

<!-- https://mvnrepository.com/artifact/com.sun.mail/javax.mail -->
<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.2</version>
</dependency>

Gradle:

If your project built on gradle:

// https://mvnrepository.com/artifact/com.sun.mail/javax.mail
implementation 'com.sun.mail:javax.mail:1.6.2'

Jar:

If you like download jar file of this library:


Code:

Execute the code below in order to send email.

private void sendEmail(){

        Properties props = new Properties();
        props.put("mail.smtp.starttls.enable", true);
        props.put("mail.smtp.auth", true);
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", 587);

        Session session = Session.getInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication("Sender email address", "Password");
                    }
                });

        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(Constant.getSharedPreferences().getEmailAddress()));
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse("receiver email address"));
            message.setSubject("your subject");
            message.setText("The body text here");
            Transport.send(message);

        } catch (Exception e) {
            Log.e("exception", e.getMessage());
            System.out.print(e);
        }
    }

Now you are done. Execute this code and email will be sent.
In next post we will learn how to send email in spring boot using freemarker.