Send email using Gmail account

by GarciaPL on Wednesday 10 September 2014

I would like to share with you a small snippet which will allow you to send email using Gmail account. In this case I will use JavaMail (javax.mail) interface for sending email messages. More information about JavaMail API reference you can find below.

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

private void sendEmail() {

        String sender = "sender@gmail.com";
        String receiver = "receiver@gmail.com";
        String title = "YOUR_TITLE_TEXT";
        String body = "YOUR_BODY_TEXT";

        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "25");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.EnableSSL.enable", "true");
        props.put("mail.smtp.auth", "true");
        props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.port", "465");
        props.setProperty("mail.smtp.socketFactory.port", "465");

        Authenticator authenticator = new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("login@gmail.com", "password");
            }
        };

        Session session = Session.getDefaultInstance(props, authenticator);

        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(sender));
            msg.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(receiver, receiver));
            msg.setSubject(title);
            msg.setText(body);
            Transport.send(msg);
        } catch (MessagingException e) {
            System.out.println("sendEmail (MessagingException) : " + e.getMessage());
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            System.out.println("sendEmail (UnsupportedEncodingException) : " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("sendEmail (Exception) : " + e.getMessage());
            e.printStackTrace();
        }
}
If you are using Gmail account to send emails, properties related with smtp configuration in this snippet will remain, but you should change variables like sender, receiver, title and body to your needs. You should also change login and password in below line which will be used to authenticate with gmail account :


return new PasswordAuthentication("login@gmail.com", "password");
Reference : [1] Oracle®'s JavaMail API reference [2] Pastebin Source