Send email in java

This example shows you how to send the email using Java Mail API.

Below is the example of java code which send the mail.


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.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

//Send an email in java
public class SendEmailExample {
	public static void main(String[] args) throws AddressException,
			MessagingException {

		// Set the basic data to send the email
		String from = "";
		String to = "";
		String subject = "Put your mail subject";
		String mailContent = "Put your mail content.";

		// You need to create a properties object to store mail server
		// smtp information such as the host name and the port number.
		// With this properties we create a Session object from
		// which we'll create the Message object.
		Properties properties = new Properties();
		properties.put("", "");
		properties.put("mail.smtp.port", "25");
		properties.put("mail.smtp.auth", "true");

		// Get the authenticator object to get the Session object
		Authenticator authenticator = new CustomAuthenticator();

		Session session = Session.getDefaultInstance(properties, authenticator);

		// The Message is a mail message to be send through the
		// Transport object. In the Message object we set the
		// sender address and the recipent address. Both of
		// this address is a type of InternetAddress. For the
		// recipient address we can also set the type of
		// recipient, the value can be TO, CC or BCC. In the next
		// two lines we set the email subject and the content text.
		Message message = new MimeMessage(session);
		message.setFrom(new InternetAddress(from));
		message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));

		// Send the message

	// This class is the implementation of the Authenticator
	// Where you need to implement the getPasswordAuthentication
	// to provide the username and password
	private static class CustomAuthenticator extends Authenticator {
		protected PasswordAuthentication getPasswordAuthentication() {
			String username = "username";
			String password = "password";
			return new PasswordAuthentication(username, password);