This post describes how we can configure JavaMail Sessions in Glassfish Server.
It is very easy to construct a mailing logic If a JavaMail Session is pre-configured in Application server. In JavaEE 7, you can fetch a JavaMail Session configured in the Application Server using @Resource annotation.
@Resource
This annotation is available under javax.annotation package.
Note: In JavaEE, @EJB, @PersistenceContext, @PersistenceUnit, @Inject, @WebServiceRef, @Resource are some of the annotations used for dependecny injection.
@Resource
This annotation is mainly used to inject several resources such as JDBC data sources, JMS connection factories & destinations, JavaMail Sessions, Timer service, etc..
Here, we will see how to configure JavaMail Sessions in Glassfish Server and fetch the resource using @Resource annotation.
We can configure a JavaMail Session in Glassfish server in three ways:
1. Using Admin Console - a web page
URL: http://localhost:4848/common/index.jsf
2. Using Glassfish Server Command-Line Tool (CLI) : asadmin
3. Using a Glassfish Server XML Resource Configuration file
( glassfish-resources.xml )
First Way:
1. Using admin console:
>>> Start the Glassfish server.
you can start using a command line tool: asadmin
you can find asadmin (bat/sh file) -navigate to bin folder of your Glassfish Server location on file system.
eg: /home/dinesh/glassfish/bin (on Linux)
C:\Softwares\Glassfish\bin (On Windows)
Command to start the Glassfish server using CLI:
>asadmin start-domain
Note: This is best way to start the server. But you can do this very easily if you are using any IDE.
>>> Once the server is started properly - open a browser - go to
http://localhost:4848/common/index.jsf
you should see admin console.
>>> On left-side Tree Pane - Select Resources -> JavaMail Sessions
You should see the web page like this:
>>> Click the New... button, then configure the JavaMail Session Details.
In the example, I have configured like this:
Important Details to be Entered:
JNDI Name: * mail/myOwn
Note: Generally JNDI names have some default naming conventions like for JDBC starts with "jdbc/" .So here, this should be prefixed with "mail/".
Mail Host: * smtp.gmail.com
Mail host for gmail is smtp.gmail.com
Default User: * donthadineshkumar
(username for connecting to mail server - from mail id remove the @gmail.com )
Here, you can set your mail username
Default Sender Address: * donthadineshkumar@gmail.com
(from Email address - from this mail id the mail will be sent).
Here, you can set your email address.
Note: These are the mandatory fields needs to be filled. Some defaults are already provided by Glassfish Server Admin console.
Additional Properties:
At the bottom of the same page - you need to add some important properties.
property : value
mail-smtp-auth : true
mail-smtp-starttls-enable:true
mail-smtp-port:587
mail-smtp-password: <<your password>>
I have used gmail SMTP TLS configuration. That is the reason why the smtp-port is 587 & smtp-starttls-enable property is enabled. you can also use SMTP SSL configuration where your port is 465. I think an SSL configuration may be required.
Even ways I have used SMTP TLS configuration.
Your configuration should look like this:
Additional properties (on same page- bottom)
Here, In the pic, I have blurred the place where password should be entered for the default mail user entered in the previous fields.
Now, go to upper right-side corner(on the same page) to save the configuration.
If you are properly configured your details- then this should show a success message. This completes the JavaMail Session configuration using Admin Console.
Second Way:
2. Using Glassfish Server Command-Line Tool : asadmin
As aforementioned, you must to bin folder of Glassfish Server on your file system.
>>start the server
>asadmin start-domain
This will start the Glassfish Server.
Waiting for domain1 to start ......................
Successfully started the domain : domain1
domain Location: /home/dinesh/Downloads/JavaDownloads/GlassFish_Server/glassfish/domains/domain1
Log File: /home/dinesh/Downloads/JavaDownloads/GlassFish_Server/glassfish/domains/domain1/logs/server.log
Admin Port: 4848
Command start-domain executed successfully.
asadmin>
you can configure JavaMail Session using a command
create-javamail-resource
Note: To get more on this type
asadmin>create-javamail-resource --help
From this help you can see lot of usage details.
Example:
Usage: create-javamail-resource --mailhost=mailhost --mailus
er=mailuser --fromaddress=fromaddress [--storeprotocol=imap]
[--storeprotocolclass=com.sun.mail.imap.IMAPStore] [--trans
protocol=smtp] [--transprotocolclass=com.sun.mail.smtp.SMTPT
ransport] [--enabled=true] [--debug=false] [--property=prope
rty] [--target=server] [--description=description] jndi_name
If you observe, there are properties which are specified in brackets [ ] - those are optional.
Configure like this:
(As we configured in Admin console - same details are given here)
--mailhost smtp.gmail.com
--mailuser donthadineshkumar
--fromaddress donthadineshkumar@gmail.com
Example:
create-javamail-resource --mailhost smtp.gmail.com --mailuser donthadineshkumar --fromaddress donthadineshkumar@gmail.com --property mail-smtp-auth=true:mail-smtp-starttls-enable=true:mail-smtp-port=587:mail-smtp-password=***** mail/cmdMailSession
>>>All additional properties must be separated by colon :
>>>Must be prefixed with --property
>>>Must enter your password (replace **** with your password)
Note: For Windows Users, if the above does not work then try replacing the separator using semi-colon.
After all the properties, give you JNDI name for the JavaMail Session. Please provide a unique name. Otherwise It would fail to create the resource.
Using ADMIN CONSOLE : created mail/myOwn
Using asadmin : created mail/cmdMailSession
(given a different JNDI name)
Once executed - you should see
Mail Resource mail/cmdMailSession created.
Command create-javamail-resource executed successfully.
Listing JavaMail Sessions:
You can list all the JavaMail Sessions created using a command
list-javamail-resources
adamin>list-javamail-resources
Deleting JavaMail Sessions:
you can delete JavaMail resources created earlier -using command
delete-javamail-resource
asadmin>delete-javamail-resource <<JNDI-JAVAMAIL-SESSION-NAME>>
asadmin>delete-javamail-resource mail/cmdMailSession
Third Way:
3.Using Glassfish Resource XML Configuration file
( glassfish-resources.xml)
Same Details are to be configured:
Example:
glassfish-resources.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC
"-//GlassFish.org//DTD GlassFish Application Server 3.1 Resource Definitions//EN"
"http://glassfish.org/dtds/glassfish-resources_1_5.dtd">
<resources>
<mail-resource debug="false"
enabled="true"
from="donthadineshkumar@gmail.com"
host="smtp.gmail.com"
jndi-name="mail/myXmlJavaMail"
object-type="user"
store-protocol="imap"
store-protocol-class="com.sun.mail.imap.IMAPStore"
transport-protocol="smtp"
transport-protocol-class="com.sun.mail.smtp.SMTPTransport"
user="donthadineshkumar">
<description>Configuring JavaMail Session Using glassfish-server.xml file</description>
<property name="mail-smtp-auth" value="true"/>
<property name="mail-smtp-password" value="***your password**"/>
<property name="mail-smtp-port" value="587"/>
<property name="mail-smtp-starttls-enable" value="true"/>
</mail-resource>
</resources>
Note: you can change the details -according to your usage. Properties which are labelled -RED - just change those.
glassfish-resources.xml file location in your project must look like this:
Showing in Enterprise Application Level:
ear
-> META-INF
-> application.xml
-> glassfish-resources.xml [Application scoped resources]
-> web-module
-> WEB-INF
-> web.xml
-> glassfish-web.xml
-> glassfish-resources.xml [Module scoped resources]
-> ejb-module
-> META-INF
-> ejb-jar.xml
-> glassfish-ejb-jar.xml
-> glassfish-resources.xml [Module scoped resources]
Note:
Simple Java Project : must be in META-INF folder.
Web Project: must be in WEB-INF folder.
EJB Module: must be in META-INF folder.
Even though, if there are no JavaMail Sessions in Glassfish Server, with XML configuration (glassfish-resources.xml) file, you can create a Session during deployment of the project.
Place this proper location and use the JNDI name as specified in XML configuration file.
eg: @Resource("mail/myXmlJavaMail")
Sample Example:
Here, I am using the configured JavaMail Session in a Servlet using @Resource annotation.
@Resource("mail/myOwn")
It is very easy to construct a mailing logic If a JavaMail Session is pre-configured in Application server. In JavaEE 7, you can fetch a JavaMail Session configured in the Application Server using @Resource annotation.
@Resource
This annotation is available under javax.annotation package.
Note: In JavaEE, @EJB, @PersistenceContext, @PersistenceUnit, @Inject, @WebServiceRef, @Resource are some of the annotations used for dependecny injection.
@Resource
This annotation is mainly used to inject several resources such as JDBC data sources, JMS connection factories & destinations, JavaMail Sessions, Timer service, etc..
Here, we will see how to configure JavaMail Sessions in Glassfish Server and fetch the resource using @Resource annotation.
We can configure a JavaMail Session in Glassfish server in three ways:
1. Using Admin Console - a web page
URL: http://localhost:4848/common/index.jsf
2. Using Glassfish Server Command-Line Tool (CLI) : asadmin
3. Using a Glassfish Server XML Resource Configuration file
( glassfish-resources.xml )
First Way:
1. Using admin console:
>>> Start the Glassfish server.
you can start using a command line tool: asadmin
you can find asadmin (bat/sh file) -navigate to bin folder of your Glassfish Server location on file system.
eg: /home/dinesh/glassfish/bin (on Linux)
C:\Softwares\Glassfish\bin (On Windows)
Command to start the Glassfish server using CLI:
>asadmin start-domain
Note: This is best way to start the server. But you can do this very easily if you are using any IDE.
>>> Once the server is started properly - open a browser - go to
http://localhost:4848/common/index.jsf
you should see admin console.
>>> On left-side Tree Pane - Select Resources -> JavaMail Sessions
You should see the web page like this:
>>> Click the New... button, then configure the JavaMail Session Details.
In the example, I have configured like this:
Important Details to be Entered:
JNDI Name: * mail/myOwn
Note: Generally JNDI names have some default naming conventions like for JDBC starts with "jdbc/" .So here, this should be prefixed with "mail/".
Mail Host: * smtp.gmail.com
Mail host for gmail is smtp.gmail.com
Default User: * donthadineshkumar
(username for connecting to mail server - from mail id remove the @gmail.com )
Here, you can set your mail username
Default Sender Address: * donthadineshkumar@gmail.com
(from Email address - from this mail id the mail will be sent).
Here, you can set your email address.
Note: These are the mandatory fields needs to be filled. Some defaults are already provided by Glassfish Server Admin console.
Additional Properties:
At the bottom of the same page - you need to add some important properties.
property : value
mail-smtp-auth : true
mail-smtp-starttls-enable:true
mail-smtp-port:587
mail-smtp-password: <<your password>>
I have used gmail SMTP TLS configuration. That is the reason why the smtp-port is 587 & smtp-starttls-enable property is enabled. you can also use SMTP SSL configuration where your port is 465. I think an SSL configuration may be required.
Even ways I have used SMTP TLS configuration.
Your configuration should look like this:
Additional properties (on same page- bottom)
Here, In the pic, I have blurred the place where password should be entered for the default mail user entered in the previous fields.
Now, go to upper right-side corner(on the same page) to save the configuration.
If you are properly configured your details- then this should show a success message. This completes the JavaMail Session configuration using Admin Console.
Second Way:
2. Using Glassfish Server Command-Line Tool : asadmin
As aforementioned, you must to bin folder of Glassfish Server on your file system.
>>start the server
>asadmin start-domain
This will start the Glassfish Server.
Waiting for domain1 to start ......................
Successfully started the domain : domain1
domain Location: /home/dinesh/Downloads/JavaDownloads/GlassFish_Server/glassfish/domains/domain1
Log File: /home/dinesh/Downloads/JavaDownloads/GlassFish_Server/glassfish/domains/domain1/logs/server.log
Admin Port: 4848
Command start-domain executed successfully.
asadmin>
you can configure JavaMail Session using a command
create-javamail-resource
Note: To get more on this type
asadmin>create-javamail-resource --help
From this help you can see lot of usage details.
Example:
Usage: create-javamail-resource --mailhost=mailhost --mailus
er=mailuser --fromaddress=fromaddress [--storeprotocol=imap]
[--storeprotocolclass=com.sun.mail.imap.IMAPStore] [--trans
protocol=smtp] [--transprotocolclass=com.sun.mail.smtp.SMTPT
ransport] [--enabled=true] [--debug=false] [--property=prope
rty] [--target=server] [--description=description] jndi_name
If you observe, there are properties which are specified in brackets [ ] - those are optional.
Configure like this:
(As we configured in Admin console - same details are given here)
--mailhost smtp.gmail.com
--mailuser donthadineshkumar
--fromaddress donthadineshkumar@gmail.com
Example:
create-javamail-resource --mailhost smtp.gmail.com --mailuser donthadineshkumar --fromaddress donthadineshkumar@gmail.com --property mail-smtp-auth=true:mail-smtp-starttls-enable=true:mail-smtp-port=587:mail-smtp-password=***** mail/cmdMailSession
>>>All additional properties must be separated by colon :
>>>Must be prefixed with --property
>>>Must enter your password (replace **** with your password)
Note: For Windows Users, if the above does not work then try replacing the separator using semi-colon.
After all the properties, give you JNDI name for the JavaMail Session. Please provide a unique name. Otherwise It would fail to create the resource.
Using ADMIN CONSOLE : created mail/myOwn
Using asadmin : created mail/cmdMailSession
(given a different JNDI name)
Once executed - you should see
Mail Resource mail/cmdMailSession created.
Command create-javamail-resource executed successfully.
Listing JavaMail Sessions:
You can list all the JavaMail Sessions created using a command
list-javamail-resources
adamin>list-javamail-resources
Deleting JavaMail Sessions:
you can delete JavaMail resources created earlier -using command
delete-javamail-resource
asadmin>delete-javamail-resource <<JNDI-JAVAMAIL-SESSION-NAME>>
asadmin>delete-javamail-resource mail/cmdMailSession
Third Way:
3.Using Glassfish Resource XML Configuration file
( glassfish-resources.xml)
Same Details are to be configured:
Example:
glassfish-resources.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC
"-//GlassFish.org//DTD GlassFish Application Server 3.1 Resource Definitions//EN"
"http://glassfish.org/dtds/glassfish-resources_1_5.dtd">
<resources>
<mail-resource debug="false"
enabled="true"
from="donthadineshkumar@gmail.com"
host="smtp.gmail.com"
jndi-name="mail/myXmlJavaMail"
object-type="user"
store-protocol="imap"
store-protocol-class="com.sun.mail.imap.IMAPStore"
transport-protocol="smtp"
transport-protocol-class="com.sun.mail.smtp.SMTPTransport"
user="donthadineshkumar">
<description>Configuring JavaMail Session Using glassfish-server.xml file</description>
<property name="mail-smtp-auth" value="true"/>
<property name="mail-smtp-password" value="***your password**"/>
<property name="mail-smtp-port" value="587"/>
<property name="mail-smtp-starttls-enable" value="true"/>
</mail-resource>
</resources>
Note: you can change the details -according to your usage. Properties which are labelled -RED - just change those.
glassfish-resources.xml file location in your project must look like this:
Showing in Enterprise Application Level:
ear
-> META-INF
-> application.xml
-> glassfish-resources.xml [Application scoped resources]
-> web-module
-> WEB-INF
-> web.xml
-> glassfish-web.xml
-> glassfish-resources.xml [Module scoped resources]
-> ejb-module
-> META-INF
-> ejb-jar.xml
-> glassfish-ejb-jar.xml
-> glassfish-resources.xml [Module scoped resources]
Note:
Simple Java Project : must be in META-INF folder.
Web Project: must be in WEB-INF folder.
EJB Module: must be in META-INF folder.
Even though, if there are no JavaMail Sessions in Glassfish Server, with XML configuration (glassfish-resources.xml) file, you can create a Session during deployment of the project.
Place this proper location and use the JNDI name as specified in XML configuration file.
eg: @Resource("mail/myXmlJavaMail")
Sample Example:
Here, I am using the configured JavaMail Session in a Servlet using @Resource annotation.
@Resource("mail/myOwn")
package com.mail.example;
import java.io.IOException;
import java.io.PrintWriter;
import javax.annotation.Resource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author dinesh
*/
@WebServlet(name = "MailServlet", urlPatterns = {"/MailServlet"})
public class MailServlet extends HttpServlet {
@Resource(name = "mail/myOwn")
private Session mailSession;
/**
* Processes requests for both HTTP GET and POST
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
Message message = new MimeMessage(mailSession);
String toUser = request.getParameter("tomailid");
String sub = request.getParameter("subject");
String msg = request.getParameter("msg");
out.println("");
out.println("");
out.println("");
out.println("Servlet MailServlet ");
out.println("");
out.println("");
try {
message.setSubject(sub);
message.setRecipient(Message.RecipientType.TO, new InternetAddress(toUser));
message.setText(msg);
Transport.send(message);
out.println("Message Sent SuccessFully..please check your mail");
} catch (MessagingException ex) {
out.println("Oops! Got an Exception");
out.println(ex.toString());
}
out.println("");
out.println("");
}
}
/**
* Handles the HTTP POST method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Servlet uses glassfish mail resources - preconfigured";
}}
Download Complete Example: Source Code
Note: Can be imported into NETBEANS IDE.
Execution Steps:
>>Download Code - Open In Netbeans IDE
>> First create JavaMail Sessions - in any of three ways.
>> Just change the JavaMail Session name in @Resource("<<your JNDI name>>")
Useful Links:
Glassfish asadmin commands - Read more...
More on glassfish-resources.xml file placement Read More...
Hope you like it - Please Share ☺




No comments:
Post a Comment