I.T. Discussion Community!
-Collapse +Expand
ASP Classic
Search ASP Classic Group:

Advanced
-Collapse +Expand ASP Classic Store

Prestwood eMagazine

November Edition
Subscribe now! It's Free!
Enter your email:

   ► KBWebsite Scri...ASP ClassicLanguage Basics   Print This     
  From the December 2015 Issue of Prestwood eMag
 
ASP Classic Language Basics:
Send email with ASPMail
 
Posted 16 years ago on 3/26/2003 and updated 12/13/2006
Take Away:

How to use ASPMail to send email from your web site.

 Tags: aspmail , asp , email , using , how to

KB100216

Need Help with ASPMail?

If you need help with ASPMail beyond the free support on this page, we can help. We've developed several web sites using ASPMail to send email. We've also used other techniques including CDONTS and ASP.NET.

About ASPMail

ASPMail allows you to send mail using the standard SMTP protocol from any program that can use ActiveX/OLE components, including ASP. Features include:

  1. SMTP (sending) Messages

  2. Multiple File Attachments

  3. File attachments support MIME and UUEncoding

  4. US Ascii and ISO-8859-1 character sets

  5. Subject line encoding for 8bit message subjects

  6. Redundant SMTP servers (If the primary SMTP server is down, the secondary server is used)

  7. Special Header Support (Standard X-Priority headers, MS Mail (including Exchange) priority headers, Urgent header, ConfirmReading and ReturnReceipt Headers)

How to use ASPMail

Using the component is as simple as

  1. Creating the object

  2. Setting a few properties

  3. Calling the SendMail method

Creating the Object

The first step to using ASPMail is to create the object. This can be done with the following code:

    <% Set Mailer = Server.CreateObject ("SMTPsvg.Mailer") %>

 

Setting the Properties

Typically you need to set five properties and call one method to define your message in ASPMail. The properties that you must set are:

FromName The name that should be used for the Sender of the message.

Example:
  Mailer.FromName = "Joe's Widgets Corp."

FromAddress The email address that should be used as the sender of the message.

Example:
  Mailer.FromAddress = "sales@joeswidgets.com"

Subject This will be used as the Subject of the message

Example:
  Mailer.Subject = "Your Widget Order"

BodyText This will be the actual message

Example:
  Mailer.BodyText = "Your order was processed."

RemoteHost The SMTP server to be used for sending the message. Typically this will be mail-fwd.rapidsite.net.

Example:
  Mailer.RemoteHost = "mail-fwd.rapidsite.net"

The method that you must call is:

AddRecipient name, email addr This method add a name and email address to the "To:" field of the message

Example:
  Mailer.AddRecipient "John Smith", "jsmith@someisp.com"

 

Calling the SendMail Method

The SendMail method takes no properties, but does return True / False to indicate Success or Failure in sending the email message.

Example 1:
    returnCode = Mailer.SendMail
    if returnCode = TRUE then
        ' Message sent sucessfully
    else
        ' Message send failure
    end if

The next example achieves the same result without using a variable for the return code.

Example 2:
    if Mailer.SendMail then
        ' Message sent sucessfully
    else
        ' Message send failure
    end if

 

Error Handling

Once we've called SendMail and have checked for a send failure we may want to know what the error condition was. ASPMail provides a Property called "Response" that contains a textual description of why the message was not sent. You could use this message to inform the user or write to a log file.

Example:
    if Mailer.SendMail then
        ' Message sent sucessfully
        response.write ("Your message was sent")     
    else
        ' Message send failure
        response.write ("Your message was not sent. ")
        response.write ("The error was: " & Mailer.Response)
    end if

 

Completed Example

<%
Set Mailer = Server.CreateObject ("SMTPsvg.Mailer")
Mailer.FromName = "Joe's Widgets Corp."
Mailer.FromAddress = "sales@joeswidgets.com"
Mailer.Subject = "Your Widget Order"
Mailer.BodyText = "Your order was processed."
Mailer.RemoteHost = "mail-fwd.rapidsite.net"

Mailer.AddRecipient "John Smith", "jsmith@someisp.com"

if Mailer.SendMail then
' Message sent sucessfully
response.write ("Your message was sent")
else
' Message send failure
response.write ("Your message was not sent. ")
response.write ("The error was: " & Mailer.Response)
end if
%>

ASPMail Troubleshooting

  • How do I determine the cause of a mail failure?

  • What would cause an "Operation timed out error"? or "ASPMail has been working great but suddenly I'm getting an 'Operation timed out' error.

  • I'm adding attachments but they aren't being added to the actual mailing. What's wrong?

  • "AddCC or AddBCC doesn't work" - is this a bug with 'ASPMail'? or "I adding multiple recipients but only the first one is getting delivered. What's wrong with ASPMail?"

  • How do I create a line-break in a message?

  • How do I set the username and password to send mail?

  • My mail to AOL is bouncing. What am I doing wrong?

  • Does ASPMail support 8bit messages? or "does ASPMail support Japanese character set"

  • Can I repeatedly assign values to the BodyText property? and "The message text keeps growing with each email I send."

  • Can ASPMail be used to retrieve files off the client computer?

  • The SMTP server is reporting back a "no relay" error. What's wrong?

  • Some of our emails are getting equal signs ("=") at the end of lines in some messages. Why?

How do I determine the cause of a mail failure?

Note about FromAddress: You must specify a value for the FromAddress property. Mail failure will occur without a FromAddress.

If the component can determine why the SendMail method failed, that information will be stored in the Response property. So, for example, to print that information to the clients browser you could add the following code:

if not Mailer.SendMail then
  if Mailer.Response <> ''" then
    strError = Mailer.Response
  else
    strError = "Unknown"
  end if
  Response.Write "Mail failure occured. Reason: " & strError
end if                   

Another fairly common problem is when a user reports that a specific feature is not working. For example BCC's may seem to never reach their destination. A valuable debugging tool is available with the SMTPLog feature. Assign a valid filename to this property and the contents of the SMTP transaction that occurs during a SendMail call will be recorded to this file. If you find that the SMTP transaction occurs without error then you should check elsewhere for the cause of mail delivery failure. Invariably the user finds that the BCC address was invalid or that the address was misconfigured. The SMTPLog feature allows you to verify if the transactions are complete and valid before pursuing other avenues in determining the cause of failure.

What would cause an "Operation timed out error"? or "ASPMail has been working great but suddenly I'm getting an 'Operation timed out' error.

Reasons for operation timed out include:

  1. SMTP server is down, overloaded or simply not responding

  2. Firewall blocking port 25 between ASPMail and SMTP server

  3. Packet filtering blocking port 25 between ASPMail and SMTP server

  4. IP route is down

  5. Your Winsock configured DNS server is down

I'm adding attachments but they aren't being added to the actual mailing. What's wrong?

  1. The path specified is not valid.

  2. The user the component is running under, typically the anonymous IIS user, does not have rights to open the file. The anon IIS user, by default, cannot read from networked drives so a path such as \\foobar\files\myfile.zip is not valid.

  3. The file is open by another process that's denying reads to the file.

"AddCC or AddBCC doesn't work" - is this a bug with 'ASPMail'? or "I adding multiple recipients but only the first one is getting delivered. What's wrong with ASPMail?"

AddRecipient, AddCC and AddBCC work just as they should. The problem is not with ASPMail. It is likely that your SMTP server is rejecting "foreign addresses" (see "no relay" question below).

To test whether ASPMail is functioning properly use the SMTPLog property to capture an SMTP session with multiple recipients. All the recipients you send to should appear in the log as the SMTP envelope is sent. If they all appear then the problem is with your SMTP server or an SMTP server down the stream (or your addresses are invalid).

How do I create a line-break in a message?

Under VBScript you can use the predefined constant VbCrLf. Simply using a Chr(13) or a Chr(10) will not work --you must use both -- the VBCrLf defined constant is the preferred method. A Carriage-return and line-feed character are required to create a new line in the message. See the sample scripts for examples.

How do I set the username and password to send mail?

Standard SMTP does not use a uid/pwd so it isn't needed. The protocol used to retrieve mail, POP3 typically requires a uid/pwd but ASPMail doesn't use POP3 since it is a send mail component.

My mail to AOL is bouncing. What am I doing wrong?

AOL will not accept anything other than a true address in the "From:" heading. Just about every mail system out there, except AOL and Compuserve, will accept the "No Mail Address" as the "From:" header. (thanks to R.S for this info).

Does ASPMail support 8bit messages? or "does ASPMail support Japanese character set"

ASPMail supports any 8 bit characters but please note:

  1. Message bodies may be 8bit.

  2. Some SMTP servers drop the 8th bit in message headers including Subject lines.

  3. You can encode message subjects using a new method named EncodeHeader. See ASP methods below for details. Some character sets don't work properly using this method, some do. We don't have any support for character sets that don't work properly using this encoding.

Can I repeatedly assign values to the BodyText property? and "The message text keeps growing with each email I send."

Yes, the text will be appended to the message. Use ClearBodyText if you need to clear the message text.

Can ASPMail be used to retrieve files off the client computer?

ASPMail is a server-side component. Retrieving files from the client computer requires a client-side component that has access to the client's local harddisk or a browser that supports file uploads in addition to a server side component/extension that can accept those files. ASPMail does not support this function.

The SMTP server is reporting back a "no relay" error. What's wrong?

The SMTP server is looking at your FromAddress and determining that it doesn't know who you are. Some SMTP servers are configured to disallow the "relaying" or transfer of mail originating from addresses outside of its own domain. The only solution is to provide a FromAddress that's local to the SMTP server's domain or get the operator of the SMTP server to allow the FromAddress you are using. This setting is commonly used by ISP's to prevent spammers from using their resources.

Some of our emails are getting equal signs at the end of lines in some messages. Why?

ASPMail can encode high characters using a scheme where the = sign
indicates a character to be decoded follow by the hex string value of
the character to be encoded. This system of course assumes that the client can decode these characters (which most can). This is called quoted-printable encoding. The default for ASPMail is not to use QP encoding. Things that trigger automatic QP encoding:

  1. High characters - characters with the following ordinal values 0..31,61,128..255

  2. Long lines of a message body (you can turn wordwrap on to fix this case)

Most clients are capable of handling QP encoding. If your client is not capable then you should upgrade your client or you must work within the above limitations to prevent the QP encoding from occuring.

Forms to Email Example

This is a basic example of an ASP script that will send the results of any form that uses the POST method to an email address.

NOTE: ASP controls the order in which form items are passed to the script. To keep the form items in a logical order would require extra processing and would limit the types of forms that could be used.

<%
set mailer = server.createobject("SMTPsvg.Mailer")

Mailer.FromName = "From Email Name"
Mailer.FromAddress = "fromaddress@mysite"
Mailer.RemoteHost = "mail.rapidsite.net"
Mailer.AddRecipient "Your Name Here", "Your Email Address Here"
Mailer.Subject = "Forms2Email"

For each Item in Request.Form ' Loop through each Form item
strMsgInfo = strMsgInfo & Item & ": " & Request.Form(Item) & vbCrLf
next

strMsgHeader = "Form information follows" & vbCrLf & "*************"
strMsgFooter = vbCrLf & "*************"
Mailer.BodyText = strMsgHeader & strMsgInfo & strMsgFooter

if Mailer.SendMail then
' Message sent Ok, redirect to a confirmation page
Response.Redirect ("http://mysite/confirm.htm")
else
' Message send failure
Response.Write ("An error has occurred.
")
' Send error message
Response.Write ("The error was " & Mailer.Response)
end if
%>

Converting MPS.SendMail to ASPMail

The function that follows will allow you to quickly replace MPS.SendMail in all of your ASP scripts.

To use the function, first place it at the begining of any scripts that currently use MPS.Sendmail. Once you've done that, remove any lines reading 'Set something = Sever.CreateObject ("MPS.SendMail")', then replace all occurances 'something.SendMail' with 'sendMessage'.

For example, this:
     something = Server.CreateObject("MPS.SendMail")
     errorCode = something.SendMail ("From", "To", "Subject", "Body")

would become this:
     errorCode = sendMessage ("From", "To", "Subject", "Body")

<%
Function sendMessage (mailFrom, mailTo, mailSubject, mailBody)
' sendMessage takes the same parameters as MPS.SendMail
' response = sendMessage (From, To, Subject, Body)
Set mailer = Server.CreateObject ("SMTPsvg.Mailer")

mailer.FromAddress = mailFrom
mailer.AddRecipient "", mailTo
mailer.Subject = mailSubject
mailer.BodyText = mailBody

mailer.RemoteHost = "mail.rapidsite.net"

If mailer.Sendmail then ' Send message
sendMessage = True ' Email was sent ok, return True
else ' Send Failure
sendMessage = mailer.Response ' Return error message
end if

end function
%>

ASPMail Methods

A guide to all of the methods that ASPMail provides on our NT Servers.

SendMail

AddCC

AddRecipient

ClearCCs

ClearRecipients

AddBCC

ClearAllRecipients

ClearBCCs

AddAttachment

GetBodyTextFromFile

ClearAttachments

ClearBodyText

AddExtraHeader

EncodeHeader

ClearExtraHeaders

GetTempPath

SendMail

The SendMail method attempts to send the email. SendMail takes no parameters, you build the message using the FromAddress, Subject, BodyText, and RemoteHost properties along with the AddRecipient method.

Returns: True / False

Example:
     if Mailer.SendMail then
          ' Message sent Successfully
     else
          Response.Write ("Mail Failure: " & Mailer.Response)
     end if

AddRecipient (name, address)

Adds a new recipient, as shown in the message's To list. 'Name' may be left blank.

Returns: True / False

Example:
     returnValue = Mailer.AddRecipient("Jay Jones", "jayj@somehost.net")
     if returnValue then
          ' jay jones added successfully
     end if

ClearRecipients

Clears any recipients assigned to the To list.

Returns: Nothing

AddCC (name, address)

Adds a new recipient, as shown in the message's CC list. The 'name' parameter may be left blank.

Returns: True / False

Example:
     returnValue = Mailer.AddCC ("", "jayj@somehost.net")
     if returnValue then
          ' jayj added successfully
     end if

ClearCCs

Clears any recipients assigned to the CC list.

Returns: Nothing

AddBCC (name, address)

Adds a new Blind Carbon Copy recipient. BCC recipients are not shown in any message recipient list.

Returns: True / False

Example:
     returnValue = Mailer.AddBCC ("Jay Jones", "jayj@somehost.net")
     if returnValue then
          ' Jay Jones added to BCC list
     end if

ClearBCCs

Clears any recipients assigned to the BCC list.

Returns: Nothing

ClearAllRecipients

Clears all recipients assigned to the To, CC and BCC lists.

Returns: Nothing

AddAttachment (filePath)

Adds attachments to current mailing. You must use a fully qualified path to attach files.

Returns: Nothing

Examples:
     Mailer.AddAttachment ("D:\webs\mysite\downloads\myfile.zip")
     Mailer.AddAttachment (Server.Mappath("/downloads/myFile.zip"))

ClearAttachments

Clears any attachments that were previously set.

Returns: Nothing

ClearBodyText

Clears any text assigned to the message’s body which may have been set previously by using the BodyText property.

Returns: Nothing

AddExtraHeader (header)

Adds extra X-Headers to the mail envelope. 'Header' is a string value that forms a proper SMTP X-Header.

Returns: True / False

Example:
     returnValue = Mailer.AddExtraHeader("X-HeaderName: XHdrValue")

ClearExtraHeaders

Clears any X-Headers that were set by use of AddExtraHeader.

GetBodyTextFromFile (filePath)

Loads message's body text from a file. filePath must be a fully qualified path.

Examples:
     Mailer.GetBodyTextFromFile ("d:\webs\mysite\data\msgbody.txt")
     Mailer.GetBodyTextFromFile (Server.MapPath("/data/msgbody.txt")

EncodeHeader (strValue)

Encodes a string in RFC1522 format to provide support for 8bit mail headers such as 8bit subject headers. 'strValue' is the string to encode.

Returns: Encoded string

Example:
     Mailer.Subject = Mailer.EncodeHeader("Résponse de Service   la clientèle")

GetTempPath

Returns the path set up by the OS for temporary mail files.

Returns: Path string

Example:
     tempPath = Mailer.GetTempPath

ASPMail Properties

A guide to all of the properties that ASPMail provides on our NT Servers.

BodyText

ReplyTo

CharSet

Response

ConfirmRead

ReturnReceipt

ContentType

SMTPLog

CustomCharSet

Subject

DateTime

SuppressMsgBody

Encoding

TimeOut

FromName

Urgent

FromAddress

UseMSMailHeaders

Organization

Version

Priority

WordWrap

RemoteHost

WordWrapLen

BodyText

The message body text. To clear the text once you have set it use the ClearBodyText Method.

Example:

Mailer.BodyText = "Your order for 15 widgets has been processed"

CharSet

The character set. By default the char set is US Ascii

Valid values:

  • 1 = US Ascii

  • 2 = ISO-8859-1

Example:

Mailer.CharSet = 2

ConfirmRead

The ConfirmReading flag. If this is set to true AND the recipients email program supports

this feature (and it is enabled) the recipients email program will send a notice back to the FromAddress confirming that this email has been read.

Example:

Mailer.ConfirmRead = true

ContentType

The ContentType property allows you to set the ContentType header of the message's BodyText. If, for example, you wanted to send HTML as the messages's body, you could set ContentType = "text/html" and EMail programs that support HTML content could properly display the HTML text.

Note: The ContentType property is ignored if you have file attachments.

Example:

Mailer.ContentType = "text/html"

CustomCharSet

If you wish to use a character set besides the included types you can set CustomCharSet to a character set string.

Example:

Mailer.CustomCharSet = "ISO-2022" or
Mailer.CustomCharSet = "big5"

DateTime

AspMail will, by default, create a Date/Time header for your local system using GMT. If you would like to override the date/time calculation set the DateTime property to a valid date/time string in the format defined by RFC 822 & RFC 1123. Example:

Mailer.DateTime = "Fri, 02 May 1997 10:53:49 -0500"

Encoding

The encoding type for attachments. The default setting is MIME.

Valid values:

  • 1 = UUEncoded

  • 2 = MIME

Example:

Mailer.Encoding = 1

FromName

The message originator’s name.

Example:

Mailer.FromName = "Joe’s Widget Shop"

FromAddress

Tthe message originator’s email address.

Example:

Mailer.FromAddress = joe@widgets.com

Organization

Sets the Organization header in the message.

Example:

Mailer.Organization = "Your Company Name"

Priority

Sets the message priority. Priorities are 1-5 and are reflected in the X-Priority

Valid values:

  • 1 – High

  • 3 – Normal

  • 5 – Low

Example:

Mailer.Priority = 1

RemoteHost

The remote SMTP host that the message will be sent through. This is typically an SMTP server located at your local ISP or it could be an internal SMTP server on your companies premises. Up to 3 server addresses can be specified, seperated by a semicolon. If the primary server is down the component will attempt to send the mail using the seconary server and so on.

Example:

Mailer.RemoteHost = "mailhost.myisp.net"
    or
Mailer.RemoteHost = "mailhost.myisp.net; mailhost.myotherisp.net"

ReplyTo

The ReplyTo property allows you to specify a different email address that replies should be sent to. By default mail programs should use the Reply-To: header for responses if this header is specified.

Response

The Response property returns any error messages that may occur.

ReturnReceipt

The ReturnReceipt flag. If this is set to true AND the recipients SMTP server supports this feature (and it is enabled) the recipients SMTP server will send a notice back to the FromAddress confirming that this email has been delivered.

Example:

Mailer.ReturnReceipt = false

SMTPLog

If you need to debug the session give a log file name here. Make sure the IUSR_XYZ IIS user has security that allows the component to write to this file. Warning: Do not use this setting in situations where multiple users can access this component at the same time. This is for single user debugging ONLY!

Example:

Mailer.SMTPLog = "c:\smtplog.txt"

Subject

The message subject.

Example:

Mailer.Subject = "Stock split announced!"

SuppressMsgBody

The SuppressMsgBody property is true by default and is used in conjuction with the SMTPLog property. When SMTPLog is set to a file and SuppressMsgBody is true the log file receives a copy of the message text. If SuppressMsgBody is false the message text is not sent to the log.

TimeOut

Timeout is the maximum time that AspMail should wait for a response from the remote server. The default is 30 seconds.

Example:

Mailer.Timeout = 15

Urgent

The urgent flag sets the X-Urgent header in the outgoing message. Not all mail readers support this flag.

Example:

Mailer.Urgent = true

UseMSMailHeaders

MS-Mail priority headers, by default, are sent in addition to the standard SMTP priority headers. You can turn MS-Mail headers off with this property

Example:

Mailer.UseMSMailHeaders = false

Version

Gets the internal component version number.

Example:

Response.Write "Component Version: " & Mailer.Version

WordWrap

The WordWrap property is off by default. Setting WordWrap to true causes the message body to wordwrap at the position specified by the WordWrapLen property.

WordWrapLen

The WordWrapLen property is set to 70 by default. You can modify the position that wordwrap occurs by changing this value.


Comments

1 Comments.
Share a thought or comment...
Comment 1 of 1

Do you know where ASPMail stores its registration key? We've misplaced ours and want to move it to a new server.

---
Craig
Posted 55 months ago
 
Write a Comment...
...
Sign in...

If you are a member, Sign In. Or, you can Create a Free account now.


Anonymous Post (text-only, no HTML):

Enter your name and security key.

Your Name:
Security key = P1215A1
Enter key:
KB Post Contributed By Mike Prestwood:

Mike Prestwood is a drummer, an author, and creator of the PrestwoodBoards online community. He is the President & CEO of Prestwood IT Solutions. Prestwood IT provides Coding, Website, and Computer Tech services. Mike has authored 6 computer books and over 1,200 articles. As a drummer, he maintains play-drums.com and has authored 3 drum books. If you have a project you wish to discuss with Mike, you can send him a private message through his PrestwoodBoards home page or call him 9AM to 4PM PST at 916-726-5675 x205.

Visit Profile

 KB Article #100216 Counter
157571
Since 4/2/2008

Follow PrestwoodBoards on: 


©1995-2019 PrestwoodBoards  [Security & Privacy]
Professional IT Services: Coding | Websites | Computer Tech