JAVA. Send Email via Gmail.


package com.javacodegeeks.snippets.enterprise;

import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
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 SendEMailViaGMail {

	private static final String username = "myusername";
	private static final String password = "mypassword";

	public static void main(String[] args) {

		String host = "";
		String from = "";
		String to = "";

		// Set properties
		Properties props = new Properties();
		props.put("", host);
		props.put("mail.smtp.port", 25);
		props.put("mail.debug", "true");
		props.put("mail.transport.protocol", "smtp");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.starttls.enable", "true");

		// Get session with authenticator
		Session session = Session.getInstance(props, new GMailAuthenticator());

		try {

		    // Instantiate a message
		    Message msg = new MimeMessage(session);

		    // Set the FROM message
		    msg.setFrom(new InternetAddress(from));

		    // The recipients can be more than one so we use an array but you can
		    // use 'new InternetAddress(to)' for only one address.
		    InternetAddress[] address = {new InternetAddress(to)};
		    msg.setRecipients(Message.RecipientType.TO, address);

		    // Set the message subject and date we sent it.
		    msg.setSubject("Email from JavaMail test");
		    msg.setSentDate(new Date());

		    // Set message content
		    msg.setText("Hello that's me - Sending an email with Java through Gmail");

		    // Send the message

		catch (MessagingException mex) {


	private static class GMailAuthenticator extends Authenticator {
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(username, password);


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s