Java Code Snippet for Sending Email using Gmail SMTP Server

Add comments

The partial code below shows how to sent an email using the Gmail’s SMTP server:

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

Session session = Session.getInstance(properties, new Authenticator() {
      public PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("username@gmail.com", "password");
      }
});

Message msg = new MimeMessage(session);
msg.setFrom(...);
msg.addRecipient(...);
msg.setSubject(...);
msg.setText(...);

Transport.sent(msg);

Leave a Reply

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in