Sending email via Gmail SMTP in Java

Gradle

// https://mvnrepository.com/artifact/javax.mail/javax.mail-api
compile group: 'javax.mail', name: 'javax.mail-api', version: '1.6.0'

// https://mvnrepository.com/artifact/com.sun.mail/javax.mail
compile group: 'com.sun.mail', name: 'javax.mail', version: '1.6.0'

GMail via SSL

package com.mkyong.common;

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMailSSL {
	public static void main(String[] args) {
		Properties props = new Properties();
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.socketFactory.port", "465");
		props.put("mail.smtp.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", "465");

		Session session = Session.getDefaultInstance(props,
			new javax.mail.Authenticator() {
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication("username","password");
				}
			});

		try {

			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress("from@no-spam.com"));
			message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse("to@no-spam.com"));
			message.setSubject("Testing Subject");
			message.setText("Dear Mail Crawler," +
					"\n\n No spam to my email, please!");

			Transport.send(message);

			System.out.println("Done");

		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}
	}
}

If you want to send HTML message :

message.setContent(someHtmlMessage, "text/html; charset=utf-8");

References
https://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
https://stackoverflow.com/questions/5068827/how-do-i-send-an-html-email
https://www.campaignmonitor.com/css/
https://stackoverflow.com/questions/16807758/java-lang-noclassdeffounderror-com-sun-mail-util-maillogger-for-junit-test-case
https://stackoverflow.com/questions/46663/how-can-i-send-an-email-by-java-application-using-gmail-yahoo-or-hotmail
https://developers.google.com/gmail/api/guides/sending

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.