Googles Gmail SMTP server supports the use of TLS (Transport Layer Security). When using a Gmail SMTP server with Javamail we can configure Javamail to use TLS using the session properties.
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
// use your gmail account username here
props.put("mail.smtp.user", "username@gmail.com");
props.put("mail.smtp.port", "465");
props.put("mail.mime.charset", "ISO-8859-1");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.fallback", "false");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
You’ll also need to specify an Authenticator when creating the session.
You can then use the session to send your mail.
Putting it all together we get this
// Create session
Properties sessionProperties = System.getProperties();
props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
// use your gmail account username here
props.put("mail.smtp.user", "username@gmail.com");
props.put("mail.smtp.port", "465");
props.put("mail.mime.charset", "ISO-8859-1");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.fallback", "false");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
Session session =
Session.getDefaultInstance(sessionProperties, new PasswordAuthenticator());
// Create message
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to, false));
message.setSubject(subject);
message.setText(body);
// Send the message
Transport.send(message);
written by objects
\\ tags: authentication, gmail, google, properties, session, smtp, tls