Sending Mail Using JavaMail API and Gmail as SMTP server

The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications. The API defines classes such as Message, Session, and Transport. It includes support for the IMAP4, POP3, and SMTP protocols. Here I am going to show you how you can use this API to send mail through SMTP protocol.

First create a MailUtility class which you can use later from your client code.

public class MailUtility {

//Set Gmail as SMTP host 
private String SMTP_HOST_NAME = "smtp.gmail.com";
private String SMTP_AUTH_USER = "yourgmailid@gmail.com";
private String SMTP_AUTH_PWD = "password";

public void postMail(String recipients[], String subject,
String message, String from) throws MessagingException {
boolean debug = false;

//Set the required JavaMail session properties
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.user", SMTP_AUTH_USER);
props.put("mail.smtp.password", SMTP_AUTH_PWD);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.ssl", "true");

props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");

//Create an Authenticator. You will find the SMTPAuthenticator class defination later
Authenticator auth = new SMTPAuthenticator();

//Create a Session from the Properties and the Authenticator
Session session = Session.getInstance(props, auth);
session.setDebug(debug);

// Create a MimeMessage
MimeMessage msg = new MimeMessage(session);

// Set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);

InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);

//Set message subject and text
msg.setSubject(subject);
msg.setText(message);

//Finally now send the message.
try {
Transport.send(msg);
} catch (MessagingException messagingException) {
messagingException.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}

}

//SimpleAuthenticator is used to do simple authentication
//when the SMTP server requires it.

private class SMTPAuthenticator extends javax.mail.Authenticator {

@Override
public PasswordAuthentication getPasswordAuthentication() {
String username = SMTP_AUTH_USER;
String password = SMTP_AUTH_PWD;
return new PasswordAuthentication(username, password);
}
}
}
And here is the client code that uses the MailUtility class for sending mail.
String emailMsgTxt = "Hello, this is a test mail from my mail application.\n";
String emailSubjectTxt = "Test Mail";
String emailFromAddress = "yourgmailid@gmail.com";
String[] receipentList=
 {
      "abc@gmail.com",
      "wxx@yahoo.com"
 };
try
{
      MailUtility smtpMailSender = new MailUtility();
      smtpMailSender.postMail(receipentList, emailSubjectTxt, emailMsgTxt, emailFromAddress);
} catch (MessagingException messagingException)
{
      messagingException.printStackTrace();
} catch (Exception ex)
{
     ex.printStackTrace();
}
That's all. Another day I will describe how you can send mail asynchronously using this mail API.

15 comments:

Anonymous November 27, 2010 at 5:26 AM  

thanks for your help.
is it possible to use javamail api with ext GWT application?
because i tried to integrate it but it failed. can u help me thanks

Unknown November 27, 2010 at 5:34 AM  

Yes it is possible. I have used in my project. Can you say at which point you have failed

Anonymous November 27, 2010 at 8:40 PM  

good,
first i use Netbeans.
i download and integrate mail.jar as a library :javamail-1.4.3
when i create a class MailUtility list below the imports :
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;
and all error is gone.

when i compliled there's errors ==>

[ERROR] Line 382: No source code is available for type javax.mail.MessagingException; did you forget to inherit a required module?
[ERROR] Errors in 'file:/F:/work/java/TunisieLait/src/java/com/extjs/gxt/samples/resources/client/model/MailUtility.java'
[ERROR] Line 31: No source code is available for type javax.mail.MessagingException; did you forget to inherit a required module?
[ERROR] Line 35: No source code is available for type java.util.Properties; did you forget to inherit a required module?
[ERROR] Line 52: No source code is available for type javax.mail.Session; did you forget to inherit a required module?
[ERROR] Line 56: No source code is available for type javax.mail.internet.MimeMessage; did you forget to inherit a required module?
[ERROR] Line 59: No source code is available for type javax.mail.internet.InternetAddress; did you forget to inherit a required module?
[ERROR] Line 66: No source code is available for type javax.mail.Message.RecipientType; did you forget to inherit a required module?
[ERROR] Line 74: No source code is available for type javax.mail.Transport; did you forget to inherit a required module?
[ERROR] Line 84: No source code is available for type javax.mail.Authenticator; did you forget to inherit a required module?
[ERROR] Line 87: No source code is available for type javax.mail.PasswordAuthentication; did you forget to inherit a required module?
Finding entry point classes
[ERROR] Unable to find type 'com.extjs.gxt.samples.desktop.client.DesktopApp'
[ERROR] Hint: Previous compiler errors may have made this type unavailable
[ERROR] Hint: Check the inheritance chain from your module; it may not be inheriting a required module or a module may not be adding its source path entries properly
F:\work\java\TunisieLait\nbproject\build-gwt.xml:141: The following error occurred while executing this line:
F:\work\java\TunisieLait\nbproject\build-gwt.xml:290: Java returned: 1
BUILD FAILED (total time: 14 seconds)



it ask me to inherit the required module but there's not xml module in the library like :

so may be i need to import other library


thanks for your response
Fakhri

Unknown November 27, 2010 at 9:16 PM  

@Fakhri : You have to create the MailUtility class in the server side where the ServiceImpl classes reside

Anonymous November 27, 2010 at 9:36 PM  

ok i will try

Anonymous November 27, 2010 at 9:47 PM  

i recreate an other class MailUtilities in server side

when compiling : Errors

GWT Compiling client-side code.
Compiling module com.extjs.gxt.samples.desktop.DesktopApp
Validating newly compiled units
[ERROR] Errors in 'file:/F:/work/java/TunisieLait/src/java/com/extjs/gxt/samples/desktop/client/SpecialGrid.java'
[ERROR] Line 380: No source code is available for type com.extjs.gxt.samples.desktop.server.MailUtilities; did you forget to inherit a required module?
[ERROR] Line 382: No source code is available for type javax.mail.MessagingException; did you forget to inherit a required module?
Finding entry point classes
[ERROR] Unable to find type 'com.extjs.gxt.samples.desktop.client.DesktopApp'
[ERROR] Hint: Previous compiler errors may have made this type unavailable
[ERROR] Hint: Check the inheritance chain from your module; it may not be inheriting a required module or a module may not be adding its source path entries properly
F:\work\java\TunisieLait\nbproject\build-gwt.xml:141: The following error occurred while executing this line:
F:\work\java\TunisieLait\nbproject\build-gwt.xml:290: Java returned: 1
BUILD FAILED (total time: 21 seconds)

should i add the inherit module in DesktopApp.gwt.xml

thanks Ratul

Fakhri

Anonymous November 27, 2010 at 9:51 PM  

in the mail.jar library there's no gwt.xml module to inherit in my project, so is it the approptiate library to use or not ?

thanks Ratul
Fakhri

Unknown November 27, 2010 at 10:43 PM  

@Fakhri: If you are using the GXT Desktop module, you have to inherit this. And mail.jar is the appropriate jar for using.

Anonymous November 27, 2010 at 11:27 PM  

ah ok i think the pb will be resolve.

you know i create a methode in the client side named sendEmail() see below :

private void sendEmail() {
String emailMsgTxt = "Hello, this is a test mail from my mail application.\n";
String emailSubjectTxt = "Test Mail";
String emailFromAddress = "fakhri.kharrat@gmail.com";
String[] receipentList={"fakhri.kharrat@gmail.com","fk_kharat@yahoo.fr"};
try
{
MailUtilities smtpMailSender = new MailUtilities();
smtpMailSender.postMail(receipentList, emailSubjectTxt, emailMsgTxt, emailFromAddress);
} catch (MessagingException messagingException)
{
messagingException.printStackTrace();
} catch (Exception ex)
{
ex.printStackTrace();
}
}

this methode is activated when i clik on a button

so when i compile errors appears :
WT Compiling client-side code.
Compiling module com.extjs.gxt.samples.desktop.DesktopApp
Validating newly compiled units
[ERROR] Errors in 'file:/F:/work/java/TunisieLait/src/java/com/extjs/gxt/samples/desktop/client/SpecialGrid.java'
[ERROR] Line 380: No source code is available for type com.extjs.gxt.samples.desktop.server.MailUtilities; did you forget to inherit a required module?
[ERROR] Line 382: No source code is available for type javax.mail.MessagingException; did you forget to inherit a required module?
Finding entry point classes
[ERROR] Unable to find type 'com.extjs.gxt.samples.desktop.client.DesktopApp'
[ERROR] Hint: Previous compiler errors may have made this type unavailable
[ERROR] Hint: Check the inheritance chain from your module; it may not be inheriting a required module or a module may not be adding its source path entries properly
F:\work\java\TunisieLait\nbproject\build-gwt.xml:141: The following error occurred while executing this line:
F:\work\java\TunisieLait\nbproject\build-gwt.xml:290: Java returned: 1
BUILD FAILED (total time: 14 seconds)

i think that the pb is in client side so what can we do for this ?

thanks Ratul
Fakhri

Unknown November 28, 2010 at 7:13 AM  

Dear Fakhri, You can not use the MailUtility class in this way. The code block you have provided should be written in the server side. Create an Asynchronous Service. And write the code in the implementation of that Service. Call the async service in the button click listener. Hope this will help you.

Anonymous November 29, 2010 at 11:16 PM  

thanks Ratul :)) it's working
Fakhri

Unknown November 30, 2010 at 8:22 AM  

Welcome Fakhri :)

Unknown March 10, 2013 at 8:01 AM  

Thanks for the post Sham!! Really helpful.. Even this website http://www.compiletimeerror.com/2013/03/java-mail-api-send-email-from-java-code.html also address something similar.. Have a look.. May help..

Anonymous March 16, 2015 at 6:24 AM  

Can u please post the full code

Anonymous June 25, 2015 at 3:25 AM  

hii,
can u tel me please where i can write dopost http method in gwt,

Total Pageviews

Tags

Twitter Updates
    follow me on Twitter

    Followers