Приглашаем посетить
Чуковский (chukovskiy.lit-info.ru)

13.4 Controlling email with ASP and PHP server script

Table of Contents

Previous Next

13.4 Controlling email with ASP and PHP server script

13.4.1 The basic ASP framework to send email

So far we have said a great deal about browsers, ECMAScript (or client-side script), and their applications on the Web. Client-side scripting is great for animating Web pages, and performing local data validation, computations, and manipulations. However the Internet, and hence its related Web technologies, is about the creation and integration of large-scale clientserver applications. From this point of view, XHTML at large can be considered as a straight-through clientserver application on the Internet since the server pays no attention to the page content.

If you want to build real server applications on the Web, you will need to concentrate more on the server side. In particular, server scripts and their practical usage on the Web are important. You have already encountered examples of ASP and PHP server scripts in Chapter 12. In this section, we continue to explore their applications to emailing. In section 13.5 we will discuss another server language called Perl and how to use it to send email.

Since the JScript of ASP is almost identical to ECMAScript, we begin this section with ASP. ASP is a Microsoft product and widely available on PC platforms. To use ASP to send email, you need something called the Collaboration Data Objects for NT Server (CDONTS) library. CDONTS is a component of Collaboration Data Objects (CDO) and is used to build Microsoft Windows and Internet-based messaging and collaboration applications. If you, or your ISP, run a Microsoft server system such as Microsoft NT or Windows with IIS, it is likely that you already have full ASP services installed and have the ability to send emails. Hence a server environment with CDONTS support is assumed when discussing all ASP programs.

The following page illustrates one of the simplest ways to send email by using ASP.



Example: ex13-09js.asp - My First Email With ASP

 1: <%@language="JScript" %>
 2:
 3: <?xml version="1.0" encoding="iso-88591"?>
 4: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 5:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 6: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 7: <head><title>My First Email With ASP -- ex1309js.asp</title></head>
 8: <body style="font-family:arial;font-size:14pt;background:#000088">
 9:
10: <%
11:  oMail = Server.CreateObject("CDONTS.NewMail");
12:  with (oMail) {
13:    To = "John@pwt-ex.com";
14:    From = "JohnSmith@pwt-ex.com";
15:    Subject = "Hello";
16:    Body = "Just want to say Hello";
17:    Send();
18: }
19: delete oMail;
20: %>
21:
22: <div> Mr. John Smith has Sent Email To John@pwt-ex.com</div>
23: </body>
24: </html>

The first line of this page is to activate ASP and to use JScript as the main server language. Lines 29 are the normal XHTML contents that the server will happily ignore. If you have CDONTS installed, the statement in line 11



oMail = Server.CreateObject("CDONTS.NewMail");

creates a server object called oMail by using the CDONTS.NewMail feature. Since oMail (object mail) is an object, it contains all the properties and member functions given by CDONTS.NewMail. The with statement in lines 1218 is used to compose the email and send it out. In fact, if you prefer, you can use instead a direct call such as



oMail.To="John@pwt-ex.com";
oMail.From="JohnSmith@pwt-ex.com";
...
oMail.Send();

After the delivery of the email, a delete command (line 19) is used to terminate the object variable oMail. It is good programming practice to delete any object variables soon after finishing with them. Finally, line 22 is just a simple "feedback" message to acknowledge delivery. The structure in lines 1020 is the basic framework for emailing with ASP.

For VBScript users, the following program fragment should help to convert this basic framework to its equivalent VBScript application:



Listing: ex13-04.txt - Code Fragment For VBScript

 1: <%@language="VBScript" %>
 2:
 3: <%
 4: Set oMail = Server.CreateObject("CDONTS.NewMail")
 5:
 6: With oMail
 7:    .To = "John@pwt-ex.com"
 8:    .From = "JohnSmith@pwt-ex.com"
 9:    .Subject = "Hello"
10:    .Body = "Just want to say Hello"
11:    .Send
12: End With
13:
14: Set oMail = nothing
15: %>

Replacing the JScript program block by this VBScript block yields a working version of ASP to send email. One common mistake when dealing with VBScript and JScript is that JScript is case sensitive whereas VBScript is not. The capital letters used in listing ex13-04.txt are purely for the purpose of improving readability and have no effect on the server. In general, we will use JScript as the default language for ASP.

Example page ex13-09js.asp is just a framework for sending mail by using ASP. A page like this has little practical value. To turn this page into a more functional one, you need to add at least an interface to get user input.

13.4.2 A general form to send email with data validation

For emailing to work, the interface part (usually an XHTML page) should contain at least the "To," "From," "Subject," and "Message" header fields so that proper email contents can be constructed from the server side. This type of page can easily be constructed as a form application. The following is an example:



Example: ex13-10.htm - A Page To Send Email

 1:  <?xml version="1.0" encoding="iso-88591"?>
 2:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4:  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5:  <head><title> A Page To Send Email - ex1310.htm </title></head>
 6:  <style>
 7:   .tx01{font-size:14pt;color:#ffff00;font-weight:bold}
 8:   .tx02{font-family:arial;font-size:14pt;background:#ffffff;color:#000000}
 9:   .butSt{background-color:#aaffaa;font-family:arial;font-weight:bold;
10:      font-size:14pt;color:#008800;width:80px;height:30px}
11:  </style>
12:  <script src="ex13-10.js"></script>
13:  <body style="background:#000088;font-family:arial;color:#00ee00">
14:  <div align="center" style="font-size:24pt;font-weight:bold">
15:   A Page To Send Email<br /><br />
16:   <form name="uMail" id="uMail" method="post"
17:     action="ex1310js.asp">
18:   <table class="tx01">
19:   <tr><td>From: (Email Add.)</td>
20:     <td><input class="tx02" type="text" name="from" id="from"></td></tr>
21:    <tr><td>To: (Email Add.)</td>
22:     <td><input class="tx02" type="text" name="to" id="to"></td></tr>
23:    <tr><td>Subject:</td>
24:    <td><input class="tx02" type="text" name="subject" id="subject"></td>
25:    </tr><tr><td valign="top">Message:</td>
26:     <td><textarea name="message" id="message" class="tx02"
27:         rows="6" cols="40" wrap="yes"></textarea></td></tr><tr><td>
28:      <input class="butSt" type="button" value="Send" onclick="uChkMail()">
29:     </td><td><input class="butSt" type="reset" value="Reset"></td></tr>
30:    </table>
31:    </form>
32:    </div>
33:
34: <script>
35: function uChkMail()
36: {
37:  if ( !uChkAddress("from") ) document.getElementById("from").focus()
38:  else if (!uChkAddress("to") ) document.getElementById("to").focus()
39:  else if (!uChkEmp("subject")) document.getElementById("subject").focus()
40:  else document.getElementById("uMail").submit()
41:     return true
42: }
43: </script>
44:
45: </body>
46: </html>

This Web page uses table and input elements to generate the necessary "To," "From," "Subject," and "Message" user input fields for emailing. Once the Send button in line 28 is clicked, an ECMAScript function uChkMail() (user check mail) is called. Sometimes, the naming convention could be useful to improve the structure and readability of your page.

The function uChkMail()is used to check valid email address and empty fields. For example, consider the statement in line 37:



if (!uChkAddress("from")) document.getElementById("from").focus()

This statement is to check whether the "from" field is a valid email address. If the user function uChkAddress("from") returns a false value, the standard function focus() will send the cursor back to the "from" field for modification and correction. The uChkEmp() function in line 39 is a function to check an empty field. You may notice that an external file ex13-10.js is declared in line 12 and the details of the above mentioned functions are defined in this file.



Listing: ex13-10.js - External Program File For ex13-10.htm

 1:  function isEmail(valSt)
 2:  {
 3:   patSt=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.(([a-zA-Z]{2,3})|(\d{1,3})))+$/
 4:   return( patSt.test(valSt))
 5:  }
 6:
 7:  function uChkAddress(inAdd)
 8:  {
 9:   inVal = document.getElementById(inAdd).value
10:   if (isEmail(inVal)){
11:       return true
12:   } else {
13:       alert("Invalid Email Address! :"+inVal)
14:       return false
15:   }
16:  }
17:
18:
19:  function uChkEmp(inField)
20:  {
21:   inVal = document.getElementById(inField).value
22:   if (inVal =="") {
23:      alert("Empty "+ inField)
24:      return false
25:   } else {
26:      return true
27:   }
28:  }

The first function isEmail() performs a pattern-matching operation. This function will be called by the second function uChkAddress(). First, we obtain the address string by a getElementbyId() call in line 9. The address string is then tested by the isEmail function. There is a valid email address if the value of isEmail() in line 10 is true, otherwise an alert box containing an error message is displayed. The uChkEmp() function declared in lines 1928 is to check whether the tested field is an empty field and returns the appropriate true or false value.

When all the "To," "From," and "Subject" fields are checked, a system function submit() is called to submit the form and "post" all data to the form action as shown in line 16 in ex13-10.htm. The form action activates the ASP program ex13-10js.asp located in the home directory of URL www.pwt-ex.com and ultimately sends the data as an email. A screen shot of this page is given in Fig. 13.17.

Figure 13.17. ex13-10.htm

graphics/13fig17.jpg


In order to get the "To," "From," "Subject," and "Message" fields, the ASP program ex13-10js.asp needs to have a mechanism to catch them from the Web page. The ASP package contains a Request object and can be used to obtain any form data with a name. The ASP program is listed below.



Example: ex13-10js.asp - Emailing With ASP

 1: <%@language="JScript" %>
 2:  <?xml version="1.0" encoding="iso-88591"?>
 3:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 4:      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 5:  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 6:  <head><title>Emailing with ASP: ex1310js.asp </title></head>
 7:  <body style="background:#000088;font-family:arial;color:#ffff00">
 8:  <div align="left" style="font-size:18pt"><br />
 9: <%
10:  var vFrom=Request.Form("from");
11:  var vTo=Request.Form("to");
12:  var vSubject = Request.Form("subject");
13:  var vBody = Request.Form("message");
14:
15:  oMail = Server.CreateObject("CDONTS.NewMail");
16:
17:  with (objMsg) {
18:    To = vTo;
19:    From = vFrom;
20:    Subject = vSubject;
21:    Body = vBody;
22:    Send();
23:  }
24:
25:  delete oMail;
26: %>
27:      Thank you! <span style="color:#ffffff"> <%=vFrom%></span><br />
28:      An Email has been sent to
29:      <span style="color:#ffffff"> <%=vTo%></span>
30: </div>
31: </body>
32: </html>

The form data from the interface ex13-10.htm is passed to this ASP program and can be accessed using the Request.Form command. For example, Request.Form in line 10 returns the "from" data and stores it in a new variable called vFrom. This way, the program captures all "To," "From," "Subject," and "Message" fields from ex13-10.htm and stores them using appropriate variables as illustrated in lines 1013. The next step is to create the object mail oMail and to compose the contents of the email as shown in lines 1821.

Finally, a simple message (lines 2729) is used to indicate that the email has been sent. A screen shot of this page is given in Fig. 13.18.

Figure 13.18. ex13-10js.asp

graphics/13fig18.jpg


13.4.3 XHTML mailing format and attachment

Most of the mailing agents such as Outlook Express can interpret HTML/XHTML language. Also, together with CSS commands, the email message can have more freedom on style, colors, font, and animated images. The following ASP program is an example used to send an animated cartoon bomb to John@pwt-ex.com.



Example: ex13-11js.asp - Sending Animated Images With Email

 1: <%@language="JScript" %>
 2:  <?xml version="1.0" encoding="iso-88591"?>
 3:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 4:      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 5:  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 6:  <head><title>Send Animated Image: ex1311js.asp </title></head>
 7:  <body style="background:#000088;font-family:arial;color:#ffff00">
 8:  <div align="left" style="font-size:18pt"><br />
 9: <%
10: var vFrom="JohnSmith@pwt-ex.com";
11: var vTo="John@pwt-ex.com";
12: var vSubject = "A Cartoon Bomb";
13: var vBody = "<?xml version=\"1.0\" encoding=\"iso-88591\"?> "+
14:  "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" "+
15:  " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> <html "+
16:  " xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\"> "+
17:  "<head><title>Emailing with ASP: ex1311js.asp </title></head> "+
18:  "<body style=\"background:#000088;font-family:arial;color:#ffff00\"> "+
19:  "<div align=\"center\" style=\"font-size:18pt\"><br /> "+
20:  "To John With Fun <br /><br />"+
21:  "<img alt=\"pic\" src=\"bomb.gif\" /></div></body></html>"
22:
23:
24: oMail = Server.CreateObject("CDONTS.NewMail");
25:
26: with (oMail) {
27:    To = vTo;
28:    From = vFrom;
29:    Subject = vSubject;
30:    MailFormat = CdoMailFormatMime;
31:    BodyFormat = CdoBodyFormatHTML;
32:    Body = vBody;
33:    AttachURL("C:\\bomb.gif", "bomb.gif");
34:    Send();
35: }
36: delete oMail;
37: %>
38: A Cartoon Bomb has been sent to <%= vTo %>.
39: </div>
40: </body>
41: </html>

After the usual ASP and XHTML header (lines 18), this program uses variables vFrom, vTo, and vSubject to store the sender, the recipient, and the subject information of the email. The body of the mail is an XHTML page defined in lines 1321 and used to display the message "To John With Fun" (line 20) and includes an animated image called bomb.gif (line 21).

In order to send this email, you need to add some specifications to the mail object oMail. The first specification is MailFormat=CdoMailFormatMime (line 30). This statement instructs the mailing agent to handle the mail format as MIME so that you can include images and other formats in the email. More information about this format is given later in this chapter. The second specification is given in line 31. This statement informs the mailing agent that the body of the email is in HTML/XHTML format to ensure that the email body can be interpreted and displayed properly.

To include an animated picture in the email body, you need to add the statement (line 33)



AttachURL("C:\\bomb.gif", "bomb.gif");

This statement is used to attach an image file bomb.gif from drive C into your email. Thus John@pwt-ex.com will receive an email with an animated cartoon bomb as shown in Figs 13.19 and 13.20.

Figure 13.19. ex13-11js.asp

graphics/13fig19.jpg


Figure 13.20. An animated email

graphics/13fig20.jpg


Next, let's see how to include an attached file in an email. To demonstrate this, we consider a mailing list application with an attachment. This application has the following XHTML interface:



Example: ex13-12.htm - Email With Attachment

 1: <?xml version="1.0" encoding="iso-88591"?>
 2:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4:  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5:  <head><title> Email With Attachment - ex1312.htm</title></head>
 6:  <style>
 7:   .tx01{font-size:14pt;color:#ffff00;font-weight:bold}
 8:   .tx02{font-family:arial;font-size:14pt;background:#ffffff;color:#000000}
 9:   .butSt{background-color:#aaffaa;font-family:arial;font-weight:bold;
10:      font-size:14pt;color:#008800;width:80px;height:30px}
11:  </style>
12:  <body style="background:#000088;font-family:arial;color:#ffff00">
13:  <div align="center" style="font-size:18pt"><br />
14:    Please Join Our Mailing List<br />
15:  <form method="post" action="ex13-12js.asp">
16:  <table class="tx01">
17:   <tr><td>Name:</td>
18:    <td><input class="tx02" type="text" name="name" id="name"></td></tr>
19:   <tr><td>Email:</td>
20:    <td><input class="tx02" type="text" name="email" id="email"></td></tr>
21:   <tr><td colspan=2>
22:     <input class="butSt" type="submit" value="Submit"></td></tr>
23:   </table>
24:   </form>
25:  </div>
26:  </body>
27:  </html>

This page is an application of XHTML form. The ASP program ex13-12js.asp in line 15 is activated when a user completes the form and the Submit button is pressed. This program will process the input data (name and email) and send an email to the user with an attached file. The coding of this ASP program is given below.



Example: ex13-12js.asp - ASP Script For ex13-12.htm

 1: <%@language="JScript" %>
 2:  <?xml version="1.0" encoding="iso-88591"?>
 3:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 4:      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 5:  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 6:  <head><title>ex1312js.asp </title></head>
 7:  <body style="background:#000088;font-family:arial;color:#ffff00">
 8:  <div align="left" style="font-size:18pt"><br />
 9: <%
10: var vFrom="JohnSmith\@pwt-ex.com";
11: var vTo=Request.Form("email");
12: var vName=Request.Form("name");
13: var vSubject="Discount"
14:
15: var vBody = "<?xml version=\"1.0\" encoding=\"iso-88591\"?> "+
16:  "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" "+
17:  " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> <html "+
18:  " xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\"> "+
19:  "<head><title>Emailing with ASP: ex1310js.asp </title></head> "+
20:  "<body style=\"background:#000088;font-family:arial;color:#ffff00\"> "+
21:  "<div align=\"left\" style=\"font-size:18pt\"><br /> "+
22:  "Dear "+ vName + "<br /><br /> "+
23:  "Thank you for filling out our mailing list form. "+
24:  "As a registered customer, I would like to inform you "+
25:  "that you are entitled to a further 10% discount on all "+
26:  "brand products for the next three months.<br /><br /> "+
27:  "Sales Manager<br /> JohnSmith <br /> www.pwt-ex.com<br /> <br />"+
28:  "(PS)We have attached this month's special offer for you to consider. "
29:
30: oMail = Server.CreateObject("CDONTS.NewMail");
31: with (oMail) {
32:    To = vTo;
33:    From = vFrom;
34:    Subject = vSubject;
35:    MailFormat = CdoMailFormatMime;
36:    BodyFormat = CdoBodyFormatHTML;
37:    Body = vBody;
38:    AttachFile("C:/special.doc","special.doc");
39:    Send();
40: }
41:
42: delete oMail;
43: %>
44: <h1>Thank you!</h1>
45:      Newsletters and special discount messages will be sent to
46:      <span style="color:#ffffff"><%=vName%></span>at
47:      <span style="color:#ffffff"><%=vTo%></span>.
48: </div>
49: </body>
50: </html>

This program is simple. The first part is to get the name and email data from the interface and use this information to construct the necessary email fields (lines 1013). The email body (lines 1528) is an XHTML page and addressed to the recipient. Since the content contains XHTML language, you need to specify the MailFormat and BodyFormat as shown in lines 35 and 36. To attach a file, the following command (line 38) is used:



AttachFile("C:/special.doc","special.doc");

In this case, a Microsoft Word document called "special.doc" is attached. Figures 13.2113.24 are some screen shots of this example in action.

Figure 13.21. ex13-12.htm

graphics/13fig21.jpg


Figure 13.24. File attachment

graphics/13fig24.gif


Figure 13.22. ex13-12js.asp

graphics/13fig22.jpg


Figure 13.23. Email message

graphics/13fig23.jpg


13.4.4 Sending email with the SMTP server and check mail

Instead of using the built-in mail object of ASP, another way to send email with ASP is to contact the mail server directly. One of the most popular and reliable mail servers on systems is the SMTP mail server. As mentioned in section 13.1, you need one or more of these server identities to set up a mailing agent such as Outlook Express. Suppose the account name and identity of an SMTP server that you can use is "JohnSmith" and "smtp.pwt-ex.com" respectively. The ASP program below can be used to get the email data from an interface page and deliver the message via the SMTP server.

If you modify the XHTML interface ex13-10.htm by replacing lines 1617 by



<form name="uMail" id="uMail" method="post"
      action="ex1313.asp" >

and call this example ex13-13.htm, you will have an interface page to send email with the SMTP server. The corresponding ASP program ex13-13.asp is listed below:



Example: ex13-13.asp - Send Email With SMTP Server

 1: <%@language="JScript" %>
 2:  <?xml version="1.0" encoding="iso-88591"?>
 3:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 4:      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 5:  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 6:  <head><title> ex1313.asp <title></head>
 7:  <body style="background:#000088;font-family:arial;color:#ffff00">
 8:  <div align="center" style="font-size:18pt"><br />
 9: <%
10:
11:  var vTo=Request.Form("to");
12:  var vSubject = Request.Form("subject");
13:  var vBody = Request.Form("message");
14:
15:  oSession = Server.CreateObject("CDONTS.Session");
16:  oSession.LogonSMTP("JohnSmith", "smtpmail.pwt-ex.com");
17:  oOutbox = oSession.Outbox;
18:  oMail = oOutbox.Messages.Add();
19:
20:  with (oMail){
21:    Subject = vSubject;
22:    Text = vBody;
23:    Recipients.Add(vTo, vTo, CdoTo);
24:    Attachments.Add("special.doc" , CdoFileData, "C:/special.doc");
25:    Send();
26:  }
27:
28:  delete oMail;
29:  delete oOutbox;
30:  oSession.Logoff();
31:  delete oSession;
32: %>
33:
34:  <h1>Thank you!</h1>
35:      An Email has been sent to
36:      <span style="color:#ffffff"> <%=vTo%></span>
37: </div>
38: </body>
39: </html>

After the fields' assignment in lines 1113, CDONTS.Session is called to create an object oSession. In order to send email, you need to access the Outbox of oSession and add a message to it. For this to happen, you need to

  • call the LogonSMTP() function to log in to an SMTP server (line 16);

  • make a copy of the Outbox object oOutbox from oSession.Outbox (line 17);

  • create the mail object oMail by calling the Add() function of oOutbox.Messages (line 18).

Once you have the mail object oMail, you can send email in the same way as the mail framework of ASP mentioned earlier.

When composing the contents of the email, the add() functions are used to add the recipient and attachment (lines 23 and 24). Finally the function Send() is invoked to deliver the email.

It is good programming practice to clean up the process soon after you have finished with it so that resources can be saved. Codes in lines 2831 are used to delete all the objects and log out from the server. Finally, a simple message is used to confirm that the email has been delivered successfully.

In addition to sending email, the CDO session (CDONTS.Session) can also be used to access other mail boxes and messages. As a very simple application, the following ASP program fragment can access the inbox of an SMTP server and check the number of email messages inside.



Example: ex13-14.asp - Checking Email

 1: <%@ LANGUAGE="JScript" %>
 2:
 3: <%
 4: var oSession = Server.CreateObject("CDONTS.Session");
 5: oSession.LogonSMTP("JohnSmith", "www.pwt-ex.com");
 6: var oInbox = oSession.GetDefaultFolder(CdoDefaultFolderInbox);
 7: Response.Write("You Have "+ oInbox.Messages.Count +" In Your Mail Box");
 8:
 9: delete oInbox
10: oSession.Logoff();
11: delete oSession
12: %>

Instead of creating an Outbox object as in ex13-13.asp, this program creates an Inbox object called oInbox in line 6. Once you have this Inbox object, a direct call to the oInbox.Messages.Count property in line 7 will return the number of email messages in the box.

13.4.5 The basic PHP framework to send email

Along with ASP, another popular server scripting technology is PHP. It is a powerful, reliable, compact, and easy to use script. Most important of all, it is free. Therefore platforms such as UNIX, LINUX, Microsoft, and many others all have an implementation porting.

Basically, with PHP you don't need any additional software to send email. If you have a PHP engine up and running, you already have the ability to send email. In normal circumstances, whether your mailing agent is sendmail or SMTP, the installation of PHP includes instructions to configure them. Furthermore, PHP provides a standard command to make the process of sending email easy. This command is called mail and has the following format:



bool mail (string to, string subject, string message
      [, string additional_headers ])

The first three parameters are compulsory and used to specify the "To," "Subject," and "Message" fields. If the optional fourth string argument is presented, this string is inserted at the end of the header. This is used to add extra headers and many advanced applications are based on this structure. The function returns true if the email has been sent successfully, otherwise a false value is returned. This mail() function is generally regarded as the basic PHP framework to send email.

One simple example showing how to use mail() is listed below.



Example: ex13-15.php - Send Email With PHP I

 1: <?PHP echo"<?";?>xml version="1.0" encoding="iso-88591"<?PHP echo"?>";?>
 2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5: <head><title>Send Email With PHP I - ex1315.php</title></head>
 6: <body style="background:#000088;text-align:center;font-family:arial">
 7: <div align="center" style="font-size:18pt;color:#ffff00"><br />
 8: <?php
 9:  $vTo ="John@pwt-ex.com";
10:  $vSubject = "Tennis";
11:  $vBody = "Do you want to play tennis tomorrow?\n\n JohnSmith";
12:
13:  if(mail($vTo, $vSubject, $vBody))
14:     echo "Successfully sent the Email to $vTo.";
15:  else
16:     echo "Failed to send the Email to $vTo."
17: ?>
18: </body>
19: </html>

As discussed in Chapter 12, any codes between the bracket pair <?php and ?> will be processed by the PHP server engine before reaching the browser. The statements in lines 817 are actually PHP script. First, three PHP variables (a name with a prefix dollar sign) are used to compose the email message: $vTo, $vSubject, and $vBody. The contents of these variables are then used to activate the mail() function as shown in line 13. Upon successful delivery of the email, the echo statement in line 14 returns a text "Successfully sent the Email to John@pwt-ex.com" to the browser.

You can specify multiple recipients by putting a comma between each address inside the variable vTo. Unlike ASP or ECMAScript, the string concatenation symbol in PHP is a period ".". For example, the following PHP statement can combine a number of recipients together:



$vTo="JohnSmith@pwt-ex.com," . "John@pwt-ex.com," . "Mary@pwt-ex.com";

Another way to use the period to combine a long list of names or recipients is



$vTo .="JohnSmith@pwt-ex.com" . ",";
$vTo .="John@pwt-ex.com" . ",";
$vTo .="Mary@pwt-ex.com";

The real power of the mail() function lies in the fourth argument for additional headers. Even a general MIME header can be constructed and passed to the mailing agent. But first, you need to learn more about PHP by constructing a general form for emailing.

13.4.6 An emailing form with PHP

To develop a general emailing form with PHP, we follow the standard approach to divide the application into two parts interface and form actions. The interface part is an XHTML form. This form generates the "From," "To," "Subject," "Cc," "Bcc," and "Message" headers to get user input. The form action contains a PHP program that is used to compose the email and to perform the delivery. The XHTML page is listed as follows:



Example: ex13-16.htm - Send Email With PHP II

 1: <?xml version="1.0" encoding="iso-88591"?>
 2:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4:  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5:  <head><title>Send Email With PHP II - ex1316.htm</title></head>
 6:  <style>
 7:   .tx01{font-size:14pt;color:#ffff00;font-weight:bold}
 8:   .tx02{font-family:arial;font-size:14pt;background:#ffffff;color:#000000}
 9:   .butSt{background-color:#aaffaa;font-family:arial;font-weight:bold;
10:      font-size:14pt;color:#008800;width:80px;height:30px}
11:  </style>
12:  <script src="ex13-10.js"></script>
13:  <body style="background:#000088;font-family:arial;color:#00ee00">
14:  <div align="center" style="font-size:24pt;font-weight:bold">
15:   A Page To Send Email<br /><br />
16:   <form name="uMail" id="uMail" method="post"
17:     action="ex13-16.php">
18:   <table class="tx01">
19:   <tr><td>From: (Email Add.)</td>
20:     <td><input class="tx02" type="text" name="from" id="from"></td></tr>
21:    <tr><td>To: (Email Add.)</td>
22:     <td><input class="tx02" type="text" name="to" id="to"></td></tr>
23:    <tr><td>Subject:</td>
24:    <td><input class="tx02" type="text" name="subject" id="subject"></td>
25:    <tr><td>Cc: (Email Add.)</td>
26:     <td><input class="tx02" type="text" name="cc" id="cc"></td></tr>
27:    <tr><td>Bcc: (Email Add.)</td>
28:     <td><input class="tx02" type="text" name="bcc" id="bcc"></td></tr>
29:    </tr><tr><td valign="top">Message:</td>
30:     <td><textarea name="message" id="message" class="tx02"
31:         rows="6" cols="40" wrap="yes"></textarea></td></tr><tr><td>
32:       <input class="butSt" type="submit" value="Send"></td>
33:     <td><input class="butSt" type="reset" value="Reset"></td></tr>
34:    </table>
35:    </form>
36:    </div>
37: </body>
38: </html>

This page is an XHTML form that contains a number of the most frequently used email fields. The inputs "From" (lines 1920), "To" (lines 2122), "Subject" (lines 2324), and "Message" (lines 2931) are compulsory. Users have to fill in these fields to send mail with PHP. The remaining ones are optional.

For simplicity of coding, we don't want to use ECMAScript to validate email addresses and to check empty fields. For a more practical example, users should apply the techniques as demonstrated in ex13-10.htm to perform a client-side validation of the compulsory fields. The optional fields may be better handled on the server side. These fields will be composed as headers as demonstrated in this example.

Once the Send button is pressed, the form action calls the PHP program ex13-16.php (line 1617) and passes all the input data as parameters. Unlike ASP, form data are accessed by using the Request.Form() function. In PHP, form data are treated just like PHP variables: all you have to do is to add a dollar sign in front of the input data name. For example, you can use the variables $from, $to, $subject, $cc, $bcc, and $message to access the values of the corresponding fields.

Consider the program code ex13-16.php:



Example: ex13-16.php - A PHP Program For ex13-16.htm

 1: <?PHP echo"<?";?>xml version="1.0" encoding="iso-88591"<?PHP echo"?>";?>
 2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5: <body style="background:#000088;text-align:center;font-family:arial">
 6: <div align="left" style="font-size:18pt;color:#ffff00"><br />
 7:
 8: <?php
 9:
10:  function error_msg($msg)
11:  {
12:    echo "<script>alert(\"Error: $msg\");history.go(-1)</script>";
13:    exit;
14:  }
15:
16:  $vFrom =$from;
17:  $vTo =$to;
18:  $vSubject =$subject;
19:  $vBody = $message;
20:  $vCc = $cc;
21:  $vBcc = $bcc;
22:
23:  if(empty($vFrom)) error_msg("Empty From field!");
24:  if(empty($vTo)) error_msg("Empty To field!");
25:  if(empty($vSubject)) error_msg("Empty Subject!");
26:  if(empty($vBody)) error_msg("Empty Body! ");
27:
28:  $vHeaders = '';
29:  if(!empty($vFrom)) $vHeaders .= "From: $vFrom\n";
30:  if(!empty($vCc)) $vHeaders .= "Cc: $vCc\n";
31:  if(!empty($vBcc)) $vHeaders .= "Bcc: $vBcc\n";
32:
33:  if (mail($vTo,$vSubject,$vBody,$vHeaders))
34:  {
35:      echo "<br />Thank you! $vFrom <br /><br />";
36:      echo "An Email Has Been Sent To $vTo Successfully";
37:  } else {
38:      echo "<br />Sorry! $vFrom <br /><br />";
39:      echo " Unable To Send Your Email To $vTo .";
40:  }
41:
42: ?>
43: </div>
44: </body>
45: </html>

The main part of this program is given in lines 842. First, a PHP function error_msg() is developed so that errors can be handled properly. This error function generates an XHTML alert box to display the error message and to exit to the previous page via the history.go() function.

As can be seen from lines 1621, input data from the interface act as PHP variables and assign new local variables $vFrom, $vTo, $vSubject, $vBody, $vCc, and $vBcc. This way, if you change the names of the interface, only this portion of the program needs to be changed.

Lines 2326 are the empty string testing for the compulsory fields. Again, they are not sophisticated and used here only for demonstration purposes. The more interesting part of this program is the construction of the additional header fields in lines 2831. First, an empty header variable $vHeader is created. If the optional field is not empty, the values are concatenated into $vHeader. Continuing in this way, you can build and add any additional header that you want.

The final part of this program (lines 3340) is the actual delivery of the email by the function mail(). Some screen shots are shown in Figs 13.25 and 13.26.

Figure 13.25. ex13-16.htm

graphics/13fig25.jpg


Figure 13.26. ex13-16.php

graphics/13fig26.jpg


13.4.7 MIME format and programming attachments

Email attachments with ASP are supported directly by the CDONTS module. For PHP, however, you need to program this capability yourself. For some users, this may be a challenging task since all we have is the framework function mail().

The basic idea to program attachments is to read the attachment file and incorporate the data into the email body. You then send it as MIME format. The following PHP program fragment can be used to open and to read a file with PHP:



$fHandle = fopen("myfile", "r");
$fData = fread($fHandle, filesize("myfile"));

The first statement is to open a data file "myfile" for reading and to create a file handle called $fHandle. By using this file handle, you can read the entire file into a variable $fData (file data) with the PHP function fread().

To incorporate attachments into email, you need the MIME format. MIME is an important aspect of email and is a subject in its own right. The detail of MIME specifications is beyond the scope of this book. For our practical purposes, the following discussion should make the idea easy to understand and to implement.

In normal circumstances, the following simple PHP mail() function generates a text email:



mail("John@pwt-ex.com","Hello","Hi, John \n How are you today? \n
JohnSmith","From: JohnSmith@pwt-ex.com")

Depending on the mailer you are using, the format of the email that contains a header and a body is similar to the listing ex13-05.txt.



Listing: ex13-05.txt

 1: To:     JohnSmith@pwt-ex.com
 2: From:   John@pwt-ex.com
 3: Subject: Hello
 4: Content-type: text/plain; charset="iso-88591"
 5: Content-transfer-encoding: 7bit
 6:
 7: Hi, John
 8: How are you today?
 9: JohnSmith
10:

Lines 15 are the headers. Apart from the "To," "From," and "Subject," the header statement in line 4 specifies the email as a plain text document by using us-ascii (i.e., US ASCII) as the character set. The statement in line 5 instructs the mailer to transfer the email with 7-bit encoding. Lines 79 are the contents of the body and are separated by one blank line.

For an email with an attachment, the typical MIME format would be like this:



Listing: ex13-06.txt

 1: To:        JohnSmith@pwt-ex.com
 2: From:      John@pwt-ex.com
 3: Subject:   Hello
 4: MIME-Version: 1.0
 5: Content-type: multipart/mixed;
 6: boundary="boundary_string"
 7:
 8: This is a MIME encoded message.
 9:
10: --boundary_string--
11: Content-type:text/plain; charset="iso-88591"
12: Content-transfer-encoding: 7bit
13:
14: Hi, John
15: How are you today?
16: JohnSmith
17: (PS) I have attached a document for you.
18:
19: --boundary_string--
20: Content-type:application/octet-stream;name=proposal
21: Content-transfer-encoding:base64
22:
23:   #### File Data ####
24:     ### ### ### ###
25:   #### File Data ####
26:
27: --boundary_string--
28:

Lines 19 are the headers in MIME format. After the usual email fields, the version of the MIME format is specified in line 4. The Content-type of this email is multipart/mixed so that applications, attachments, as well as text messages can be mixed together. In order to separate different contents, a boundary is defined in line 6. The boundary_string is usually a unique long (32 characters) string that is used to separate multiple contents of the email body. The remaining part of this header (lines 79) is some information for the mailer.

The email body consists of two parts separated by the boundary_string. The first part (lines 1019) is a normal text message. The second part (lines 2027) contains the data of an application. The name of the application is "proposal" and is transmitted as a stream of octet data in base 64 encoding. The actual file data appear one blank line after the encoding statement and before the next boundary_string.

In order to program attachments, you may need to generate the email in MIME format as in ex13-06.txt. First, you construct an XHTML page as the interface part.



Example: ex13-17.htm - Email With MIME Type

 1: <?xml version="1.0" encoding="iso-88591"?>
 2:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4:  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5:  <head><title> Email With MIME Type  ex1317.htm</title></head>
 6:  <style>
 7:   .tx01{font-size:14pt;color:#ffff00;font-weight:bold}
 8:   .tx02{font-family:arial;font-size:14pt;background:#ffffff;color:#000000}
 9:   .butSt{background-color:#aaffaa;font-family:arial;font-weight:bold;
10:      font-size:14pt;color:#008800;width:80px;height:30px}
11:   .butSt2{background-color:#aaffaa;font-family:arial;font-weight:bold;
12:      font-size:14pt;color:#008800;width:320px;height:30px}
13:  </style>
14:  <body style="background:#000088;font-family:arial;color:#00ee00">
15:  <div align="center" style="font-size:24pt;font-weight:bold">
16:   A Page To Send Email<br /><br />
17:   <form name="uMail" id="uMail" method="post"
18:     action="ex13-17.php">
19:   <table class="tx01">
20:   <tr><td>From: (Email Add.)</td>
21:     <td><input class="tx02" type="text" name="from" id="from"></td></tr>
22:    <tr><td>To: (Email Add.)</td>
23:     <td><input class="tx02" type="text" name="to" id="to"></td></tr>
24:    <tr><td>Subject:</td>
25:    <td><input class="tx02" type="text" name="subject" id="subject"></td>
26:    <tr><td>Attachment Name: </td>
27: <td><input class="tx02" type="text" name="attname" id="attname"></td></tr>
28:    <tr><td>Attachment File:</td>
29: <td><input type="file" class="butSt2" name="attfile" id="attfile"></td>
30:    </TR>
31:    </tr><tr><td valign="top">Message:</td>
32:     <td><textarea name="message" id="message" class="tx02"
33:         rows="6" cols="40" wrap="yes"></textarea></td></tr><tr><td>
34:       <input class="butSt" type="submit" value="Send"></td>
35:     <td><input class="butSt" type="reset" value="Reset"></td></tr>
36:    </table>
37:    </form>
38:    </div>
39: </body>
40: </html>

This page is a form application that is used to obtain the "From," "To," "Subject," and "Attachment Name" information from the users. The only new feature is the input statement given in lines 2829:



<input type="file" class="butSt2" name="attfile" id="attfile">

This statement generates an open-file window so that the attachment file (attfile) can be picked up by using a mouse click. Once the Send button is pressed, the following PHP program, ex13-17.php, is called and generates the MIME format as illustrated in ex13-06.txt.



Example: ex13-17.php - A PHP Program For ex13-17.htm

 1: <?PHP echo"<?";?>xml version="1.0" encoding="iso-88591"<?PHP echo"?>";?>
 2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5: <body style="background:#000088;text-align:center;font-family:arial">
 6: <div align="left" style="font-size:18pt;color:#ffff00"><br />
 7:
 8: <?php
 9:  global $vFrom, $vTo, $vSubject, $vBody;
10:  global $vAttName, $vAtt, $vAttSize, $vHeaders;
11:
12:  $vFrom =$from;
13:  $vTo =$to;
14:  $vSubject =$subject;
15:  $vBody = $message;
16:
17:  $vAttName = $attname;
18:  $vAtt = $attfile;
19:  $vAttSize = filesize($vAtt);
20:
21:  $vHeaders="From: $vFrom\n";
22:
23:  include "ex1317.inc";
24:
25:  if (!empty($vAttName) && ($vAttSize >0) )
26:  {
27:     myAttachment();
28:  } else {
29:    $vHeaders .= "Content-type: text/plain; charset=\"iso-88591\" \n";
30:    $vHeaders .= "Content-transfer-encoding: 7bit \n\n";
31:  }
32:
33:  if (mail($vTo,$vSubject,$vBody,$vHeaders))
34:  {
35:      echo "<br />Thank you! $vFrom <br /><br />";
36:      echo "An Email Has Been Sent To $vTo Successfully";
37:  } else {
38:      echo "<br />Sorry! $vFrom <br /><br />";
39:      echo " Unable To Send Your Email To $vTo .";
40:  }
41:
42: ?>
43: </div>
44: </body>
45: </html>

The first part of this PHP program is to get the interface data from ex13-17.htm including the "Attachment Name" and "Attachment File" in lines 17 and 18. If the attachment name is not empty and the corresponding file size is bigger than zero (line 25), you are well prepared for an attachment. The function myAttachment() is called to generate the necessary MIME format. This function is defined in the external PHP file ex13-17.inc as an included file of ex13-17.php (line 23). If you don't have an attachment, the usual text headers are generated as in lines 2930. The final part (lines 3340) of the program is to send the email off.

The included file ex13-17.inc is listed as follows:



Example: ex13-17.inc - An Include File For ex13-17.php

 1: <?php
 2:  function myAttachment()
 3:  {
 4:   global $vBody;
 5:   global $vAttName, $vAtt, $vHeaders;
 6:
 7:   $fileHandle = fopen($vAtt, "r");
 8:   $fileData = fread($fileHandle, filesize($vAtt));
 9:   $fileData = chunk_split(base64_encode($fileData));
10:
11:   $vBoundaryString = md5(uniqid(time()));
12:   $lHeaders = $vHeaders;
13:   $lHeaders .= "MIME-Version: 1.0\n";
14:   $lHeaders .= "Content-type: multipart/mixed;
15:         boundary=\"$vBoundaryString\" \n\n";
16:   $lHeaders .= "This is a MIME encoded message. \n\n";
17:
18:   $lBody = "--$vBoundaryString-- \n";
19:   $lBody .= "Content-type:text/plain; charset=\"iso-88591\" \n";
20:   $lBody .= "Content-transfer-encoding:7bit \n\n";
21:   $lBody .= "$vBody \n";
22:   $lBody .= "--$vBoundaryString-- \n";
23:   $lBody .= "Content-type:application/octet-stream;name=$vAttName \n";
24:   $lBody .= "Content-transfer-encoding:base64 \n\n";
25:   $lBody .= $fileData . "\n\n";
26:   $lBody .= "--$vBoundaryString--";
27:   $vBody = $lBody;
28:   $vHeaders .= $lHeaders;
29:  }
30: ?>

Global variables are used in this page to simplify variable passing. Soon after the variable declarations, you open the attachment file, read the data, and prepare the data into chunks of base 64 encoded streams. The streams are stored in the variable $fileData ready to be transmitted as an attachment.

The next step is to define the boundary string $vBounddaryString (line 11). In order to have a unique string, we call the UNIX time function time(), convert it into a unique identifier, and finally call the md5() function to transform it to a 32-character string. Since the md5() function provides 2128 different possibilities, there will be virtually no chance of a repeated boundary string.

The remaining task is to construct the header and the body in MIME format. A local variable $lHeaders is used to generate and store the header (lines 1215). Another local variable, $lBody, is used to generate the email body. Since we designed one message and one attachment only, the $lBody has two parts separated by the boundary string $vBoundaryString. The first part (lines 1921) is the email itself and the content is the user input in variable $vBody. The second part is the attachment and the file data are copied into $lBody as shown in line 25. Finally, the header and body are copied back to the global variables $vHeader and $vBody. When you have finished all the statements of this function, you then have all the required information to deliver the email with an attachment by making the function call



mail($vTo,$vSubject,$vBody,$vHeaders)

Some screen shots are shown in Figs 13.27 and 13.28.

Figure 13.27. ex13-17.htm

graphics/13fig27.jpg


Figure 13.28. Email with attachment

graphics/13fig28.jpg


    Table of Contents

    Previous Next