AspEmail Manual Chapter 2: Getting Started

Contents

2.1 Creating an Instance of the AspEmail Object

ASP

To use AspEmail in an ASP environment, you must create an instance of the AspEmail object in your ASP script as follows:

<%
...
Set Mail = Server.CreateObject("Persits.MailSender")
...
%>

VB

To use AspEmail in a VB environment, open your VB project, go to Project/References... and check the box next to Persits Software AspEmail 5.0. Declare an AspEmail object variable as follows:

Dim Mail As MailSender

Create an instance of the AspEmail object as follows:

Set Mail = New MailSender

ASP.NET

AspEmail comes with an ASP.NET wrapper assembly, ASPEMAILLib.dll, which has to be placed in the \Bin subdirectory of your ASP.NET application. Alternatively, you can place this file in the Global Assembly Cache.

In C#, create an instance of AspEmail as follows:

<%@ Import Namespace="ASPEMAILLib" %>
<script runat="server" LANGUAGE="C#">
void Page_Load(Object Source, EventArgs E)
{
  ...
  ASPEMAILLib.IMailSender objMail;
  objMail = new ASPEMAILLib.MailSender();
  ...
}
</script>

2.2 Essential Properties and Methods

In order to send email, AspEmail "talks" to an SMTP server. The SMTP server does not have to be running on the same machine as AspEmail, in fact it can be located anywhere on the local network or the Internet.

You must specify the address of your SMTP server via the Host property. The default port number for SMTP services is 25, but if your SMTP server runs on a different port, you must also specify it via the Port property:

Mail.Host = "smtp.mycompany.com" ' Required
Mail.Port = 25 ' Optional. Port is 25 by default

You may also specify a comma- or semicolon-separated list of SMTP hosts, as follows:

Mail.Host = "smtp.domain1.com;smtp2.domain1.com;host.domain2.com"

If the first host on the list is down, AspEmail will automatically attempt to connect to the second host, etc. If none of the specified hosts are working, an error exception will be thrown.

You must also specify the sender's email address and, optionally, name as follows:

Mail.From = "sales@mycompany.com"' Required
Mail.FromName = "Sales Department" ' Optional

To add message recipients, CCs, BCCs, and Reply-To's, use the AddAddress, AddCC, AddBcc and AddReplyTo methods, respectively. These methods accept two parameters: the email address and, optionally, name. Notice that you must not use an '=' sign to pass values to the methods. For example,

Mail.AddAddress "jsmith@company1.com", "John Smith"
Mail.AddCC "bjohnson@company2.com" ' Name is optional

Use the Subject and Body properties to specify the message subject and body text, respectively. A body can be in a text or HTML format. In the latter case, you must also set the IsHTML property to True. For example,

' text format
Mail.Subject = "Sales Receipt"
Mail.Body = "Dear John:" & chr(13) & chr(10) & "Thank you for your business. Here is your receipt."

or

' HTML format
Mail.Subject = "Sales Receipt"
Mail.Body = "<HTML><BODY BGCOLOR=#0000FF>Dear John:....</BODY></HTML>"
Mail.IsHTML = True

To send a file attachment with a message, use the AddAttachment method. It accepts the full path to a file being attached. Call this method as many times as you have attachments. Notice that you must not use the '=' sign to pass a value to the method:

Mail.AddAttachment "c:\dir\receipt.doc"

To send a message, call the Send method. The method throws exceptions in case of an error. You may choose to handle them by using the On Error Resume Next statement, as follows:

On Error Resume Next
Mail.Send
If Err <> 0 Then
  Response.Write "An error occurred: " & Err.Description
End If

2.3 Code Samples

The following code sample demonstrates a simple email-sending form.

<%
' change to address of your own SMTP server
strHost = "mail.elinkisp.com"

If Request("Send") <> "" Then
   Set Mail = Server.CreateObject("Persits.MailSender")
   ' enter valid SMTP host
   Mail.Host = strHost

   Mail.From = Request("From") ' From address
   Mail.FromName = Request("FromName") ' optional
   Mail.AddAddress Request("To")

   ' message subject
   Mail.Subject = Request("Subject")
   ' message body
   Mail.Body = Request("Body")
   strErr = ""
   bSuccess = False
   On Error Resume Next ' catch errors
   Mail.Send ' send message
   If Err <> 0 Then ' error occurred
      strErr = Err.Description
   else
      bSuccess = True
   End If
End If
%>

<HTML>
<BODY BGCOLOR="#FFFFFF">
<% If strErr <> "" Then %>
<h3>Error occurred: <% = strErr %>
<% End If %>
<% If bSuccess Then %>
Success! Message sent to <% = Request("To") %>.
<% End If %>
<FORM METHOD="POST" ACTION="Simple.asp">
<TABLE CELLSPACING=0 CELLPADDING=2 BGCOLOR="#E0E0E0">
<TR>
   <TD>Host (change as necessary in script):</TD>
   <TD><B><% = strHost %></B></TD>
</TR>
<TR>
   <TD>From (enter sender's address):</TD>
   <TD><INPUT TYPE="TEXT" NAME="From"></TD>
</TR>
<TR>
   <TD>FromName (optional, enter sender's name):</TD>
   <TD><INPUT TYPE="TEXT" NAME="FromName"></TD>
</TR>
<TR>
   <TD>To: (enter one recipient's address):</TD>
   <TD><INPUT TYPE="TEXT" NAME="To"></TD>
</TR>
<TR>
   <TD>Subject:</TD>
   <TD><INPUT TYPE="TEXT" NAME="Subject"></TD>
</TR>
<TR>
   <TD>Body:</TD>
   <TD><TEXTAREA NAME="Body"></TEXTAREA></TD>
</TR>
<TR>
   <TD COLSPAN=2><INPUT TYPE="SUBMIT" NAME="Send" VALUE="Send Message">
</TD>
</TR>
</TABLE>
</FORM>
</BODY>
</HTML>

Click the links below to run this code sample (ASP and ASP.NET versions, respectively):

The following code sample sends email in the HTML format. The script is essentially the same except that the message body is set to an HTML string, and the property IsHTML is set to True:

strHTML = message body in HTML format
...
Mail.IsHTML = True
Mail.Body = "<HTML><BODY><CENTER>" & strHTML & "</CENTER></BODY></HTML>"
...

Click the links below to run this code sample.

2.4 Email Address Validation

AspEmail is capable of validating the syntax of an email address. As of Version 5.2, it is also able to determine, with a high degree of certainty, whether a particular email address actually exists.

The method ValidateAddress takes an email address as an argument and returns 0 if the address is syntactically valid. A number greater than 0 means a syntax error. All possible return values are as follows:

Value
Meaning
0
Valid
1
Too short
2
Too long (greater than 256 chars)
3
No @
4
Nothing before @
5
Characters before @ must be a-z A-Z 0-9 ' _ . - +
6
No dots after @
7
Zero-length subdomain
8
Characters in a subdomain must be a-z A-Z 0-9 -
9
Characters in a top-level subdomain must be a-z A-Z 0-9
10
Top-level subdomain must be at least 2 characters long
11
Name part of address cannot start or end with a dot
12
A subdomain cannot start or end with a dash (-)

For example:

If Mail.ValidateAddress( Email ) <> 0 Then
   Response.Write "Invalid email address."
End If

The ValidateAddress method makes no determination whether the email address being validated actually exists. As of Version 5.2, AspEmail offers another method, ValidateAddressMX, which internally calls ValidateAddress to determine its syntactic correctness, performs a DNS lookup of the MX records for the address's domain, and then contacts the corresponding SMTP server to determine if it recognizes the address as valid.

ValidateAddressMX expects two arguments: the email address being validated and, optionally, the IP address of the DNS server for the MX record lookup. If the 2nd argument is omitted, the method obtains the addresses of the local DNS servers from the system registry. ValidateAddressMX returns an empty string if the email address is successfully validated, or an error message if the validation fails.

To validate an address against its corresponding SMTP server, ValidateAddressMX sends three SMTP commands: HELO, MAIL FROM and RCPT TO. The value used for the HELO command is the Helo property, for the MAIL FROM command the MailFrom property, and for the RCPT TO command the address being validated. If MailFrom is not specified, the address being validated is used for the MAIL FROM command as well. It is recommended that you specify your domain name for the Helo property, and your valid email address for the MailFrom property before calling ValidateAddressMX, as follows:

Mail.Helo = "mydomain.com"
Mail.MailFrom = "myself@mydomain.com"
Res = Mail.ValidateAddressMX( "someone@somedomain.com" )
If Res = "" Then
   Response.Write "OK"
Else
   Response.Write "Not OK: " & Res
End If

Note that the validation procedure performed by the ValidateAddressMX method is not 100% accurate. An error returned by the method does not always mean the address is invalid, and a lack of error is not always an indication the address exists.

2.5 Extended Multipart/Alternative Support

2.5.1 Body and AltBody

Multipurpose Internet Mail Extensions (MIME), the format in which most email messages are transmitted, allows a message body to be specified in several alternative versions at the same time. This feature, referred to as multipart/alternative, was originally designed to allow a message body to be specified in both HTML and plain-text forms to accommodate text-only email viewers.

Each sub-section within a multipart/alternative section of the message is preceded with a Content-Type header specifying this sub-section's format, such as Content-Type: "text/plain" for the plain-text version of the message body, and Content-Type: "text/html" for the HTML version.

Since its early days, AspEmail has supported the dual plain-text/HTML message bodies via the properties Mail.Body and Mail.AltBody. The HTML version of the body is to be specified via the former, and plain-text version via the latter, as follows:

Mail.Body = "<html><b>Hello</b> <i>World</i>!</html>" ' HTML version
Mail.AltBody = "Hello World!" ' Plain-text version

If the content of the message body were to be loaded from a disk file, the method AppendBodyFromFile can be used. This method's 2nd optional argument specifies whether it is Mail.Body that the content of the file is to be appended to (if set to True or omitted) or Mail.AltBody (if set to False). For example:

Mail.AppendBodyFromFile "c:\path\body.html", True ' Append Mail.Body
Mail.AppendBodyFromFile "c:\path\body.txt", False ' Append Mail.AltBody

2.5.2 AddAltBody Method

As of Version 5.6, AspEmail's support for multipart/alternative is no longer limited to just two content types (text/plain and text/html). Via the new method AddAltBody, any number of multipart/alternative subsections with arbitrary content types can be added to the email message. With the help of this method, messages generated by AspEmail can host various advanced content, such as accelerated mobile pages (AMP), calendars, etc. The method expects two string arguments: the content for the multipart/alternative subsection, and its content-type.

The following snippet generates a basic AMP message for which the content-type is "text/x-amp-html":

str = "<!doctype html>"
str = str & "<html amp4email>"
str = str & "<head>"
str = str & "<meta charset=""utf-8"">"
str = str & "<script async src=""https://cdn.ampproject.org/v0.js""></script>"
str = str & "<style amp4email-boilerplate>body{visibility:hidden}</style>"
str = str & "</head>"
str = str & "<body>"
str = str & "Hello, AMP4EMAIL world."
str = str & "</body>"
str = str & "</html>"

Mail.AddAltBody str, "text/x-amp-html"
...

The AddAltBody method can be used to specify the HTML and plain-text versions of the message body in lieu of Body and AltBody properties. The content-type value must be set to "text/html" and "text/plain", respectively:

' Same as Mail.Body = htmlText
Mail.AddAltBody htmlText, "text/html"

' Same as Mail.AltBody = plainText
Mail.AddAltBody plainText, "text/plain"

The text specified via AddAltBody can be retrieved via the method GetAltBody which expects the content-type as an argument, as follows:

text = Mail.GetAltBody("text/x-amp-html")

A call to the method ResetAll clears the list of alternative bodies along with all other lists and properties.

2.5.3 Sending Calendar Invitations

As of Version 5.6, the above described method AppendBodyFromFile has been retrofitted to be used with any alternative body and not just plain-text and HTML ones. In addition to True and False, the 2nd optional argument can now be set to a content-type string. The following code snippet creates a calendar invitation by appending a .ics file to the "text/calendar" alternative body:

Mail.AppendBodyFromFile( "c:\path\invite.ics", "text/calendar")