Code Robo
Formatter
Comparator
Tester
Merger
Converter
Utility
Java Code Complience
Validator
EncoderDecoder
Virtual Service
Java Code To Send Email Using Gmail SMTP server
       Talk to EasyAssistant

Java Send Email Functions. It uses GMail smtp server. It shows basic java code to send an email connecting to GMail server. It can be copied and used any other java java project. It uses java mail api class .


Java Send Email File Content:
package com.easycodeforall.easychat.chat;

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;

import sg.ws.tracker.trbean.PatientBean;

public class SendMail {

	public static void main(String args[]) {

		SendMail obj = new SendMail();
		obj.send();
	}

	public boolean send() {

		boolean sentEmail = false;
		String toEmailAddress = "easycodeforall@gmail.com";
		String fromAddress = "easycodeforall@gmail.com";
		String mailServerName = "smtp.gmail.com";

		Properties properties = System.getProperties();
		properties.put("mail.smtp.host", mailServerName);
		properties.put("mail.smtp.port", "465");
		// properties.put("mail.smtp.starttls.enable", "true");
		properties.put("mail.smtp.ssl.enable", "true");
		properties.put("mail.smtp.auth", "true");

		/*
		 * Get the Session object passing userid and password
		 */
		Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication("easycodeforall@gmail.com", "*********");
			}
		});

		session.setDebug(true);

		try {
			// Create a MimeMessage object.
			MimeMessage mimeMessage = new MimeMessage(session);
			mimeMessage.setFrom(new InternetAddress(fromAddress));
			mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmailAddress));
			mimeMessage.setSubject("Attention!! How is your heath today?");
			mimeMessage.setText("We could not trace you/him/her in last 24 hrs");
			Transport.send(mimeMessage);
			System.out.println("Sent message successfully....");
			sentEmail = true;
		} catch (MessagingException mex) {
			mex.printStackTrace();
		}

		return sentEmail;
	}
}



Note: If you are getting exception to connect and authenticate userid and password. Please following things.
  1. Please double cheeck the user id(email address) and password you are passing.
  2. Login to GMail. Go to gmail settings. Check the checkbox to allow Other program/api to connect gmail.



Post Your Comment:
Name :
Email ( Optional) :
Comments / Suggestion (* Required) It is required: :
: