Pages Navigation Menu

Coding is much easier than you think

Sending Email through Gmail server in Java

Email via Gmail


This java tutorial is to send email in java using Gmail. The program will use Gmail SMTP server to send mail.

For sending email using JavaMail Api you need to import 2 jar files:

1.mail.jar
2.activation.jar

Download required jar files here..
download

package com.simplecode.email;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class JavaEmail {

	Properties emailProperties;
	Session mailSession;
	MimeMessage message;

	public static void main(String args[]) throws AddressException,
			MessagingException {

		JavaEmail javaEmail = new JavaEmail();

		javaEmail.setMailServerProperties();
		javaEmail.createEmailMessage();
		javaEmail.sendEmail();
	}

	public void setMailServerProperties() {

		// gmail's smtp port
		String emailPort = "587";

		emailProperties = System.getProperties();
		emailProperties.put("mail.smtp.port", emailPort);
		emailProperties.put("mail.smtp.auth", "true");
		emailProperties.put("mail.smtp.starttls.enable", "true");

	}

	public void createEmailMessage() throws AddressException,
			MessagingException {
		String[] toEmails = { "[email protected]" };
		String emailSubject = "Java Email";
		String emailBody = "This is an email sent by <b>JavaMail</b> api.";

		mailSession = Session.getDefaultInstance(emailProperties, null);
		message = new MimeMessage(mailSession);

		for (int i = 0; i < toEmails.length; i++) {
	message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmails[i]));
		}

		message.setSubject(emailSubject);
		// for a html email
		message.setContent(emailBody, "text/html");
		// emailMessage.setText(emailBody);// for a text email

	}

	public void sendEmail() throws AddressException, MessagingException {
		String emailHost = "smtp.gmail.com";

		// just the id alone without @ gmail.com
		String senderUsername = "your emailid here";
		String senderEmailPassword = "your email password here";

		Transport transport = mailSession.getTransport("smtp");
		transport.connect(emailHost, senderUsername, senderEmailPassword);
		transport.sendMessage(message, message.getAllRecipients());
		transport.close();
		System.out.println("Email sent successfully.");
	}

}



Note :
  • Here it is assumed that your localhost is connected to the internet and capable enough to send an email.
  • The example program uses Gmail SMTP server.
  • Mail authentication is set to true and need to give sender’s email and password. That is, we cannot send email anonymously.
  • You can add email attachment to emailMessage.

About Mohaideen Jamil