Sending Email through GMail

In my last 2 posts I have shown you how to send SMTP email using Java.
But I still haven’t shown how to send an Email through a secured SMTP server.

To do so I’ll show you how to use GMail secured SMTP server to send Emails.

Take a look at this class:

	public GMail() {
		try {
			String from = "everyDayDeveloper";
			String to = "";
			String body = "bla bla ...";
			String subject = "gmail"; 
			String senderEmail = "";
			String senderPassword = "myPassword";
			MimeMessage message = new MimeMessage(getGmailSession());
			message.setFrom(new InternetAddress(from));
			  new InternetAddress(to));
		} catch (Exception e){
	public static Session getGmailSession()	{
			Properties props = System.getProperties();
			props.put("", "");
	        props.put("mail.smtp.auth", "true");
	        props.put("mail.debug", "true");
	        props.put("mail.smtp.port ", "465");
	        props.put("mail.smtp.socketFactory.port", "465");
	        props.put("mail.smtp.socketFactory.fallback", "false");
	        Session session = 
                               new javax.mail.Authenticator() {
	 protected PasswordAuthentication getPasswordAuthentication() {
	    return new PasswordAuthentication(senderEmail, senderPassword);
	        return session;

The basic is the same, like sending a simple SMTP message.

What’s different here is the creation of the Session object in the function getGmailSession().

The Session object is created with much more properties and with the Authenticator which holds the authentication properties.

You will also need the mail.jar that can be found here.

downloaddownload source

Leave a Reply

Your email address will not be published.