Send An Email Using A Bean

CK1820 
Created at Aug 30, 2007 23:37:08 
41   0   0   0  
This JSP snippets shows how to send an email using a reuasable javabean

<!-- SendMail.jsp -->
<HTML>
  <HEAD>

  <TITLE>JSP Sample - Send Email</TITLE>
  </HEAD>
  <BODY background="../../images/Background.gif">
  <CENTER>
  <BR>
  <%--
    Prepare the inputs and call the bean method to send the
    mail using the API

  --%>
  <jsp:useBean id="sendMail" class="SendMailBean" scope="page" />
  <%
    String l_from    = request.getParameter("p_from");
    String l_to      = request.getParameter("p_to");
    String l_cc      = request.getParameter("p_cc");
    String l_bcc     = request.getParameter("p_bcc");
    String l_subject = request.getParameter("p_subject");
    String l_message = request.getParameter("p_message");

    String l_smtpSvr = request.getParameter("p_smtpServer");
    session.setAttribute("smtpServer",l_smtpSvr);
    String l_result  = sendMail.send(l_from,l_to,l_cc,l_bcc,l_subject,l_message,l_smtpSvr);
  %>
  <%= l_result %>
  <FONT SIZE=3 COLOR="blue">
  <A HREF="InputsForm.jsp">Compose Mail</A>
  </CENTER>
  </BODY>
</HTML>


// SendMailBean.java
import javax.mail.*;          //JavaMail packages
import javax.mail.internet.*; //JavaMail Internet packages
import java.util.*;           //Java Util packages

public class SendMailBean {


  public String send(String p_from,String p_to,String p_cc,String p_bcc,String p_subject,String p_message,String p_smtpServer) {
    String l_result = "<BR><BR><BR><BR><BR><BR><BR>";
    // Name of the Host machine where the SMTP server is running
    String l_host = p_smtpServer;

    // Gets the System properties
    Properties l_props = System.getProperties();


    // Puts the SMTP server name to properties object
    l_props.put("mail.smtp.host",l_host);

    // Get the default Session using Properties Object
    Session l_session = Session.getDefaultInstance(l_props,null);

    l_session.setDebug(true); // Enable the debug mode

    try {
      MimeMessage l_msg = new MimeMessage(l_session); // Create a New message

      l_msg.setFrom(new InternetAddress(p_from)); // Set the From address

      // Setting the "To recipients" addresses
      l_msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(p_to,false));

      // Setting the "Cc recipients" addresses
      l_msg.setRecipients(Message.RecipientType.CC,InternetAddress.parse(p_cc,false));

      // Setting the "BCc recipients" addresses

      l_msg.setRecipients(Message.RecipientType.BCC,InternetAddress.parse(p_bcc,false));

      l_msg.setSubject(p_subject); // Sets the Subject

      // Create and fill the first message part
      MimeBodyPart l_mbp = new MimeBodyPart();
      l_mbp.setText(p_message);

      // Create the Multipart and its parts to it
      Multipart l_mp = new MimeMultipart();
      l_mp.addBodyPart(l_mbp);


      // Add the Multipart to the message
      l_msg.setContent(l_mp);

      // Set the Date: header
      l_msg.setSentDate(new Date());

      // Send the message
      Transport.send(l_msg);
      // If here,then message is successfully sent.
      // Display Success message
      l_result = l_result + "<FONT SIZE=4 COLOR="blue"><B>Success!</B>"+
                 "<FONT SIZE=4 COLOR="black"> "+

                 "<HR><FONT color=green><B>Mail was successfully sent to </B></FONT>: "+p_to+"<BR>";
      //if CCed then,add html for displaying info
      if (!p_cc.equals(""))
        l_result = l_result +"<FONT color=green><B>CCed To </B></FONT>: "+p_cc+"<BR>";
      //if BCCed then,add html for displaying info
      if (!p_bcc.equals(""))
        l_result = l_result +"<FONT color=green><B>BCCed To </B></FONT>: "+p_bcc ;

      l_result = l_result+"<BR><HR>";
    } catch (MessagingException mex) { // Trap the MessagingException Error
        // If here,then error in sending Mail. Display Error message.
        l_result = l_result + "<FONT SIZE=4 COLOR="blue"> <B>Error : </B><BR><HR> "+
                   "<FONT SIZE=3 COLOR="black">"+mex.toString()+"<BR><HR>";
    } catch (Exception e) {

        // If here,then error in sending Mail. Display Error message.
        l_result = l_result + "<FONT SIZE=4 COLOR="blue"> <B>Error : </B><BR><HR> "+
                   "<FONT SIZE=3 COLOR="black">"+e.toString()+"<BR><HR>";

        e.printStackTrace();
    }//end catch block
    finally {
      return l_result;
    }
  } // end of method send

} //end of bean


<!-- InputForm.jsp -->
HTML>
<HEAD>
<TITLE>JSP Sample - Sending Mail using Java Mail API</TITLE>
</HEAD>
<BODY background="../../images/Background.gif">

 <SCRIPT LANGUAGE="JavaScript1.1">
    function submission1() {
      if(document.forms[0].p_from.value =="" ||
         document.forms[0].p_to.value =="" ||
         document.forms[0].p_smtpServer.value =="") {
        alert("Host,From and To fields are mandatory.");
        return;
      }

      document.forms[0].action = "SendMail.jsp";
      document.forms[0].submit();
    }
  </SCRIPT>
  <CENTER><BR>
  <br>
  <BR>
   <TABLE BGCOLOR=black WIDTH=100% CELLPADDING="1">
    <TR><TD>

     <CENTER><B><FONT COLOR=Red SIZE=3>Send Mail
    </TD></TR>
   </TABLE>
   <TABLE BORDER=0 >
    <TR>
    <TD>
      <FORM METHOD=POST>
      <TABLE BORDER=0 CELLPADDING=4>
        <TR>
              <TD ALIGN=RIGHT width="124"><b>Mail Server Host</b></TD>

              <TD ALIGN=LEFT width="298">
                <% String l_svr = (String)session.getAttribute("smtpServer"); %>
                <INPUT TYPE="text" NAME="p_smtpServer" SIZE=60
             VALUE="<%= l_svr!=null ? l_svr : "" %>" >
          </TD>
        </TR>
        <TR>
              <TD ALIGN=RIGHT width="124"><b>From</b></TD>
              <TD ALIGN=LEFT width="298">
                <INPUT TYPE=TEXT SIZE=60 MAXLENGTH=60 NAME="p_from">
          </TD>

        </TR>
        <TR>
              <TD ALIGN=RIGHT width="124"><b>To</b></TD>
              <TD ALIGN=LEFT width="298">
                <INPUT TYPE=TEXT SIZE=60 MAXLENGTH=200 NAME="p_to">
          </TD>
        </TR>
        <TR>
              <TD ALIGN=RIGHT width="124"><b>CC</b></TD>
              <TD ALIGN=LEFT width="298">
                <INPUT TYPE=TEXT SIZE=60 MAXLENGTH=200 NAME="p_cc">
          </TD>

        </TR>
        <TR>
              <TD ALIGN=RIGHT width="124"><b>BCC</b></TD>
              <TD ALIGN=LEFT width="298">
                <INPUT TYPE=TEXT SIZE=60 MAXLENGTH=200 NAME="p_bcc">
          </TD>
        </TR>
        <TR>
              <TD ALIGN=RIGHT width="124"><b>Subject</b></TD>
              <TD ALIGN=LEFT width="298">
                <INPUT TYPE=TEXT SIZE=60 MAXLENGTH=100 NAME="p_subject">
          </TD>
        </TR>

      </TABLE>
          <b>Message</b><br>
      <TEXTAREA NAME="p_message" ROWS=10 COLS=66 SIZE=2000 WRAP=HARD></TEXTAREA>
      <BR><BR>
      <CENTER>
      <INPUT TYPE=BUTTON VALUE=" Send " onClick="submission1();"> 
      <INPUT TYPE=RESET VALUE="Reset Form"><br>
      </CENTER>
      </FORM>
    </TD>
    </TR>
  </TABLE>
  </CENTER>
  </BODY>

</HTML>



Tags: Display JSP Email MimeBodyPart RDP Port RecipientType SMTP SendMail setRecipients Share on Facebook Share on X

◀ PREVIOUS
Select And Deselect All Checkboxes By Javascript
▶ NEXT
Confirm The Link Clicked
  Comments 0
Login for comment
SIMILAR POSTS

JQuery And Function Chaining (created at Aug 30, 2007)

Send Email Using C# (created at Aug 26, 2007)

How To Send An E-mail By Code (created at Aug 25, 2007)

How to send email in PHP ? (created at Oct 16, 2007)

Put Date Time on HTML (created at Oct 27, 2008)

How to print out text strings on HTML directly ? (created at Oct 27, 2008)

How to include file in JSP ? (created at Oct 27, 2008)

How to add a declaration on JSP code ? (created at Oct 27, 2008)

How to set and get sessions on JSP code ? (created at Oct 27, 2008)

How to resize image ? (updated at Dec 19, 2023)

How to send email by TIdSMTP VCL ? (created at Jul 07, 2009)

Word counting source program based on MapReduce framework (updated at Dec 17, 2023)

Copy text to clipboard in Javascript (created at May 07, 2013)

Set up an SMTP server on CentOS 7 (created at Jan 15, 2024)

OTHER POSTS IN THE SAME CATEGORY

Button That Will Show The Page's Source (created at Sep 07, 2007)

Add A Scrolling Status Bar Text To Your Site (created at Sep 07, 2007)

Add This Page To Favorites (created at Sep 05, 2007)

Code To Clear Browser History (created at Sep 05, 2007)

Remove the spaces before begin and after end of text (created at Sep 05, 2007)

How To Close A Pop-up Window ? (created at Sep 04, 2007)

Pop Up Window On Top (updated at Jan 15, 2024)

How to display message on browser status bar ? (created at Sep 04, 2007)

New Window (created at Sep 04, 2007)

Firefox Web Tweaking (created at Sep 03, 2007)

Color Table (created at Sep 03, 2007)

Cursor Changer (created at Sep 03, 2007)

Dual Scroller (created at Sep 03, 2007)

Enlarge Image (created at Sep 03, 2007)

Confirm The Link Clicked (updated at Jan 15, 2024)

Select And Deselect All Checkboxes By Javascript (created at Aug 30, 2007)

Javascript Mouse Event Handler Example (created at Aug 30, 2007)

Getting WebSearchers On Your Site (created at Aug 30, 2007)

Hiding HTML on the browser (created at Aug 30, 2007)

JQuery And Function Chaining (created at Aug 30, 2007)

How to get date time in Javascript ? (created at Aug 30, 2007)

Javascript based Alarm Clock (created at Aug 30, 2007)

Javascript implemented Calendar (created at Aug 30, 2007)

Basic Date Display (created at Aug 30, 2007)

Address Book (created at Aug 29, 2007)

Displays the number of pages that the users browser has displayed in its session (created at Aug 29, 2007)

Greeting For The Time Of Day (created at Aug 29, 2007)

Access Granted (created at Aug 29, 2007)

Cookie enabled browser checking in Javascript (created at Aug 29, 2007)

Cookie Redirect (created at Aug 29, 2007)

UPDATES

Creating a Pinterest-Style Card Layout with Bootstrap and Masonry (created at Apr 24, 2024)

Mastering Excel Data Importation in PHP (updated at Apr 24, 2024)

JSON format control in PHP (updated at Apr 24, 2024)

Equal Height Blocks in Bootstrap with JavaScript (created at Apr 22, 2024)

How to convert integer to text string ? (updated at Apr 22, 2024)

Checking similarity between two strings in PHP (updated at Apr 21, 2024)

Create Blob Image in HTML based on the given Text, Width and Height in the Center of the Image without saving file (updated at Apr 21, 2024)

How do I determine the client IP type (IPv4/IPv6) in PHP (updated at Apr 16, 2024)

How do I determine the client IP type in Python - IPv4 or IPv6 (updated at Apr 13, 2024)

Getting Started with PyTorch: A Beginner's Guide to Building Your First Neural Network (updated at Apr 09, 2024)

Predicting Buyer Preferences with PyTorch: A Deep Learning Approach (updated at Apr 09, 2024)

Forecasting the Weather with PyTorch: A Beginner's Guide to Temperature Prediction (created at Apr 09, 2024)

PyTorch example to Forcast Stock Price based on 10 days Dataset (created at Apr 09, 2024)

Mastering Model Persistence: Saving and Loading Trained Machine Learning Models in Python (created at Apr 08, 2024)

Harnessing the Power of Random Forest Algorithm in Python (created at Apr 08, 2024)

Understanding and Implementing K-Nearest Neighbors (KNN) Algorithm in Python (created at Apr 08, 2024)

Forecasting with Linear Regression and KNN Regression in Python (updated at Apr 07, 2024)

What is 302 Found Redirection in HTTP 1.1? (created at Apr 04, 2024)

Mastering Random Forest Regression: A Comprehensive Guide with Python Examples (updated at Apr 01, 2024)

Python Implementation of Linear Regression (updated at Apr 01, 2024)

Mastering Supervised Machine Learning with Python: A Comprehensive Guide (created at Apr 01, 2024)

Mastering AI: A Beginner's Guide to Python Programming and Beyond (created at Apr 01, 2024)

How do I create animated background for Google Meet? (updated at Mar 28, 2024)

Building a Simple DNS Server in Delphi with TTL Support (created at Mar 16, 2024)

How to force cookies, disable php sessid in URL ? (updated at Mar 16, 2024)

Implementing a Versatile DNS Server in PHP: Handling A, AAAA, CNAME, and TXT Records (updated at Mar 16, 2024)

Implementing a Versatile DNS Server in Python: Handling A, AAAA, CNAME, and TXT Records (created at Mar 16, 2024)

Building a Basic DNS Server in PHP/Python: A Beginner's Guide (updated at Mar 15, 2024)

Dynamic DNS Made Easy: Building a Python-Based Solution (created at Mar 15, 2024)

Exploring the Depths of Data Transfer: sendfile vs. kTLS (created at Mar 15, 2024)