aspmail user manual

29
The following chapters guide you step-by-step through all the features AspEmail has to offer. 1. Introduction Covers general AspEmail features, system requirements, and the installation procedure. 2. Getting Started Covers sending simple text and HTML email. 3. Attachments Covers sending email with file attachments. Also covers AspUpload usage in conjunction with AspEmail. 4. Embedded Images Covers sending email with embedded images. 5. Authentication & Security Covers SMTP authentication, as well as S/MIME encryption and digital signing of messages. 6. Unicode & Non-ASCII Support Covers AspEmail's foreign alphabet support. 7. Message Queuing, Part I Covers message queuing and deferred processing functionality. 8. Message Queuing, Part II Covers logging and bounced-message handling. Chapter 1. Introduction 1.1 What is AspEmail? AspEmail is an active server component for sending e-mail messages using an external SMTP server in an ASP or VB environment. AspEmail supports multiple recipients, multiple file attachments, HTML format, embedded images and sounds, non-US ASCII character sets, secure mail, and high-performance message queuing. AspEmail's basic functionality, including file attachment and HTML support, is absolutely free. Premium features require a registration key after a 30-day evaluation period. A copy of AspEmail can be downloaded from www.aspemail.com/download.html . 1.2 What's New in AspEmail 5.1 AspEmail 5.1 supports the Transport Layer Security (TLS) protocol. Now it can be used with any SMTP server requiring TLS, such as Google's smtp.gmail.com server. TLS encrypts all traffic between the email sender and SMTP server, including the SMTP login information, message headers, body and attachments.

Upload: marcelo

Post on 01-Nov-2014

184 views

Category:

Documents


5 download

DESCRIPTION

ASPMail User Manual

TRANSCRIPT

Page 1: ASPMail User Manual

The following chapters guide you step-by-step through all the features AspEmail has to offer.

1. Introduction Covers general AspEmail features, system requirements, and the installation procedure.

2. Getting Started Covers sending simple text and HTML email.

3. Attachments Covers sending email with file attachments. Also covers AspUpload usage in conjunction with AspEmail.

4. Embedded Images Covers sending email with embedded images.

5. Authentication & Security Covers SMTP authentication, as well as S/MIME encryption and digital signing of messages.

6. Unicode & Non-ASCII Support Covers AspEmail's foreign alphabet support.

7. Message Queuing, Part I Covers message queuing and deferred processing functionality.

8. Message Queuing, Part II Covers logging and bounced-message handling.

Chapter 1. Introduction

1.1 What is AspEmail?

AspEmail is an active server component for sending e-mail messages using an external SMTP server in an ASP or VB environment. AspEmail supports multiple recipients, multiple file attachments, HTML format, embedded images and sounds, non-US ASCII character sets, secure mail, and high-performance message queuing.

AspEmail's basic functionality, including file attachment and HTML support, is absolutely free. Premium features require a registration key after a 30-day evaluation period.

A copy of AspEmail can be downloaded from www.aspemail.com/download.html.

1.2 What's New in AspEmail 5.1

AspEmail 5.1 supports the Transport Layer Security (TLS) protocol. Now it can be used with any SMTP server requiring TLS, such as Google's smtp.gmail.com server.

TLS encrypts all traffic between the email sender and SMTP server, including the SMTP login information, message headers, body and attachments.

To make AspEmail communicate with the SMTP server via TLS, simply set the TLS property to True:

Mail.TLS = True

1.3 AspEmail Feature Summary

Sends e-mail using an external SMTP server programmatically. Supports multiple recipients, CC's, BCC's, Reply-To's, file attachments. Supports HTML format. Embedded images and sounds (multipart/related). Sends messages in both HTML and text formats (multipart/alternative). Secure mail in the S/MIME format, when used in tandem with AspEncrypt. Various SMTP authentication methods.

Page 2: ASPMail User Manual

Transport Layer Security (TLS) support.   NEW! High-volume message queuing support. Deferred message delivery. NNTP support. Memory attachments. Up to 64 simultaneous SMTP sessions when sending out queued mail. Multiple attempts to resend a failed message. Bounced message handling. Full Unicode support in message body and headers. Advanced logging.

1.4 System Requirements

Windows 2000, 2003, XP, 2008, Vista, 7. IIS with ASP or ASP.NET (any version) or Any other development environment supporting COM.

1.5 Installation

The AspEmail package is comprised of the following executable files:

AspEmail.dll - the actual AspEmail component library. All other files are only needed if message queuing is used.

EmailAgent.exe - the EmailAgent Windows service running in the background to send queued mail.

EmailAgentCfg.cpl - the EmailAgent configuration applet appearing in Control Panels. EmailLogger.dll - the logging component which provides programmatic access to the

EmailAgent log file.

The setup application aspemail.exe downloadable from the AspEmail.com web site automatically installs all these files along with the documentation and code samples.

In case you need to install the product manually, do the following:

1. Place the file AspEmail.dll in any directory on the server, and register it using the regsvr32 command-line utility:

c:\AspEmail>regsvr32 aspemail.dll

Unless you wish to use message queuing, you are done. If you want to utilize the EmailAgent Windows service for background processing of queued messages, install the EmailAgent files as follows:

2. Place the file EmailAgent.exe in any directory on the server and register it by executing the following command:

c:\AspEmail>EmailAgent -install

The EmailAgent service should now appear in the Services Control Panel, under the name Persits Software EmailAgent. Note that previous versions of EmailAgent (prior to 5.0) appear in the Services list under the name Persits Software Email Agent (with a space between the words "Email" and "Agent").

3. Copy the file EmailAgentCfg.cpl into the \system32 directory of your Windows installation.

4. Register EmailLogger.dll the same way as aspemail.dll using regsvr32.

1.6 Uninstalling AspEmail and EmailAgentTo uninstall AspEmail manually, shut down IIS (net stop iisadmin /y) and stop EmailAgent from Control Panels.

1. Unregister aspemail.dll and emaillogger.dll as follows:

Page 3: ASPMail User Manual

c:\AspEmail>regsvr32 /u aspemail.dllc:\AspEmail>regsvr32 /u emaillogger.dll

2. Delete the file EmailAgentCfg.cpl from the \system32 directory.

3. Uninstall EmailAgent by executing the command

c:\AspEmail>EmailAgent -remove

Chapter 2. Getting Started

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 MethodsIn 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.

Page 4: ASPMail User Manual

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 Portproperty:

Mail.Host = "smtp.mycompany.com" ' RequiredMail.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 = "[email protected]" ' RequiredMail.FromName = "Sales Department" ' Optional

To add message recipients, CCs, BCCs, and Reply-To's, use the AddAddress, AddCC, AddBcc andAddReplyTo 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 "[email protected]", "John Smith"Mail.AddCC "[email protected]" ' 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 formatMail.Subject = "Sales Receipt"Mail.Body = "Dear John:" & chr(13) & chr(10) & "Thank you for your business. Here is your receipt."

or

' HTML formatMail.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 NextMail.SendIf Err <> 0 Then  Response.Write "An error occurred: " & Err.DescriptionEnd If

2.3 Code SamplesThe following code sample demonstrates a simple email-sending form.<%

Page 5: ASPMail User Manual

' change to address of your own SMTP serverstrHost = "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 IfEnd 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>

Page 6: ASPMail User Manual

</TABLE></FORM></BODY></HTML>

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

http://localhost/aspemail/Simple/Simple.asp

http://localhost/aspemail/Simple/Simple.aspx 

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 = TrueMail.Body = "<HTML><BODY><CENTER>" & strHTML & "</CENTER></BODY></HTML>"...

Click the links below to run this code sample.

http://localhost/aspemail/HtmlFormat/HtmlFormat.asp

http://localhost/aspemail/HtmlFormat/HtmlFormat.aspx 

2.4 Email Address ValidationAspEmail 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

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

Page 7: ASPMail User Manual

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 Heloproperty, 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 = "[email protected]"Res = Mail.ValidateAddressMX( "[email protected]" )If Res = "" Then   Response.Write "OK"Else   Response.Write "Not OK: " & ResEnd 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.

Chapter 3. Attachments

3.1 The AddAttachment Method

AspEmail enables your application to send email messages with one or many file attachments. To add an attachment to a message, use the method AddAttachment, which expects a full physical path to the file being attached.

The following code sample demonstrates the usage of this method:

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

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

   Mail.From = "[email protected]"   Mail.FromName = "Persits Software, Inc."   Mail.AddAddress Request("To")

   ' Attach two files in the same directory (any file type can be attached)   strPath = Server.MapPath(".")   Mail.AddAttachment strPath & "\ps_logo.gif"   Mail.AddAttachment strPath & "\wehave.gif"

   ' message subject

Page 8: ASPMail User Manual

   Mail.Subject = "Logo & Motto"   ' message body   Mail.Body = "Persits Software logo and motto images are attached."

   Mail.Send ' send message   Response.Write "Success!"End If%>

<HTML><BODY BGCOLOR="#FFFFFF"><FORM ACTION="Attachments.asp">Enter email: <INPUT TYPE="TEXT" NAME="To"><INPUT TYPE=SUBMIT NAME="Send" VALUE="Send"></FORM></BODY></HTML>

Click the links below to run this code sample:

http://localhost/aspemail/Attachments/Attachments.asp

http://localhost/aspemail/Attachments/Attachments.aspx 

3.2 Memory Attachments (AddAttachmentMem Method)Starting with AspEmail 5.0, files can be attached not only from disk but also from memory. For example, if your application stores images in the database as blobs, you can attach a database-stored image to a message directly, without first exporting the file to the server's hard drive. This enables you to skip a costly step, and avoid file name collisions.

Memory files are attached via the method AddAttachmentMem which expects two arguments: a filename and a memory blob to copy the file content from. The second argument must be a Variant safe array of bytes.

The following code sample attaches images stored in a MS Access database IMAGES.MDB which is included with the installation. To learn more about storing files in the database as blobs, read this chapter of the Persits Software AspUpload manual.

<%' change to address of your own SMTP serverstrHost = "smtp.myisp.net"

If Request("Send") <> "" Then   ' Connect to database   strDbPath = Server.MapPath(".") & "\images.mdb"   ConnectStr = "DRIVER={Microsoft Access Driver (*.mdb)};DBQ=" & strDbPath

   Set rs = Server.CreateObject("adodb.recordset")   rs.Open "images", ConnectStr, 2, 3

   If rs.EOF Then      Response.Write "Recordset is empty."      Response.End   End If

   ' Create instance of AspEmail   Set Mail = Server.CreateObject("Persits.MailSender")   ' enter valid SMTP host   Mail.Host = strHost   Mail.From = "[email protected]"   Mail.FromName = "Persits Software, Inc."

Page 9: ASPMail User Manual

   Mail.AddAddress Request("To")

   ' Attach files stored in database as blobs   While Not rs.EOF      Mail.AddAttachmentMem rs("name").Value, rs("blob").Value      rs.MoveNext   Wend

   ' message subject   Mail.Subject = "Memory Attachments"   ' message body   Mail.Body = "Files from the Database are attached."   Mail.Send ' send message   Response.Write "Success!"End If%>

<HTML><BODY BGCOLOR="#FFFFFF"><FORM ACTION="AttachBlobs.asp">Enter email: <INPUT TYPE="TEXT" NAME="To"><INPUT TYPE=SUBMIT NAME="Send" VALUE="Send"></FORM></BODY></HTML>

Click the links below to run this code sample:

http://localhost/aspemail/Attachments/AttachBlobs.asp

http://localhost/aspemail/Attachments/AttachBlobs.aspx 

3.3 Uploading Attachments with AspUploadCode samples above assume that files being attached are already located on the server. However, if a file to be attached is on a client's machine, it must first be uploaded to the Web server, or it cannot be attached.

To upload a file to the server, you may use any upload component. We recommend Persits SoftwareAspUpload®, a free evaluation copy of which can be downloaded from here.

The following code sample demonstrates the usage of AspEmail/AspUpload tandem:

<%   ' change to address of your own SMTP server   strHost = "mail.elinkisp.com"   ' We use AspUpload component to capture uploaded file and access other form items.   ' Because of the special ENCTYPE attribute we can no longer use Request.Form,   ' we must use Upload.Form instead.   ' More more info on AspUpload, visit www.aspupload.com.

   Set Upload = Server.CreateObject("Persits.Upload")   Upload.IgnoreNoPost = True

   ' capture an upload and save uploaded files (if any) in temp directory   Upload.Save "c:\upload"

   ' We cannot use Upload.Form or Upload.Files until Upload.Save is called.   If Upload.Form("Send") <> "" Then      Set Mail = Server.CreateObject("Persits.MailSender")

Page 10: ASPMail User Manual

      Mail.From = "[email protected]"      Mail.FromName = "Attachment Demo"      Mail.Host = strHost      Mail.Subject = Upload.Form("Subject")      Mail.Body = Upload.Form("Body")      Mail.AddAddress Upload.Form("To")

      ' Handle attached file via Upload.Files collection.      ' Check if a file was ineed uploaded      If Not Upload.Files("Attachment") Is Nothing Then         Mail.AddAttachment Upload.Files("Attachment").Path      End If

      ' We are done. Send message      Mail.Send      Response.Write "Success!"   End If%>

<HTML><BODY BGCOLOR="#FFFFFF"><!-- Note special ENCTYPE attribute: it is necessary to upload a file--><FORM METHOD="POST" ACTION="UploadAttachment.asp" ENCTYPE="multipart/form-data"><TABLE CELLSPACING=0 CELLPADDING=0><TR><TD>Enter email:</TD><TD><INPUT TYPE="TEXT" NAME="To"></TD></TR><TR><TD>Enter Subject:</TD><TD><INPUT TYPE="TEXT" NAME="Subject"></TD></TR><TR><TD>Enter Body:</TD><TD><TEXTAREA NAME="Body"></TEXTAREA></TD></TR><TR><TD>Select File Attachment:</TD><TD><INPUT TYPE=FILE NAME="Attachment"></TD></TR><TR><TD COLSPAN=2><INPUT TYPE=SUBMIT NAME="Send" VALUE="Send"></TD></TR></TABLE></FORM></BODY></HTML>

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

http://localhost/aspemail/UploadAttachment/UploadAttachment.asp

http://localhost/aspemail/UploadAttachment/UploadAttachment.aspx 

3.4 Using Memory Uploads with Memory AttachmentsAspUpload is capable of uploading files to memory rather than saving them to disk. You can combine this feature with AspEmail's memory attachments to attach files directly from memory for better performance and security.

To use memory uploads, the method Upload.Save should be called without arguments. The binary content of a file is accessed via the property File.Binary.

Instead of

If Not Upload.Files("Attachment") Is Nothing Then   Mail.AddAttachment Upload.Files("Attachment").PathEnd If

the following code should be used:

Upload.Save ' save to memory....Set File = Upload.Files("Attachment")

Page 11: ASPMail User Manual

If Not File Is Nothing Then   Mail.AddAttachmentMem File.FileName, File.BinaryEnd If ...

The code samples UploadAttachmentMem.asp and UploadAttachmentMem.aspx demonstrate this memory uploads/memory attachment technique. Click the links below to run this code sample.

http://localhost/aspemail/UploadAttachment/UploadAttachmentMem.asp

http://localhost/aspemail/UploadAttachment/UploadAttachmentMem.aspx 

Chapter 4. Embedded Images

4.1 Linked vs. Embedded Images

Commercial e-mail messages often contain images, graphics and other design elements. When a message is sent in the HTML format, images used in the message body can be either linked or embedded.

Linked images are not part of the message itself. They are usually hosted by the message sender and referenced in the message body via an <IMG> tag pointing to the sender's server, as follows:

<IMG SRC="http://www.sender-company.com/images/flower.jpg">

The main advantage of linked images is that the message body remains small. The main disadvantages are that such messages cannot be viewed off-line, and they have a limited lifespan (images on the sender's server may be moved, deleted, or the server itself may go offline).

Unlike linked images, embedded images are part of the message itself. They are similar to regular attachments, although they use the multipart/related format, as opposed to multipart/mixed. An embedded image is also referenced in a message body using an <IMG> tag, but instead of a URL, an image identifier, or Content ID, is used, as follows:

<IMG SRC="cid:My-Image-Identifier">

A message with embedded images can be viewed off-line and remains intact over time, as images are permanently attached to the body. A message may contain regular attachments and embedded images at the same time.

4.2 The AddEmbeddedImage Method

AspEmail offers support for embedded images via the method AddEmbeddedImage which takes two arguments: the physical path to an image file, and its Content ID, which is simply an arbitrary string without spaces. If your message contains multiple embedded images, each must be assigned a unique Content ID.

The following example uses the file margin.gif (included with the component) as the background image for a message (note that here we use the BACKGROUND attribute of the <BODY> tag instead of <IMG>):

... Mail.Body="<HTML><BODY BACKGROUND=""cid:My-Image"">...</HTML>"Mail.AddEmbeddedImage "c:\aspemaildir\margin.gif", "My-Image"

In a similar manner, you can embed a sound file in your message using the <BGSOUND> tag, for example:

Mail.Body = "<HTML><BGSOUND=""cid:My-Sound""></BGSOUND>...</HTML>"Mail.AddEmbeddedImage "c:\winnt\media\ringin.wav", "My-Sound"

Page 12: ASPMail User Manual

Note: Content-IDs are case-sensitive. Make sure the values specified by "cid:..." and AddEmbeddedImage fully match.

To make your script more readable, you may choose to place your message body in a separate file and import it into the Body property using the method AppendBodyFromFile which accepts a full path to the text or HTML file containing the message body. A body file may look as follows:

<HTML><HEAD><STYLE>BODY {COLOR: #427d64; FONT-FAMILY: "Arial"; FONT-SIZE: 12pt; MARGIN-LEFT: 8em}</STYLE></HEAD><BODY BACKGROUND="cid:My-Background-Image"><CENTER><H2>Thank-you for Shopping At Our Online Store!</H2><B>We hope you will come back soon.</B><P><A HREF="http://www.persits.com"><IMG SRC="cid:Persits-Software-Logo" BORDER=0></A></CENTER></BODY></HTML>

The following code sample demonstrates the usage of AddEmbeddedImage and AppendBodyFromFile:

<%' change to address of your own SMTP serverstrHost = "smtp.myisp.net"

If Request("Send") <> "" ThenSet Mail = Server.CreateObject("Persits.MailSender")' enter valid SMTP hostMail.Host = strHostMail.From = "[email protected]"Mail.FromName = "Persits Software Sales"Mail.AddAddress Request("To")

' message subjectMail.Subject = "Thank-you for your business"' append body from filestrBodyPath = Server.MapPath(".") & "\SampleBody.htm"Mail.AppendBodyFromFile strBodyPath

' Add embedded image for backgroundstrImagePath = Server.MapPath(".") & "\margin.gif"Mail.AddEmbeddedImage strImagePath, "My-Background-Image"

' Add embedded image for logostrImagePath = Server.MapPath(".") & "\ps_logo.gif"Mail.AddEmbeddedImage strImagePath, "Persits-Software-Logo"

Mail.Send ' send messageResponse.Write "Success!"End If%><HTML><BODY BGCOLOR="#FFFFFF"><FORM ACTION="EmbeddedImages.asp">Enter email: <INPUT TYPE="TEXT" NAME="To"><INPUT TYPE=SUBMIT NAME="Send" VALUE="Send">v </FORM></BODY></HTML>

Page 13: ASPMail User Manual

Click the links below to run this code sample:

http://localhost/aspemail/EmbeddedImages/EmbeddedImages.asp

http://localhost/aspemail/EmbeddedImages/EmbeddedImages.aspx 

4.3 The AddEmbeddedImageMem Method

The previous chapter described the method AddAttachment and its "memory" counterpart AddAttachmentMem which attaches a file from memory rather than disk. Like AddAttachment, the AddEmbeddedImage method also has a memory counterpart, AddEmbeddedImageMem, which expects three arguments: the file name, Content ID, and memory array containing the binary content of the file. The latter is usually a recordset value containing a file blob, or a memory upload.

Chapter 5. Authentication & Security

5.1 SMTP Authentication

SMTP servers are often configured to require an email client to provide a username and password when sending a message. This is done to protect the SMTP server from unauthorized use by external users, and to prevent spam.

An attempt to send email via a secured SMTP server may result in run-time errors such as

550 Relaying Denied

The SMTP protocol provides several authentication methods through which a mail client submits its security credentials to the server during an SMTP session. SMTP servers usually support at least one authentication method, but most support several.

The most common SMTP authentication methods are as follows:

1. AUTH=LOGIN

This is the simplest authentication method where the username and password are sent to the SMTP server in clear text (that is, unencrypted) although the values are Base64-encoded. Authentication parameters can therefore be intercepted.

2. CRAM-MD5

The server sends a random string to the client. Both the client and the server calculate an MD5 digest of the concatenation of the random string and the password; the client then sends the server the result of its calculation. The server compares the two results.

This method is more secure than AUTH=LOGIN because the actual password never gets sent to the server.

2. NTLM

This is Microsoft's proprietary authentication protocol also known as "Challenge/Response". It is also secure in the sense that the password never gets transmitted over the network.

5.2 AspEmail's Authentication SupportAspEmail provides two properties, Username and Password through which user credentials are specified.<%...Mail.Username = "Administrator"Mail.Password = "He11o@World!"

Page 14: ASPMail User Manual

...Mail.Send%>

When used in the standard mode (message queuing is not used), AspEmail supports the AUTH=LOGIN method only. When sending queued mail, AspEmail, in conjunction with EmailAgent, supports all three protocols described above. When attempting to negotiate an authentication protocol with the SMTP server, AspEmail tries the authentication methods in the following order: CRAM-MD5, NTLM, AUTH=LOGIN.

5.3 Secure Mail Support

When used in conjunction with Persits Software AspEncrypt, AspEmail is capable of sending signed and/or encrypted messages in the industry-standard S/MIME format.

When sending an encrypted (enveloped) message, the AspEmail/AspEncrypt tandem takes the recipient's digital certificate and encrypts the message with its public key. Only the owner of the certificate can decrypt such a message since no one else has the corresponding private key.

When sending a digitally signed message, the sender certificate's private key is used to sign the message. AspEmail/AspEncrypt are also capable of sending messages that are first signed and then encrypted.

AspEmail is the only ASP component on the market that is officially certified to be S/MIME-enabled by RSA Security, the inventor of public-key cryptography and S/MIME, and was listed on RSA's web site among other S/MIME-enabled software products (the list was recently removed from the RSA web site.)

To learn how to send secure mail with AspEmail/AspEncrypt, read the Secure Mail chapter on the AspEncrypt.com web site.

Here is another useful article by Peter Persits on implementing a secure mail application at15seconds.com.

5.4 Transport Layer Security (TLS) Support

As of Version 5.1, AspEmail supports the Transport Layer Security (TLS) protocol. This secure protocol encrypts all traffic between the email-sending client application and SMTP server, and not just the passwords. The security of the protocol is based on public-key cryptography.

Some SMTP servers require the email sender to use TLS. An example of such a server is Google's popular free smtp.gmail.com server. An attempt to use this SMTP server without TLS results in the error message

530 5.7.0 Must issue a STARTTLS command first.

To enable AspEmail's TLS support, you must set the TLS property to True, as follows:

Mail.Host = "smtp.gmail.com"Mail.Username = "MyGMailAccount"Mail.Password = "He11o@World!"Mail.TLS = True...Mail.Send

Note that TLS is currently only supported by AspEmail itself but not EmailAgent.

Chapter 6. Unicode and Non-ASCII Support

6.1 Quoted-Printable Format

Page 15: ASPMail User Manual

AspEmail is capable of sending messages in alphabets other than US-ASCII by supporting the "Quoted-Printable" format. This format is described in RFC-2045. The idea of the format is that characters with codes less than 33 and greater than 126 are represented by an "=" followed by a two digit hexadecimal representation of the character's value. For example, the decimal value 12 (US-ASCII form feed) is represented as =0C, and the decimal value 61 (US-ASCII "=") can be represented as =3D.

AspEmail encodes the message body in the Quoted-Printable format automatically if theContentTransferEncoding property is set to the string "Quoted-Printable" (letter case is immaterial). You may also set the Charset property to the appropriate character set. The following code snippet sends a message in Russian:

<% @codepage=1251 %>

<%...Mail.Charset = "Windows-1251"Mail.Body = "Сообщение по-русски."Mail.ContentTransferEncoding = "Quoted-Printable"%>

The directive <% @codepage=1251 %> instructs the ASP interpreter to treat the hard-coded characters in the script as Russian symbols (1251 is the Russian code page). As a result, the Body property will receive a Russian Unicode string.

6.2 Non-ASCII Characters in Headers

If you wish to send a message with certain mail headers such as Subject:, To: or From: containing non-US-ASCII characters, you should use the method Mail.EncodeHeader to encode your character string according to the RFC 1522. The method takes one required parameter, the header string, and one optional parameter, the character set, which is "ISO-8859-1" by default. For example:

<% @codepage=1251 %>

<%Mail.Subject = Mail.EncodeHeader("Тема По-русски", "Windows-1251")Mail.FromName = Mail.EncodeHeader("Иван", "Windows-1251")Mail.AddAddress "[email protected]", Mail.EncodeHeader("Штейн")%>

6.3 Unicode and UTF-8

From MSDN: "Unicode is a 16-bit, fixed-width character encoding standard that encompasses virtually all of the characters commonly used on computers today. This includes most of the world's written languages, plus publishing characters, mathematical and technical symbols, and punctuation marks."

From Unicode.org: "Computers ... store letters and other characters by assigning a number for each one. Before Unicode was invented, there were hundreds of different encoding systems for assigning these numbers. No single encoding could contain enough characters... Unicode provides a unique number for every character, no matter what the platform, no matter what the program, no matter what the language."

For example, the basic Latin letter "A" has the code Hex 0041 (65), the Russian letter   has the code Hex 0416 (1046), and the Chinese character   has the code Hex 32A5 (12965).

UTF-8 (Unicode Transformation Format, 8-bit encoding form) is the recommended format to be used to send Unicode-based data across networks, in particular the Internet. UTF-8 represents a Unicode value as a sequence of 1, 2, or 3 bytes.

Unicode characters in the range Hex 0000 to 007F are encoded simply as bytes 00 to 7F. This means that files and strings which contain only 7-bit ASCII characters have the same encoding under both ASCII and UTF-8. Therefore, the Unicode 0041 ("A") in UTF-8 is Hex 41.

Unicode characters in the range Hex 0080 to 07FF are encoded as a sequence of two bytes For example, the Unicode 0416 ( ) is encoded as Hex D0 96. Unicode characters in the range Hex 0800 to FFFF are encoded as a sequence of three bytes. For example the Unicode 32A5 ( ) is encoded as Hex E3 8A A5.

Page 16: ASPMail User Manual

6.4 UTF-8 Support in AspEmail

AspEmail 5.0 offers full UTF-8 support in both a message body and headers. To send a UTF-8 encoded message, you must set the CharSet property to the string "UTF-8" (case is immaterial), andContentTransferEncoding to "Quoted-Printable". You should also pass "UTF-8" as the second argument to EncodeHeader.

The following code sample demonstrates the UTF-8 usage:

<%' change to address of your own SMTP serverstrHost = "smtp.myisp.net"

' Enable UTF-8 -> Unicode translation for form itemsSession.CodePage = 65001 ' UTF-8 code

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

   Mail.From = "[email protected]" ' From address   Mail.FromName = Mail.EncodeHeader(Request("FromName"), "utf-8")   Mail.AddAddress Request("To")

   ' message subject   Mail.Subject = Mail.EncodeHeader( Request("Subject"), "utf-8")

   ' message body   Mail.Body = Request("Body")

   ' UTF-8 parameters   Mail.CharSet = "UTF-8"   Mail.ContentTransferEncoding = "Quoted-Printable"   Mail.Send ' send message   Response.Write "Message sent to " & Request("To")End If%>

<HTML><HEAD><META HTTP-EQUIV="Content-Type" content="text/html; charset=utf-8"><TITLE>AspEmail: Unicode.asp</TITLE></HEAD><BODY>

<FORM METHOD="POST" ACTION="Unicode.asp"><TABLE CELLSPACING=0 CELLPADDING=0><TR><TD>Enter email:</TD><TD><INPUT TYPE="TEXT" NAME="To"></TD></TR><TR><TD>Enter your name:</TD><TD><INPUT TYPE="TEXT" NAME="FromName"></TD></TR><TR><TD>Enter Subject:</TD><TD><INPUT TYPE="TEXT" NAME="Subject"></TD></TR><TR><TD>Enter Body:</TD><TD><TEXTAREA cols="50" rows="10" NAME="Body"></TEXTAREA></TD></TR><TR><TD COLSPAN=2><INPUT TYPE=SUBMIT NAME="Send" VALUE="Send"></TD></TR></TABLE></FORM></BODY></HTML>

This code sample has several important elements you must not overlook:

Page 17: ASPMail User Manual

<META HTTP-EQUIV="Content-Type" content="text/html; charset=utf-8">

This META tag specifies the character set for this page to be UTF-8. This, among other things, instructs the browser to UTF8-encode all form items when the form is submitted.

Session.CodePage = 65001

This line instructs our ASP script to convert UTF8-encoded form items (returned by the Request.Form collection) back to regular Unicode strings. The number 65001 is the UTF-8 code page.

Mail.Subject = Mail.EncodeHeader( Request("Subject"), "utf-8")

The second optional argument is set to "UTF-8" for proper encoding of the header.

Mail.CharSet = "UTF-8"Mail.ContentTransferEncoding = "Quoted-Printable"

These two lines ensure proper UTF-8 encoding of the message body.

Click the links below to run this code sample:

http://localhost/aspemail/NonAscii/Unicode.asp

http://localhost/aspemail/NonAscii/Unicode.aspx 

6.5 Valid CharSet Values

You may specify the following string values for the CharSet property, as well as the second optional argument to the EncodeHeader method:

Value Meaning

"UTF-8" UTF-8

"UTF-7" UTF-7

"Windows-1250""cp1250"

ANSI - Central Europe

"Windows-1251""cp1251"

ANSI - Cyrillic

"Windows-1252""cp1252""ascii""us-ascii"

Latin I

"Windows-1253""cp1253"

ANSI - Greek

"Windows-1254""cp1254"

ANSI - Turkish

"Windows-1255""cp1255"

ANSI - Hebrew

"Windows-1256""cp1256"

ANSI - Arabic

"Windows-1257""cp1257"

ANSI - Baltic

"Windows-1258""cp1258"

ANSI - Vietnamese

"ISO-8859-1" Latin I (default value)

"ISO-8859-2" Central Europe

"ISO-8859-3" Latin 3

"ISO-8859-4" Baltic

"ISO-8859-5" Cyrillic

"ISO-8859-6" Arabic

Page 18: ASPMail User Manual

"ISO-8859-7" Greek

"ISO-8859-8" Hebrew

"ISO-8859-9" Latin 5

"ISO-8859-15" Latin 9

"cp866" Russian DOS

"koi8-r" Russian

"koi8-u" Ukrainian

"shift_jis" Japanese Windows

"ks_c_5601-1987""korean"

Korean

"EUC-KR""korean"

EUC - Korean

"BIG5" Traditional Chinese Windows

"GB2312""chinese"

Simplified Chinese

"HZ-GB-2312" Simplified Chinese HZ

"EUC-JP" EUC - Japanese

"X-EUC-TW" EUC - Traditional Chinese

Chapter 7. Message Queuing.

7.1 Why Use Message Queuing?

When the method Mail.Send is called, AspEmail opens a session with the SMTP server and sends message information to it for further processing and delivery. Depending on the message size, an SMTP session may take a long time to complete. Sending messages to hundreds or thousands of recipients may put a heavy load on IIS for an extended period of time and affect the overall Web server performance.

AspEmail 5.0 offers the flag Mail.Queue which, if set to True, instructs the Send method to place a message in a queue and return immediately, without opening an SMTP session. Your message-sending ASP script no longer has to wait until a message is sent, which means a better client-response time and less load on IIS.

AspEmail is shipped with EmailAgent.exe, a Windows service running in the background, which polls the message queue and sends out queued messages. EmailAgent 5.0 is capable of opening up to 64 simultaneous SMTP sessions for quicker processing.

The old method Mail.SendToQueue is still supported for backwards compatibility, but it is recommended that the sequence

Mail.Queue = TrueMail.SendXXX

be used instead (where SendXXX is one of the following methods: Send, SendEncrypted, SendSigned, and SendSignedAndEncrypted). Unlike older versions, AspEmail 5.0 can queue encrypted and/or signed messages as well.

AspEmail creates message files in the plain ASCII format, so that they can be easily viewed and modified by hand, if necessary. A typical file name looks like this: 20030408-16195159-23c-0.eam-new. Once a message file is placed in the queue, its name can be retrieved via the read-only propertyMail.QueueFileName.

7.2 Configuring EmailAgent

Page 19: ASPMail User Manual

EmailAgent installation instructions can be found in Chapter 1. Once EmailAgent has been installed on your system, the EmailAgent button should appear in Control Panels, as follows:

Double-click on the EmailAgent button. The EmailAgent Control Panel applet will come on which enables you to configure, launch and shut down EmailAgent. It also allows you to monitor thread status and view logs.

The General tab displays the current status of the EmailAgent service as a whole (left pane) and each individual thread (right pane). The Go button launches the service, Stop stops the service, and Queuedisplays the content of the message queue folder.

Page 20: ASPMail User Manual

The Configuration tab contains basic parameters including the message queue folder, the number of simultaneous SMTP sessions, and others.

Message Queue PathThis parameter specifies a folder on the server's hard drive where queued messages are placed when the Mail.Queue property is set to True and the method Mail.Send is called. Any physical folder can be used for queued messages. EmailAgent will automatically create 4 subfolders underneath the specified folder: \Sent, \Failed, \Incoming, and \Log. Successfully sent messages are copied from the main queue folder to the \Sent folder, and failed messages to the \Failed folder. Incoming message are saved in the \Incoming folder. The \Log folder contains the log file.

Simultaneous SessionsThis number must be between 1 and 64 and defaults to 16. It specifies the number of SMTP sessions EmailAgent opens simultaneously with an SMTP server to send out queued mail.

Tip: While it may be tempting to use all 64 threads, consider the following: if your SMTP server is configured to limit the total number of simultaneous sessions to, say, 20, all extra sessions will be dropped, and the corresponding messages returned to the queue for resending. This will actually slow your system down. Ask your system administrator how many simultaneous sessions your SMTP server allows, and set this parameter accordingly.

Poll message queue every ... secondsThis parameter specifies when to poll the message queue again if it is currently empty.

Repeat sending after ... minutesWhen a non-fatal error occurs during an SMTP session, a message is left in the main queue for EmailAgent to try and resend it. This parameter specifies how soon EmailAgent should attempt to send this message again.

Cancel sending after ... hoursIf a message generates a non-fatal error, EmailAgent attempts to send it repeatedly for the specified number of hours. If unsuccessful, it copies the message to the \Failed folder. Once a message is in the \Failed folder, no further attempts are made to send it.

Do not move sent messages to the \Sent folderBy default, all successfully sent messages are moved to the \Sent folder. If this option is checked, sent messages are simply deleted from the queue.

Page 21: ASPMail User Manual

The SMTP tab configures SMTP parameters.

Relay through ... Host/Relay through DNSStarting with AspEmail 5.0, the Mail.Host property is optional. If no Host is specified when generating queued mail, EmailAgent will use the host address specified in Relay through .... Host, or attempt to use the recipient's own SMTP server, if Relay through DNS is selected.

The address of the recipient's SMTP server is derived from the recipient's email address by looking up DNS records. DNS relaying is slower but it does not require the sender to have his/her own SMTP relay server.

Use AuthenticationIf necessary, specify authentication parameters to be used with the SMTP server.

The POP3 and Log tabs will be described in the next chapter.

7.3 Deferred ProcessingWith AspEmail 5.0, you can specify the exact date and time when you want a message to be delivered via the Timestamp property, as follows:

...Mail.Timestamp = CDate("Feb 28, 2003 10:15:00 PM")Mail.Queue = TrueMail.Send

If you wish a message to be delivered in, say, 5 hours, the following code may be used:

Mail.Timestamp = Now() + 5/24 ' dates are measured in days, so 1/24 is one hour

7.4 EmailAgent vs. EmailAgent.NET

While EmailAgent will continue to be supported, we recommend that EmailAgent.NET, a more advanced version of EmailAgent released on Nov 1, 2011, be used instead. EmailAgent.NET is shipped with AspEmail.NET but can be used with AspEmail as well. It does not require a separate license.

Compared to EmailAgent, EmailAgent.NET supports multiple queues, up to 256 simultaneous sessions per queue, TLS and, improved logging.

For more information about EmailAgent.NET, please see Chapter 4 of the AspEmail.NET User Manual.

Page 22: ASPMail User Manual

7.5 Logging

EmailAgent logs all failed sends in the ascii text file EmailAgent.log located under the \Log sub-folder of the main message queue folder. It can optionally log successful sends as well.

A typical failure entry may look as follows:

2003/02/20 17:51:31.793 File:20030220-17512416-980-0 From:<[email protected]> To:<[email protected]> FAILURE: SMTP connect to servername:25

A success entry may look as follows:

2003/02/20 17:55:03.578 File:20030220-17545845-980-0 From:<[email protected]> To:<[email protected]> SUCCESS: Sending to imail.innerhost.com [imail.hosting.innerhost.com]: 250 Message queued

All entries contain a timestamp, the name of a file containing the message, the From: and To: information, and a reason for failure (or a success notification from the SMTP server).

Whether to log all messages or errors only can be set on the Log tab:

If you opt to log error messages only, you may also choose to log POP3 retrievals. These types of log entries are useful for bounced message handling described below.

7.6 Programmatic Access to the LogThe AspEmail setup includes a component, EmailLogger.dll, which provides programmatic access to the log entries.

The following code snippet opens the current log file and displays all entries in it:

Set Logger = Server.CreateObject("Persits.MailLogger")Logger.Open ' open default log

For Each Record in Logger.Records   Response.Write Record.Text & "<BR>"Next

Logger.Close

The Open method accepts an optional argument specifying the location of the log file. If nothing is specified, the default log file is opened.

Page 23: ASPMail User Manual

The Records property returns the collection of LogEntry objects representing individual log entries. The LogEntry object supports the following properties:

Text - returns the entire log entry text.

FileName - returns the filename of the message file responsible for this entry.

DateTime - returns timestamp information for this log entry.

Status - returns the strings "SUCCESS", "FAILURE", "ERROR", "SYSTEM" or "RECEIVED" for a successful send, failed send (non-fatal, message will be resent), failed send (fatal, message will not be resent), system error, or received email, respectively. Mail receiving is covered later in this chapter.

Recipient - returns the recipient address. This property is particularly useful for bounced mail handling purposes (covered below).

7.7 Bounced Mail Handling

Every time an email message is sent by a company to a large number of recipients (e.g. a newsletter to subscribers), the sender almost always receives a certain amount of "bounced" mail as addresses tend to become obsolete over time. Therefore, any database of email addresses needs to be cleaned up periodically to get rid of addresses that are no longer valid. AspEmail 5.0 offers a set of features enabling you to handle bounced mail efficiently.

You must take the following steps to set up a bounced-mail handling framework using AspEmail 5.0:

Step 1. Set up a "sink" mail account where all bounced messages would go. Let's call [email protected]. You may also use an existing mail account.

Step 2. In your mail-sending script, set the property Mail.MailFrom to the "sink" address:

Mail.MailFrom = "[email protected]"

This ensures that all bounced messages will come to this address, and not the one specified viaMail.From.

Step 3. Configure EmailAgent's POP3 tab:

The option "Disable APOP" should be used if your POP3 server does not support APOP authentication, which is rare.

Page 24: ASPMail User Manual

Step 4. During and after a batch send, EmailAgent will retrieve bounced messages from the "sink" account and place them into the \Incoming subfolder underneath the main message queue folder. At the same time, an entry will be added to the log, which may look as follows:

2003/02/28 13:20:13.637 SUCCESS: Received message #1 C:\Queue\Incoming\2816cd831.eam-rcv (11297 bytes) [email protected]

You can now retrieve and process all bounced mail addresses using the EmailLogger component, as follows:

Set Logger = Server.CreateObject("Persits.MailLogger")Logger.Open ' open default log

For Each Record in Logger.Records   If Record.Status = "RECEIVED" and Record.Recipient <> "" Then       ' Do something with Record.Recipient   End ifNext

Logger.Close

You can replace the "Do something" line with ADO-based script that removes the Record.Recipient value from your address database.

Note that Record.Recipient can sometimes be empty as it is not always possible to extract a recipient address from a bounced message, therefore you must test this property for an empty value.

IMPORTANT: You must enable the option "Log all messages" or check the box "Log POP3 Retrievals" on the Log tab for the bounced-message feature to work.