How to send email in JAVA using JAVA Mail API ?

 

In this post I am going to show how to send emails using java. Here I have taken a standalone application to show how to run, but the same code can be used in any java web application to send emails. For sending emails we need JAVA MAIL API. This API provides a framework independent of any protocol and any platform to send electronic mails. Various protocols like SMTP, POP, IMAP etc. are supported by this API.

Resources Required:

Mail.jar – This is the jar which is a bundle of java mail API.

Here I am using Gmail SMTP server to send emails (its free). You can use other SMTP host provider or can install any of the SMTP server providers like Apache James Server, Podcast server and use them.

File:

EmailUtility.java
This class contains two methods sendMail() and main().

To send email we have to get the mail Session object by providing details like hostname, port, username, password etc. After getting the session object we have to create Message object and have to set the mail subject, to addresses, from address, message etc and the using Transport we can send the mail.

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

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 EmailUtility {
	public void sendMail(List<String>toAddress, String mailIdFrom, String message){
		
		final String username = "your_mail@gmail.com";
		final String password = "your@password";
		String smtpHost = "smtp.gmail.com";
		String smtpPort = "587";
		
		//setting the server properties
		Properties properties = newProperties();
		properties.put("mail.smtp.auth", "true");
		properties.put("mail.smtp.starttls.enable", "true");
		properties.put("mail.smtp.host", smtpHost);
		properties.put("mail.smtp.port", smtpPort);
		
		//getting the session object
		Session session = Session.getInstance(properties,
			new javax.mail.Authenticator() {
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(username, password);
				}
			}
		);

		try {
			// Create a default MimeMessage object.
			Message msg = new MimeMessage(session);
			// Set From: header field of the header.
			msg.setFrom(new InternetAddress(mailIdFrom));

			//preparing address array for sending mails to multiple recipient
			InternetAddress address[] = new InternetAddress[toAddress.size()];
			for(inti=0;i<toAddress.size();i++){
				address[i] = new InternetAddress(toAddress.get(i));
			}
			// Set To: header field of the header.
			msg.addRecipients(javax.mail.Message.RecipientType.TO,address);
			//setting mail subject
			msg.setSubject("Mail Testing");
			//setting the message to send
			msg.setText(message);
			//sending the message
			Transport.send(msg);

			System.out.println("Mail sent successfully");

		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}
	}
	public static void main(String[] args) {
		List<String>toAddresses = new ArrayList<String>();
		toAddresses.add("acd@gmail.com");
		toAddresses.add("xyz@hotmail.com");
		
		String message = "Testing email";
		
		newEmailUtility().sendMail(toAddresses,"youremail@test.com", message);
	}
}

Note:Before running the above application try to ping the SMTP Host from your system. If ping is successful then mail will be sent successfully else running it will throw exception and mail can’t be sent. Because the application will be unable to connect to the SMTP server.

COMMENTS ( 2 )

Great post. I found myself checking constantly this web site and
I am impressed! Extremely helpful info specially the last part
:) I maintain such info much. I used to be seeking this certain information for any long time.
Thanks a lot and better of luck.

Reply

Leave a comment

SUBSCRIBE TO NEWSLETTER

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Categories