Sending Mail From Java

Sending Mail From Java:
You can send mails from java, here using gmail smtp sample working code given.

Required Jar:

Java Program:

package in.javadomain;

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 SendMail {

	public static void main(String[] args) {

		final String fromEmailId = "gmail-username";
		final String fromEmailPwd = "gmail-password";
		final String toEmailId = "to email id";
		final String mailSub = "";
		final String mailContent = " is a website where you can get many programming tutorials,"
				+ "\n\n And solutions for many programming problems!";

		Properties gmailProps = new Properties();
		gmailProps.put("mail.smtp.auth", "true");
		gmailProps.put("mail.smtp.starttls.enable", "true");
		gmailProps.put("", "");
		gmailProps.put("mail.smtp.port", "587");

		System.out.println("Authenticating username and password");
		Session session = Session.getInstance(gmailProps,
				new javax.mail.Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(fromEmailId,
		System.out.println("Authentication Successful!");

		try {
			Message message = new MimeMessage(session);
			// To Email Id set here
			// Subject set here
			// Mail content set here
			System.out.println("Mail Sent Successfully");
		} catch (MessagingException e) {
			throw new RuntimeException(e);

Authenticating username and password
Authentication Successful!
Mail Sent Successfully

Recommended Java Books:

377 total views, 1 views today

Leave a Reply

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