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! |
<a href="http://zeus.developershed.com/shonuff.php?blackbird=3853&zoneid=442&source=&dest=http%3A%2F%2Fwww.ibm.com%2Fdeveloperworks%2Fspaces%2Fjazz%3FS_TACT%3D105AGY31%26S_CMP%3DDEVSHED&ismap="><img src="http://images.devshed.com/corp/img/news/jazz01.gif" alt="developerWorks Jazz space" align="left"></a>You've heard the buzz about Jazz... want to know more about it from a developer's perspective? Check out the Jazz space on developerWorks. This space is an up-to-date resource for developers, including technical information about Jazz and products built on Jazz, like Rational Team Concert Express. The Jazz space includes content from a wide variety of sources, including links, feeds, and comments from experts. FREE! Go There Now!
|
|
|
|
You'll get answers to many questions and more from David Barnes, Lead Evangelist for IBM Emerging Internet Technologies. David will discuss aspects of Web 2.0 that bring value to corporations, academia, and government. He'll also discuss IBM's vision around Web 2.0, including the importance of remixability and consumability. The discussion will culminate with examples of various IBM Software Group solutions you can use to get ahead of the Web 2.0 adoption curve. FREE! Go There Now!
|
|
|
|
Poor Requirements Management capabilities in an Enterprise have been linked to excessive project failures, escalating IT costs, and failure to deliver competitive advantage into the marketplace. Join Brianna M Smith from IBM Rational and learn about how successful organizations align IT and Business stakeholders through collaborative processes and tools for effective requirements management, and how an integrated approach across the IT lifecycle can provide unparalleled visibility and traceability to ensure that project teams are delivering on the business vision by "doing the right things" and "doing things right." FREE! Go There Now!
|
|
|
|
Learn to enable users to both rate existing animations and to combine existing animations into new snippets. This is the third in a series of three tutorials that chronicle the building of a site that enables collaborative discussion and animation building using Domino and OpenLaszlo. FREE! Go There Now!
|
|
|
|
Visit IBM developerWorks to download the latest trial version of IBM Data Studio V1.1 at no cost. IBM Data Studio is a comprehensive data management solution that helps you effectively design, develop, deploy and manage your data, databases, and database applications throughout the data management life cycle utilizing a consistent and integrated user interface. Unlike other client-side data management solutions that focus on only one aspect of the application lifecycle or database administration, Data Studio complements the Rational Software Delivery platform, providing unparalleled flexibility for a heterogeneous data server environment across platforms. FREE! Go There Now!
|
|
|
|
Discover how IBM Rational AppScan Standard Edition can help you detext vulnerabilities in your web applications in the Web Application Security eKit. IBM Rational AppScan is a leading suite of automated web application security solutions that scan and test for common Web application vulnerabilities. The new Web Application Security eKit provides you with valuable resources, including white papers, demos, and additional information on the benefits of testing your Web applications. FREE! Go There Now!
|
|
|
|
Visit IBM developerWorks to download a free trial version of WebSphere Extended Deployment Compute Grid, which lets you schedule, execute, and monitor batch jobs. Because online transaction processing and batch jobs execute simultaneously on the same server resources, you can avoid costly duplication of resources. Compute Grid supports job types of Java transactional batch, compute-intensive and a new type called "native execution", which enables non-Java workloads to run on distributed end points. FREE! Go There Now!
|
|
|
|
Listen to this webcast to get an overview of Info 2.0 and a technical demo of how to quickly build an enterprise mashup. IBM's Info 2.0 technology leverages emerging Web 2.0 technologies such as mashups, feeds, AJAX, and JSON in order to simplify assembly of information using feeds and services. Come learn about the technical elements of Info 2.0 including the Feed Generation framework, Mashup Engine, and mashup assembly components. Learn how to pull information from databases, departmental information, and the Web to create mashups critical to your company’s success. We will also discuss best practices to help you get started. FREE! Go There Now!
|
|
|
|
This webcast outlines the best practices that must be instituted to gain the maximum benefit from SOA while maintaining high quality of service. Whether you are deploying new applications or managing and monitoring your existing infrastructure, learn how you can ensure high quality of services with SOA based solutions from IBM. All registrants who attend this live Web Seminar will receive complimentary access to a white paper titled “Maintaining QoS in an SOA Environment”. FREE! Go There Now!
|
|
|
|
Viper 2 brings a great value to developer communities including SQL, XML, PHP, Ruby, .NET and Java. You probably already know that DB2 Express-C is free for developers to develop, deploy and distribute. Viper 2 provides a variety of means that help move your application from the development stage to deployment more rapidly. This webcast shows how to best utilize the latest tools available for developing DB2 applications. FREE! Go There Now!
|
|
|
|
All FREE IBM® developerWorks Tools! |