Sending Mail From Java

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

Required Jar:
javax.mail

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 = "Javadomain.in";
		final String mailContent = "Javadomain.in 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("mail.smtp.host", "smtp.gmail.com");
		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,
								fromEmailPwd);
					}
				});
		System.out.println("Authentication Successful!");

		try {
			Message message = new MimeMessage(session);
			// To Email Id set here
			message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(toEmailId));
			// Subject set here
			message.setSubject(mailSub);
			// Mail content set here
			message.setText(mailContent);
			Transport.send(message);
			System.out.println("Mail Sent Successfully");
		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}
	}
}

Output:
Authenticating username and password
Authentication Successful!
Mail Sent Successfully

Recommended Java Books:

244 total views, 0 views today

Leave a Reply

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