James will now show you how one could use ASP to send out email messages. The components used in this article include CDONTS, JMail, ASPMail, and ASPEMail.
How to send email from a form continues to be one of the top asked questions on search engines and ASP sites like mine.
I've always offered you the source code for my forms (i.e. www.coveryourasp.com where you can download the entire site), but it's now time to step through the code with you and explain the code in more detail.
Do you know how to write <form>'s with ASP? If not, read that first.
Let's look at the first step after the form has been submitted - validating the inputs:
// has the form been submitted?
if ( bSubmitted )
{
// get the data from the form...
sEmail = '' + Request.Form ( "email" );
// validate the email address and moan if it fails
if ( sEmail != '' && !IsValidEmail ( sEmail, hexVeLevelDns ) )
{
// pretend the form hasn't been sent yet
bSubmitted = false;
}
}
The email address is retrieved from the form, and if not blank, it is sent into IsValidEmail( ) to be validated.
If the function returns false then I reset bSubmitted which causes the form to be re-displayed. But what does IsValidEmail( ) do?
This function resides in the utils/email.asp Server Side Include. As you can see below, the function simply calls GetEmailRating( ), and displays a message if the function fails...
function IsValidEmail ( sEmail, nLevel )
{
// test all email addresses sent in
var sEmailList = sEmail.split ( /[\s;,]/ );
var nEmail;
for ( nEmail in sEmailList )
{
if ( hexVeLevelBad == GetEmailRating ( sEmailList [ nEmail ], nLevel ) )
{
Out ( '<center><b><font color="red">"' + sEmailList [ nEmail ] + '" is an invalid email address - try again!</font></b>' );
Out ( '<br><a href="ValidateEmail.asp">(See how this email validation was done)</a></center><p>' );
return false;
}
}
return true;
}
...so we really have to look at GetEmailRating( ).
var hexVeLevelSyntax = 1;
var hexVeLevelDns = 2;
var hexVeLevelSmtp = 3;
function GetEmailRating ( sEmail, nLevel )
{
// simple syntax validation if no Hexillion component
if ( !bUseHexillion )
{
if ( IsValidEmailSyntax ( sEmail ) )
return hexVeLevelSyntax;
return hexVeLevelBad;
}
//...use HexValidEmail
To start with, I declare some global variables that are passed into these validation functions. Think of these as const's or enum's that are used to determine the level of confidence in the email address.
Pass in hexVeLevelDns and Hexillion's cool HexValidEmail component will ensure that the domain in the email address exists. These constants are also used as return values from the functions.
If we're not going to be taking advantage of HexValidEmail, and hence bUseHexillion is set to false in include/config.asp, we call a function that uses a regular expression to determine if the syntax of the email address is valid.
Thanks again to Ed Courtenay for donating the regular expression used to validate the syntax. I'll leave you to explore that and the rest of the source code concerning email validation by viewing the entire utils/email.asp source code at the end of the article.
For more information on HexValidEmail, and the 3 levels of validation it offers, see my live demonstration.
Making up the email
Having validated the email address, we need to make up the email and send it.
// make up the message body
var sBody = 'Message: "' + sMessage + '"\n\n';
if ( sFromName != '' )
sBody += 'From: "' + sFromName + '".\n';
if ( sFromEmail != '' )
sBody += 'Email: "' + sFromEmail + '".\n';
The body of the email is very simple in this case - this form is sending the information to me, so I just declare an sBody variable and add each data on a new line ( \n is a linefeed character in JavaScript, C, C++, etc ).
sBody += 'Browser: "' + Request.ServerVariables ( "HTTP_USER_AGENT" ) + '".\n';
sBody += 'IP address: "' + Request.ServerVariables ( "REMOTE_ADDR" ) + '".\n';
var dateToday = new Date();
sBody += 'Time: "' + dateToday.getHours() + ':' + dateToday.getMinutes() + '".\n';
Then, I add some more information to the email such as the user agent (browser) that was used, and the IP address of the sender. All this data and much more is available from the Request.ServerVariables collection.
Lastly, I add the time that the email was sent - note that this is server time, not the local client time...
// send Email with our generic function
SendEmail ( sFromEmail, 'Feedback@' + sHostDomain, '', sSubject, sBody );
...and send the email, again using a function defined in the utils/email.asp SSI.
Using the SendEmail( ) function
This function is used to send all the emails throughout the site - so it's the only place that cares what email system you are using. Currently, 3 components are supported, but I'll support whatever else you ask for, within reason!
• Microsofts' "Collaboration Data Objects for Windows NT Server", commonly known as CDONTS.
• Persits' ASPEmail component.
• ServerObjects' ASPMail component.
• Dimac's w3 JMail component.
The email component to use is specified by the nEmailServer setting in include/config.asp.
Using CDONTS
// get a mail object
oMail = Server.CreateObject ( "CDONTS.NewMail" );
// setup the mail
if ( sFromEmail == "" )
oMail.From = 'Anonymous';
else
oMail.From = sFromEmail;
var sEmailList = sToEmail.split ( /[\s;,]/ );
var nEmail;
var sMail = '';
for ( nEmail in sEmailList )
sMail += sEmailList [ nEmail ] + ';';
oMail.To = sMail;
sEmailList = sBccEmail.split ( /[\s;,]/ );
sMail = '';
for ( nEmail in sEmailList )
sMail += sEmailList [ nEmail ] + ';';
oMail.Bcc = sMail;
oMail.Importance = 1;
// if you want HTML mail...
// uncomment the next two lines
// oMail.BodyFormat = 0;
// oMail.MailFormat = 0;
// if you want to add an attachment...
// uncomment the next line
// oMail.AttachFile ( 'c://autoexec.bat' );
oMail.Subject = sSubject;
oMail.Body = sBody;
// send it
oMail.Send ( );
Sending a simple email is very easy. This is literally the only code I've ever used. Start by creating an instance of the CDONTS.NewMail object, then fill in the relevant properties and call the Send( ) method.
Some things to note though:
• In order to specify multiple To, Cc or Bcc recipients of a message, simply separate the addresses with a semicolon...
oMail.To = 'me@me.com;you@you.com;her@her.com'
• Although the documentation says that you can send in an optional caption to the AttachFile method, it's never worked for me!
• After the call to Send( ), the object is invalid. Do not try to use it again - you must create a new object.
Using JMail
To use JMail, set
nEmailServer=nEmailJMAIL
in include/config.asp. The SendEmail function will then execute the following code...
// get a mail object
oMail = Server.CreateObject ( "JMail.SMTPMail" );
// setup the mail
oMail.Silent = true;
oMail.ServerAddress = 'mail.' + sHostDomain;
if ( sFromEmail == "" )
oMail.Sender = oMail.ReplyTo = 'Anonymous';
else
oMail.Sender = oMail.ReplyTo = sFromEmail;
var sEmailList = sToEmail.split ( /[\s;,]/ );
var nEmail;
for ( nEmail in sEmailList )
oMail.AddRecipient ( sEmailList [ nEmail ] );
sEmailList = sBccEmail.split ( /[\s;,]/ );
for ( nEmail in sEmailList )
oMail.AddRecipientBcc ( sEmailList [ nEmail ] );
oMail.Subject = sSubject;
oMail.Body = sBody;
// send it
oMail.Execute ( );
Again, very straightfoward code. The main difference from CDONTS is how multiple recipients are handled. JMail requires that the semicolon-separated list is split into an array, then fed into the AddRecipient method one at a time.
Using ASPMail
To use ASPMail, set nEmailServer=nEmailASPMAIL in include/config.asp. The SendEmail function will then execute the following code...
// get a mail object
oMail = Server.CreateObject ( "SMTPsvg.Mailer" );
// setup the mail
if ( sFromEmail == "" )
oMail.ReplyTo = 'Anonymous';
else
oMail.ReplyTo = sFromEmail;
// =========================
// important - ASPMail only works if the
// FromAddress is the same domain as
// the RemoteHost domain
// =========================
oMail.FromAddress = 'james@' + sHostDomain;
oMail.RemoteHost = 'mail.' + sHostDomain;
var sEmailList = sToEmail.split ( /[\s;,]/ );
var nEmail;
for ( nEmail in sEmailList )
oMail.AddRecipient ( "", sEmailList [ nEmail ] );
sEmailList = sBccEmail.split ( /[\s;,]/ );
for ( nEmail in sEmailList )
oMail.AddBCC ( "", sEmailList [ nEmail ] );
oMail.Subject = sSubject;
oMail.BodyText = sBody;
// send it
oMail.SendMail ( );
Very similar to the JMail component, ASPMail also needs multiple recipients sent into an AddRecipient method individually.
Take note of the comment above concerning the FromAddress and RemoteHost properties. I wasted some time tracking down that problem! ASPMail is actually the email system used on CoverYourASP.
Using ASPEmail
To use ASPEmail, set
nEmailServer=nEmailASPEMAIL
in include/config.asp. The SendEmail function will then execute the following code...
// get a mail object
oMail = Server.CreateObject ( "Persits.MailSender" );
// setup the mail
if ( sFromEmail == "" )
oMail.From = 'Anonymous';
else
oMail.From = sFromEmail;
oMail.Host = 'mail.' + sHostDomain;
var sEmailList = sToEmail.split ( /[\s;,]/ );
var nEmail;
for ( nEmail in sEmailList )
oMail.AddAddress ( sEmailList [ nEmail ] );
sEmailList = sBccEmail.split ( /[\s;,]/ );
for ( nEmail in sEmailList )
oMail.AddBCC ( sEmailList [ nEmail ] );
oMail.Subject = sSubject;
oMail.Body = sBody;
// send it
oMail.Send ( );
As with all the third party components, I split the email address string into an array, and feed it into an Add method - for ASPEmail that's the AddAddress method.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |
More ASP Articles
More By James Shaw
developerWorks - FREE Tools! |
Set up a PHP Web interface for the Java(TM) business application using a database created in earlier in this series. The PHP Web interface collects information from users and sends the session data to the Java business application for processing and for a response. FREE! Go There Now!
|
|
|
|
Visit IBM developerWorks to download a free trial of the latest release of IBM Lotus Sametime Standard V8.0. Lotus Sametime Standard V8.0 is a platform for unified communications and collaboration that combines security features with an extensible, open solution including integrated Voice over IP, geographic location awareness, mobile clients, and a robust Business Partner community offering telephony and video integration. FREE! Go There Now!
|
|
|
|
As systems increase in complexity, communication between systems and software teams becomes more and more difficult. Now, there’s a way to improve product quality and communication.<br />Read the “Model Driven Systems Development” white paper to see how. Also included in this kit are more educational white papers, customer examples, tutorials, informative Webcasts, and best practices for designing, building and managing systems.<br /> FREE! Go There Now!
|
|
|
|
IBM DB2 9.5 provides new options for tighter security, and allows for more granularity and flexibility in administration of the database. This tutorial is the first of two tutorials that cover roles and trusted contexts. Follow the exercises in this tutorial, and learn how to take advantage of the new DB2 feature roles in combination with other essential e-business technologies such as Web services, Web application server, and DB2 database server. FREE! Go There Now!
|
|
|
|
Ken Krugler, co-founder of code search company Krugle, and Laura Merling, vice president of Marketing and Business Development for Krugle, join to talk about the ins and outs of code search and what it means as a new feature for developerWorks users. FREE! Go There Now!
|
|
|
|
Join this Rational Talks to You teleconference on December 11 at 1:00 pm ET to get tips on building your own plugins with Rational Method Composer. Get your questions answered! FREE! Go There Now!
|
|
|
|
Discover how Rational tools and best practices for testing can make your job easier. The new Rational Testing eKits provide you with valuable resources – including demos, webcasts, tutorials, and articles – that help you address your specific testing needs across the software lifecycle. Five new eKits are available covering the topics of Requirements and Test Management, Functional Testing, Performance Testing, Code Quality and Embedded Systems, and SOA and Web Services Testing. FREE! Go There Now!
|
|
|
|
Learn the basics of the IBM Customer Information Control System (CICS). With a hands-on exercise, learn how to get your first CICS application up and running on your desktop using TXSeries V6.1 for Windows. The tutorial shows you how to download and install a free trial version of TXSeries V6.1. FREE! Go There Now!
|
|
|
|
It's a good time to be a Web developer. You've never had more choices in terms of technologies. There are so many great open source Web servers, databases, programming languages, and development frameworks. No matter what combination of technologies you prefer to work with, there is an integrated development environment (IDE) that can increase your productivity: Eclipse. In this tutorial, Part 1 of a three-part "Web development with Eclipse Europa" series on how to use Eclipse for Web development with Java technology, PHP, and Ruby, we'll see how the latest release of Eclipse -- Europa -- can be used to rapidly develop Java Web applications. We'll use Java Platform, Enterprise Edition 5 (Java EE) for Eclipse to build a Web application for tracking and calculating baseball statistics. FREE! Go There Now!
|
|
|
|
No matter what combination of technologies you prefer to work with as a Web developer, Eclipse is a single integrated development environment (IDE) that can increase your productivity. In Part 2, we'll see how easy it is to develop PHP applications using a different set of Eclipse plug-ins, collectively known as the PHP Development Toolkit (PDT.) FREE! Go There Now!
|
|
|
|
All FREE IBM® developerWorks Tools! |