DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Cookies Revisited: A Networking Solution for Third-Party Cookies
  • A Beginner's Guide to Spark UI: Concepts and How to Use It
  • Multi-Tenant .NET Applications With Keycloak Realms
  • Observability and DevTool Platforms for AI Agents

Trending

  • Data Lake vs. Warehouse vs. Lakehouse vs. Mart: Choosing the Right Architecture for Your Business
  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 1
  • Operational Principles, Architecture, Benefits, and Limitations of Artificial Intelligence Large Language Models
  • Endpoint Security Controls: Designing a Secure Endpoint Architecture, Part 2
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Sending an Email using the JavaMail Session and Glassfish

Sending an Email using the JavaMail Session and Glassfish

I decided to share some tips about this EE environment javaMail api configuration.

By 
Slim Ouertani user avatar
Slim Ouertani
·
Jun. 25, 12 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
50.6K Views

Join the DZone community and get the full member experience.

Join For Free

Purpose

This tutorial is a supplement to the article of oracle published here.

After reading this later, I decided to share some tips about this EE environment javaMail api configuration.

Introduction

Two years ago, we decided to move to JEE 6 for our enterprise solutions and take a lot of fun with new EJB 3.1 features and annotations. Glassfish has made our lives easier, it was very easy to declare variables using it's administration console.

Less complicated than using global resource environment for properties It is also the continuation to this tricks this tutorial delegate to Glassfish EE server managing mail session.

Prerequisites

Before starting this tutorial, you should:

Fully understand of http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/javamail/javamail.html

Have access to an SMTP server. You must know the host name, port number, and security settings for your SMTP server. Web mail providers may offer SMTP access, view your email account settings or help to find further information. Be aware that your user name is often your full email address and not just the name that comes before the @ symbol.

Have basic familiarity with Servlets and CDIs (helpful but not required)

Create a Java mail session resource

To create and JavaMail Session :

  1. start galssfish server
  2. open admin console ( default localhost:4848)
  3. Go to Resources -> JavaMail Sessions -> click new to add new javaMail resource
  4. make sure the following field are filled in :


  1. Jndi name : EMailME for example, will be used later on lookup resource :
    @Resource(lookup = "EMailME")
  2. Mail host
  3. Default user
  4. Default sender will be used later on mailSession.getProperty("mail.from")

5- For secure Mail add this advanced setting :

1-mail.smtp.password : email password

2-mail.smtp.port : email port

3-mail.smtp.auth : true


This screenshot summarizes all these parameters :

Java Mail Session

II - Using email Service


This tutorial is a supplement to oracle one. We will use CDI with the same example.


1 - MailSessionBean Will be a CDI bean with RequestScope

2- Inject the full JavaMail Session as resource rather than create it


@Named
@RequestScoped
public class EmailSessionBean {

    @Resource(lookup = "EMailME")
    private Session mailSession;

    public void sendEmail(String to, String subject, String body) {
        MimeMessage message = new MimeMessage(mailSession);
        try {

            message.setFrom(new InternetAddress(mailSession.getProperty("mail.from")));
            InternetAddress[] address = {new InternetAddress(to)};
            message.setRecipients(Message.RecipientType.TO, address);
            message.setSubject(subject);
            message.setSentDate(new Date());
            message.setText(body);

            Transport.send(message);
        } catch (MessagingException ex) {
            ex.printStackTrace();
        }
    }
}

Look short !

4- EmailServlet remind the same except using @Inject rather than @EJB


@WebServlet(name = "EmailServlet", urlPatterns = {"/EmailServlet"})
public class EmailServlet extends HttpServlet {

    @Inject
    private EmailSessionBean emailBean;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 .........
   }
 ......
}

Conclusion

Let's EE Server manager MailSession for us, keep configuration on server and thanks to Glassfish administration console managing JavaMail Session became easier.

Session (web analytics) JavaMail GlassFish

Opinions expressed by DZone contributors are their own.

Related

  • Cookies Revisited: A Networking Solution for Third-Party Cookies
  • A Beginner's Guide to Spark UI: Concepts and How to Use It
  • Multi-Tenant .NET Applications With Keycloak Realms
  • Observability and DevTool Platforms for AI Agents

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!