How to Send Email in Java Using SMTP?

Here you will learn how to send email in java using smtp.

JavaMail API provides the functionality for sending email. The process involves following three step.

  1. Get Session Object
  2. Compose Message
  3. Send Message

For sing JavaMail API we have to import jars mail.jar and activation.jar.

Download the jars from below link and import in your project.

Download: http://www.javatpoint.com/src/mail/mailactivation.zip

How to Send Email in Java Using SMTP?

Image Source

Send Email in Java Using SMTP Example

Below is the Java program to send email.

Make sure to change the host name, user name, password and port number according to your email provider.

package com;

import java.util.Properties;  
import javax.mail.*;  
import javax.mail.internet.*;

public class SendMail {
	public static void main(String[] args) {
		//change these according to you
		String HOST_NAME="mail.thejavaprogrammer.com";
		final String USER_NAME="contact@thejavaprogrammer.com";
		final String PASSWORD="tjp123";
		String TO="sareneeru420@gmail.com";
		
		//get session object
		Properties props = new Properties();
		props.put("mail.smtp.host",HOST_NAME);
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", "587");
		
		Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(USER_NAME,PASSWORD);
			}
		});
		
		try {
			//compose message
			MimeMessage message = new MimeMessage(session);
			message.setFrom(new InternetAddress(USER_NAME));
			message.addRecipient(Message.RecipientType.TO,new InternetAddress(TO));
			message.setSubject("Java Send Mail");
			message.setText("Testing Java Send Mail!!!");
			
			//send message
			Transport.send(message);
			
			System.out.println("Message Sent!!!");
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}
}

If everything goes fine then you will see “Message Sent!!!” in console.

Note: Disable antivirus in your system otherwise it will cause problem in sending mail.

Above java send email example program is self explanatory, if still you are facing any problem then ask your queries in comment section.

Leave a Comment

Your email address will not be published. Required fields are marked *