Sign In
   Developer Productivity PKGs
Enterprise Web Apps
Accounting Suite for IBM i

Send Emails Example Web Page (AVR.NET) and Project

the Essence

This technical article provides a simple AVR.NET programming example, written for sending email notifications when a new user joins a website.  From an application software developer's perspective, the essential technical feats involved are:

  • instancing the SMTP client service and reusing it
  • populating an email object based on input from the UI, an ASP.NET Web Form
  • sending the email using the SMTP client

Web Form Picture of Web Page

Why are we here?
  • To see syntactical nuances and an example for instancing and populating a mail object, and sending an email using the .NET framework 4.0 and AVR.NET


  • To see the ease of interaction between the ASP.NET GUI controls and high level language programming


  • If you are new to OO syntax, ASP.NET or Web Forms, the introductory and tutorial-like explanations may provide value

Visual Studio IDE

AVR.NET WebSite Example 1 Project


A Little More Background

AVR.NET is a .NET language developed by ASNA of San Antonio, TX.  It works with the Common Language Runtime (CLR) and the .NET Frameworks as do C#.NET and VB.NET.  The latest version we are curently working with is AVR.NET for Visual Studio 2015 (Visual RPG 14.0).  AVR.NET provides a number of features for compatibility and ease of conversion from other RPG languages.


Example Code

.aspx.vr file contents

AVR.NET
source code

web page class
Send Email Example 1



Using System
Using System.Data
Using System.Configuration
Using System.Collections
Using System.Web
Using System.Web.Security
Using System.Web.UI
Using System.Web.UI.WebControls
Using System.Web.UI.WebControls.WebParts
Using System.Web.UI.HtmlControls


BegClass SendEmailExample1 Partial(*Yes) Access(*Public) Extends(System.Web.UI.Page)

    // class level declarations hard-coded for simplicity of example
    dclfld boolSignInStatus type(*boolean) inz(*false)
    dclfld strPasswordType type(*string) inz("Registered")


    BegSr Page_Load Access(*Private) Event(*This.Load)

    dclsrparm sender type(*Object)
    dclsrparm e type(System.EventArgs)

        if (NOT Page.IsPostBack)
            //
            // Executes the first time that the page is loaded.
            //
        else
            // Runs subsequent times that the page is displayed.
        endif


    EndSr


    //************************************************************************************************************
    //  this routine is run each time this page is displayed (after the web server sends out the page)
    //  do not attempt to verify results of this routine by displaying something in the page
    //    (because the display of the page has already occurred by the time this routine runs)
    //************************************************************************************************************

    BegSr Page_Unload Access(*Private) Event(*This.Unload)

    dclsrparm sender type(*Object)
    dclsrparm e type(System.EventArgs)


    EndSr


    //************************************************
    // send 2 emails example using AVR.NET
    //************************************************

    BegSr btnSendExampleEmails_Click Access(*Private) Event(*This.btnSendExampleEmails.Click)
                       
    dclsrparm sender type(*Object)
    dclsrparm e type(System.EventArgs)

        // In a case such as this where we are sending > 1 email, it can make sense to instance the executable
        //  that sends the email only once.  Plus we get to show syntax for passing of parameters by reference
        //  in this example.

        // declare and instance the service program that will send the message and
        //  interact with the SMTP server as a client
        dclfld smtpclientService           type(System.Net.Mail.SmtpClient) New()
        // later, when the .Send method is invoked, the smtpclientService will interact with your ISP's mail server
        //  (or your in-house mail server) to authenticate and then make the email send request

        // use the new StringBuilder class to formulate the body text of the email (instead of a simple *string object
        //  type, where each change to the string value causes what is equivalent to creating a new string object and
        //  setting It's value)
        dclfld strbldrEmailBodyText     type(System.Text.StringBuilder) New(512)

        // tell the SMTP client service the IP address of the SMTP server and what port to use
        //  (based on application keys (specified in web.config))
        //  note: [] indicates an array element as in C#.NET
        smtpclientService.Host = ConfigurationManager.AppSettings["apkSMTPServerAddress"]
        smtpclientService.Port = ConfigurationManager.AppSettings["apkSMTPServerPort"]

        // set the credentials, which is basically an email account and it's password,
        // "NetworkCredential" is a type of object that can be initialized with 2 strings (shown)
        smtpclientService.Credentials = *new System.Net.NetworkCredential( +
        ConfigurationManager.AppSettings["apkSentFromEMailAddress"], +
        ConfigurationManager.AppSettings["apkSentFromEMailAddressPwd"] )

        //************************************************************
        // create and send the email to the website manager
        //************************************************************
        // pass the smtpclientService object by reference for efficiency
        // pass the email body text string builder object by reference so we can receive back the updated version
        // easiest way to explain passing by reference is: passing a pointer to the object (no duplication of the object
        //  value(s) and/or object properties and metadata occurs)
        *this.srSendNotificationEmailToWebSiteMgr(*ByRef smtpclientService, *ByRef strbldrEmailBodyText)

        //************************************************************************************************
        // create and send an email with a temporary password to the registering (new) user   
        //************************************************************************************************
        if (cbPasswordRequest.Checked *and (boolSignInStatus *ne *true *or strPasswordType *eq "Registered"))
                    dclfld strTemporaryPassword  type(*string)
           
                    // start generate random number to use as temporary password
                    dclfld TempPasswordRandom type(System.Random) New()
                    dclfld intTemporaryPassword *integer4
                    // *integer4 has a maximum of 10 digits

                    // random can generate a negative number
                    // use avr.net fuction, %abs, to obtain absolute value
                    intTemporaryPassword = %abs(TempPasswordRandom.Next())
                    strTemporaryPassword = intTemporaryPassword.ToString()
                    // end of generate random number to use as temporary password

                    *this.srSendTempPwdToContact(*ByRef smtpclientService, +
                                                                        *ByRef strbldrEmailBodyText, +
                                                                        *ByRef strTemporaryPassword)
        endif

           
    EndSr
 

    //************************************************************************** 
    // This routine sends a notification email to the website manager
    //**************************************************************************

    BegSr srSendNotificationEmailToWebSiteMgr

    dclsrparm smtpclientService        type(System.Net.Mail.SmtpClient)     by(*reference)      
    dclsrparm strbldrEmailBodyText  type(System.Text.StringBuilder)         by(*reference)

        // the service program that will send the message and interact with the SMTP server as a client has
        //  already been declared and instanced and provided with a host name and credentials

        // Declare and instance the email object
        dclfld EmailMessageObjectFPInfoRcvd type(System.Net.Mail.MailMessage) New()

        EmailMessageObjectFPInfoRcvd.From = +
            *new System.Net.Mail.MailAddress(ConfigurationManager.AppSettings["apkSentFromEMailAddress"])
           
        EmailMessageObjectFPInfoRcvd.CC.Add(ConfigurationManager.AppSettings["apkSentFromEMailAddress"])
        // the .To property became a collection in .NET 2.0
        EmailMessageObjectFPInfoRcvd.To.Add( +
                        ConfigurationManager.AppSettings["apkSendToInternalActionEMailAddress"])
        EmailMessageObjectFPInfoRcvd.Subject = ConfigurationManager.AppSettings["apkBaseURLName"] ++
                        " information request received from web site."

        // Formulate the body of the email object, EmailMessageObjectFPInfoRcvd.Body...

        // Use the new StringBuilder class so the string variable is not erased and recreated over and over
        //  the string builder object to use in building the email message body has already been
        //  declared and instanced

        // To set format of email body to HTML instead of just text (html formatting tags required for anything fancy),
        //   EmailMessageObjectFPInfoRcvd.IsBodyHtml = *true

        // %trim and .trim() are equivalent
        if (txtNewUserCode.Text <> *blank)
                    strbldrEmailBodyText.Append("The following actions were requested for " ++
                                                                     %trim(txtNewUserCode.Text))
        else
                    strbldrEmailBodyText.Append("The following actions were requested for " + txtCtcName.Text.Trim())
        endif
        if (txtCompanyName.Text <> *blank *and cbRegisterAsIndependentConsumer.Checked <> *true)
                    strbldrEmailBodyText.Append(" from " + %trim(txtCompanyName.Text))
        endif
        strbldrEmailBodyText.Append(":")

        if (cbPasswordRequest.Checked)
                    strbldrEmailBodyText.Append(Environment.NewLine + "  * Account creation requested.")
        endif
        if (cbContactMe.Checked)
                    strbldrEmailBodyText.Append(Environment.NewLine + "  * Call requested.")
        endif
        if (cbSendPromoLit.Checked)
                    strbldrEmailBodyText.Append(Environment.NewLine + "  * Promotional Literature requested.")
        endif
        EmailMessageObjectFPInfoRcvd.Body = strbldrEmailBodyText.ToString()

        Try
                    smtpclientService.Send(EmailMessageObjectFPInfoRcvd)
        Catch
                    // if that didn't work, it won't be able to send a diagnostic email either
        EndTry           

    EndSr


    //**************************************************************************************************
    // This routine sends an email with a temporary password to the registering (new) user  
    //**************************************************************************************************

    BegSr srSendTempPwdToContact

    dclsrparm smtpclientService           type(System.Net.Mail.SmtpClient)  by(*reference)      
    dclsrparm strbldrEmailBodyText     type(System.Text.StringBuilder)      by(*reference)
    dclsrparm strTemporaryPassword  type(*string)                                       by(*reference)

        // the service program that will send the message and interact with the SMTP server as a client
        // has already been declared and instanced and provided with a host name and credentials

        dclfld emailmsgSendTempPwd System.Net.Mail.MailMessage New()
           
        emailmsgSendTempPwd.From = *new System.Net.Mail.MailAddress( +
                                                                    ConfigurationManager.AppSettings["apkSentFromEMailAddress"])
        emailmsgSendTempPwd.CC.Add(ConfigurationManager.AppSettings["apkSentFromEMailAddress"])
        emailmsgSendTempPwd.To.Add(txtEmailAddress.Text)

        dclfld strBaseURLName type(*string)
        strBaseURLName = ConfigurationManager.AppSettings["apkBaseURLName"]
                       
        emailmsgSendTempPwd.Subject = "temporary password for the " + strBaseURLName + " website"

        // the string builder object to use in building the email message body has already been declared
        //  and instanced
        // init strbldrEmailBodyText back to ""
        strbldrEmailBodyText.Length = 0
                       
        strbldrEmailBodyText.Append("Dear New " +  strBaseURLName + " Website Member," ++
                                                                     Environment.NewLine + Environment.NewLine)

        strbldrEmailBodyText.Append("Thank you for your interest in " + strBaseURLName ++
                " and our company.  Here is your temporary password: " + Environment.NewLine ++
                Environment.NewLine + strTemporaryPassword + Environment.NewLine + Environment.Newline)

        strbldrEmailBodyText.Append("In order to take the next step in getting set up, please use the the +
        New User Code you recently defined along with the (above) temporary password to sign in at the +
        secured web page:" + Environment.NewLine + Environment.NewLine)
                       
        strbldrEmailBodyText.Append("https://" + ConfigurationManager.AppSettings["apkBaseURL"] ++
                         "/YourLogIn.aspx" + Environment.NewLine + Environment.NewLine)
                       
        strbldrEmailBodyText.Append("Until Later," + Environment.NewLine + "WebMaster")

        emailmsgSendTempPwd.Body = strbldrEmailBodyText.ToString()

        Try
                    smtpclientService.Send(emailmsgSendTempPwd)

        Catch e1 System.Exception
                    // if that didn't work, it won't be able to send a diagnostic email either
        EndTry           

    EndSr


Endclass

Specifying the UI controls
UI controls for the web page can be specified in XHTML and stored in the .aspx source file.  We are using the XHTML 1.1 Target Schema for Validation.



Assigning constants in web.config
One of the ways to assign constants at the website level is to store them in the web.config file.




                Site Map     Switch to
Mobile View

You are at the web site of Tegratecs Development Corp.  Click here to go to the home page of this site...
Offering Innovation & Providing ROI
while minimizing Islands of Automation
Our contact information:
Tegratecs Development Corp.®
1320 Tower Road
Schaumburg, IL 60173
847-397-0088
800-739-FPSS
( please contact us or register or sign in )
© 2012-2024