Blog

Managed File Transfer and Network Solutions

Sending Email Using Java GMail and SMTP

Posted by Van Glass on Mon, Aug 01, 2011 @ 03:51 PM


java gmailGoogle allows GMail account users to access their account using any capable email client such as Microsoft Outlook, Apple Mail.app and others. For this to work GMail provides POP and IMAP access to these client applications so that they can access emails stored on GMail servers. In addition to this, GMail provides access to its SMTP server to allow these clients to send emails through it.

In order to prevent abuse such as spamming and to provide increased security the GMail SMTP server requires that you connect using SMTP SSL and login using your account credentials prior to sending any mail.

The purpose of this article is to demonstrate how to securely connect to the GMail SMTP server and send mail using a bit of Java code which make use of com.jscape.inet.smtpssl.SmtpSsl class found in Secure iNet Factory.

The procedures in this article may also apply to other SMTP servers that provide secure SSL/TLS access.

Prerequisites

GMail account
Secure iNet Factory

 

 

Download Secure iNet Factory



Using SmtpSsl to Send Email via GMail SMTP Server

The SmtpSsl class implements basic functionality of a secure SMTP client using SSL/TLS. It supports both implicit SSL/TLS on port 465 (default) and explicit SSL/TLS using STARTTLS command on port 25.

Below is a Java code snippet that shows how to use SmtpSsl to connect to GMail using implicit SSL, authenticate and then send an email.

//import necessary classes
import com.jscape.inet.smtpssl.SmtpSsl;
import com.jscape.inet.email.EmailMessage;
         // create a new SmtpSsl instance connecting securely via port 465 using implicit SSL
         smtp = new SmtpSsl("smtp.gmail.com", 465);
         // establish secure connection
         smtp.connect();
         // login using gmail account details
         smtp.login(username, password);
         // create new email message
         EmailMessage message = new EmailMessage();
         message.setTo(to);
         message.setFrom(username);
         message.setSubject("Sending email via Gmail SMTP");
         message.setBody("This is the body of the message");
         // send message
         smtp.send(message);
         // disconnect     
         smtp.disconnect();     

Summary

This article demonstrates how straightforward and easy it is to connect to a secure SMTP server, in this case GMail, and then send an email.

References

Class SmtpSsl

Topics: Secure iNet Factory