How to Send Mail in Java?

A simple tutorial on how to send and receive mails using JavaMail code.

Steps to Use JavaMail

What is JavaMail?
JavaMail is a Java API which allows you to compose, write and read emails. You can use this API to send and receive electronic mail through SMTP, POP3, and IMAP. The main advantage of JavaMail is the protocol-independent and platform-independent structure for sending and receiving emails.
You can use the below given JavaMail code in your mailing forms coding portion to send and receive mail.
JavaMail Coding:
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 emailMessage;
public static void main(String args[]) throws AddressException,
MessagingException {
JavaEmail javaEmail = new JavaEmail();
public void setMailServerProperties() {
String emailPort = "587";//gmails smtp port
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 = { "enter recipient mail id here" };
String emailSubject = "Java Email";
String emailBody = "This is an email sent by JavaMail api.";
mailSession = Session.getDefaultInstance(emailProperties, null);
emailMessage = new MimeMessage(mailSession);
for (int i = 0; i < toEmails.length; i++) {
emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmails[i]));
emailMessage.setContent(emailBody, "text/html");//for a html email
//emailMessage.setText(emailBody);// for a text email
public void sendEmail() throws AddressException, MessagingException {
String emailHost = "";
String fromUser = "your emailid here";//just the id alone without
String fromUserEmailPassword = "your email password here";
Transport transport = mailSession.getTransport("smtp");
transport.connect(emailHost, fromUser, fromUserEmailPassword);
transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
System.out.println("Email sent successfully.");

Note: You can edit the highlighted portions in the coding as per your need.