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:


Download required jar files here..


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();


	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 = { "" };
		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]));

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


	public void sendEmail() throws AddressException, MessagingException {
		String emailHost = "";

		// just the id alone without @
		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());
		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

I'm a Full stack developer of IT exp in J2EE, AngularJs, MicroServices, Docker, Spring (Boot, MVC, Cloud), Bluemix, DevOps. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

%d bloggers like this: