Sending E-mail with .Net, the Easy Way
You can send robust e-mail messages from your .Net app within minutes...

In this edition of E-mail Secrets you will learn the basics of sending e-mail with .Net.  We will take a look at the issues pertaining to the needs of most developers and explain them in an easy to understand way.  We will try to stay away from complicated topics such as MIME, Base64, etc... Most of the software that we will use to send the messages is free and shields the developer from a learning curve.  Most importantly, we will show you how to start sending e-mail from your .Net apps right away.  The included sample code can be downloaded and you can be sending e-mail like a pro in minutes...  Read on...

In this edition you will learn:

This edition also contains sample code that will enable you to:

Do you really want to look under the hood?...

Sending e-mail is either incredibly complicated, or a very simple task.  It all depends on your perspective.  Every day we get into our cars and drive from here to there, mostly not worrying about the mechanics under the hood.  E-mail is similar.  Users of popular e-mail software can send an e-mail message without having to worry about the low level details such as RFC-822, MIME, Base64, etc...

Developers of e-mail applications often find themselves wrestling with these details, but that does not have to be so.  With the advent of several excellent developer tools (assemblies in .Net speak), any developer with even trivial .Net experience can send e-mail like the pros without worrying about the complexities "under the hood."

I am not going to dwell on these complexities, because I don't believe that you need to understand them to build a successful e-mail enabled application.  If you appreciate the finer details of the process, there are plenty of RFC's on the Internet which you can spend countless hours deciphering.  Suffice it to say that I have done that so you don't have to.  For those who want to build dependable applications that send e-mail, without investing in a large learning curve, read on...

The very basics...

Even though I promised not to waste your time and/or bore you with the low level details, I want to give you a basic primer on e-mail technology because I think that it will help you ground yourself and enable you to relate what I have to say in this article with other things you may read. 

E-mail is delivered across the Internet with the SMTP protocol.  The SMTP protocol dictates how e-mail messages are submitted to the Internet and delivered to the recipient.  The construct of each message is governed by many other specifications.  The specifications for SMTP and the construct of messages are contained in the multitude of RFC's floating around the Internet.

Without diving into all the internals, I want you to know that the code in this newsletter will enable you to build messages that take advantage of all the latest e-mail technologies while preserving compatibility across the different mail servers and readers on the net.

Enough said, lets get on with it.

The following sample will show you how to send e-mail from your .Net applications with only one line of code...

The absolutely easiest and fastest way to send email...

This one line of code will create and send an e-mail message.  It uses the FreeSMTP.Net assembly, which can be downloaded here.  More on FreeSMTP.Net in a minute...

VB Sample	
Quiksoft.FreeSMTP.SMTP.QuickSend( _
   "mail.yourdomain.com", _
   "recipient@domain.com", _
   "sender@domain.com", _
   "Subject...", _
   "Message text.", _
   Quiksoft.FreeSMTP.BodyPartFormat.Plain)
C# Sample			
Quiksoft.FreeSMTP.SMTP.QuickSend(
    "mail.yourdomain.com",
    "recipient@domain.com",
    "sender@domain.com",
    "Subject...",
    "Message text.",
    Quiksoft.FreeSMTP.BodyPartFormat.Plain);

It doesn't get much easier than this.  Add a reference to the FreeSMTP.Net assembly, and call the QuickSend method.  Because the QuickSend() method is static, you do not even have to instantiate a class.  The method will even allow the sending of HTML messages, by setting the last parameter to BodyPartFormat.HTML.

FreeSMTP.Net is free as its name implies.  But don't think that because it is free, that it is not good.  FreeSMTP.Net is produced by Quiksoft who also produces the popular EasyMail Objects, EasyMail Advanced API and EasyMail .Net EditionQuiksoft specializes in e-mail technologies for professional developers.  FreeSMTP.Net is offered by Quiksoft as an introduction to its product line.  It is not often that you find quality in things for free, but FreeSMTP.Net is clearly an exception.

Sending an attachment...

Since the QuickSend() method does not support attachments, we will instantiate the FreeSMTP.Net EmailMessage object, add the attachments and send it with an instance of the FreeSMTP.Net SMTP class.  As you can see, all this requires only a few lines of code.

VB Sample	
Dim msg As New EmailMessage( _
   "recipient@domain.com", _
   "sender@domain.com", "Subject...", _
   "Message text.", _
   BodyPartFormat.Plain)
msg.Attachments.Add("c:\\attachment.txt")
Dim smtp As New SMTP("mail.yourdomain.com")
smtp.Send(msg)
			
C# Sample			
EmailMessage msg = new EmailMessage(
   "recipient@domain.com",
   "sender@domain.com", "Subject...",
   "Message text.",
   BodyPartFormat.Plain);
msg.Attachments.Add("c:\\attachment.txt");
SMTP smtp = new SMTP("mail.yourdomain.com");
smtp.Send(msg);

Sending HTML message with support for non HTML mail readers...

To send an HTML message with support for non HTML mail readers, we must actually send two message bodies.  One is formatted in HTML and the other in plain text.  Mostly every non HTML mail reader will be able to ignore the HTML and display the text body instead.

Many people are using the System.Web.Mail class to send mail through their .Net apps, but there are many reasons why this might not be the best route.  We will touch on this again, but for now I would like to point out that the System.Web.Mail class does not support sending more than one body format in the same message.  Therefore, the System.Web.Mail classes do not allow you to send an HTML message with support for non HTML readers.

VB Sample	
Dim msg As New EmailMessage( _
   "recipient@domain.com", _
   "sender@domain.com", "Subject...", _
   "Text message.", BodyPartFormat.Plain)
Dim html As New String( _
   "<html><body><b>HTML</b> message.</body></html>")
msg.BodyParts.Add(html, BodyPartFormat.HTML)
Dim smtp As New SMTP("mail.yourdomain.com")
smtp.LogFile = "c:\\smtp log.txt"
smtp.Send(msg)

C# Sample
EmailMessage msg = new EmailMessage(
   "recipient@domain.com",
   "sender@domain.com", "Subject...",
   "Text message.", BodyPartFormat.Plain);
string html =
   "<html><body><b>HTML</b> message.</body></html>";
msg.BodyParts.Add(html, BodyPartFormat.HTML);
SMTP smtp = new SMTP("mail.yourdomain.com");
smtp.LogFile="c:\\smtp log.txt";
smtp.Send(msg);

In this example we instantiate an EmailMessage class using the overloaded constructor to create a plain text message.  Next we add a new body part to the message formatted as HTML.  The FreeSMTP.Net assembly will automatically use this information to create a message that contains both plain text and HTML versions of the message.  Beneath the hood, the Send() method builds a MultiPart Alternative MIME message.  The developer is shielded from the complexity of MIME, but can rest assured that their message is compatible with mostly every mail reader.

Continue on to find out about the #1 problem that affects most developers sending e-mail from their apps...

Getting your message onto the Internet...

To get your message out onto the Internet, it must be submitted to an SMTP server.  The SMTP class of FreeSMTP.Net needs the address of a mail server that will accept your message.  In the previous examples we have specified the mail server as mail.yourdomain.com.  Of course your mail server will be different, so be sure to change this in your code.

The role of the mail server is to accept your message and see that it gets delivered to the recipient.  If the recipient is local (i.e. the same domain as the mail server) the process is all handled internally by the mail server.  If the recipient is located outside of your mail server's domain (usually the case), the mail server will find and contact the recipient's mail server and deliver the message to it.  This process is called "relaying".

The number one problem that trips up most developers trying to build their first mail enabled application, is that their mail server rejects the messages that are sent to it by their application. 

Mostly every mail server on the Internet employs some type of "relay" security.  This security prevents spammers from using your mail server as a gateway to get their messages out on the Internet.  The side effect of this is that if your mail server does not think that you or your application are authorized to relay mail through it, it will reject your messages.  There are several different methods of employing security on mail servers.  Some mail servers will only accept mail from certain IP addresses.  Some may require your application to authenticate itself by providing a user name and a password before it will allow you to submit mail for non-local delivery.  Your mail server administrator should be able to tell you the type of authentication employed.

In any event, if your messages are being rejected by your mail server, you will need to diagnose the problem and take corrective measures so that your server will accept your messages.

The SMTP class of the FreeSMTP.Net assembly contains a LogFile property which is very useful in debugging your applications.  Simply set the LogFile property to a file name and it will automatically create a log of the SMTP conversation with the server.  By viewing this log in notepad, you can see exactly what the problem is.  i.e.:

smtp.LogFile="c:\\smtp log.txt" 

Here is the output of a log file that I created:

Connect to server. mail.quiksoft.com 
220 quiksoft.com MailSite ESMTP Receiver 
EHLO domain.com
250-quiksoft.com
250-SIZE 0
250-ETRN
250-ENHANCEDSTATUSCODES
250-X-IMS 3 10398
250-DSN
250-VRFY
250-AUTH SCRAM-MD5 LOGIN CRAM-MD5 NTLM
250-AUTH=LOGIN
250 8BITMIME
MAIL FROM:<sender@domain.com>
250 2.0.0 sender@domain.com OK
RCPT TO:<recipient@domain.com>
501 5.7.1 This system is not configured
to relay mail from <sender@domain.com>
to <recipient@domain.com> for 69.80.22.132

The only item of interest here is the last line which clearly indicates why the server rejected the message.  The logging capability or FreeSMTP.Net will save you loads of time diagnosing SMTP problems and is another feature that distinguishes the FreeSMTP.Net classes from System.Web.Mail.  System.Web.Mail does not allow you to log the SMTP conversation and therefore is of little help, when you experience problems.

Solving the relay problem...

If you are experiencing relaying problems, there are several ways to solve them. 

1. Mail server configuration
If your application will be running on the same IP or group of IP addresses every time, your mail server administrator may be able to configure the mail server to accept all mail from those IP addresses.

2. Use a different SMTP server
You may have access to a different server that does not require authentication, or one that has been previously setup to accept messages from you.  Another alternative is to install your own dedicated SMTP server which will accept and deliver the messages for you without question.  One such server is SMTP Express.  There are many other benefits to using a server like SMTP Express.  For example, since SMTP Express runs on the same computer as your application, you can submit messages to SMTP Express much faster than submitting them to a remote mail server.  In fact the SMTP class of FreeSMTP.Net  contains a SubmitToExpress() method that will submit your message to SMTP Express via the file system, which will be about 10x faster than submitting through TCP/IP to a traditional mail server.  This means that your application will be more responsive, because SMTP Express will handle the delivery in the background.  Additionally, SMTP Express is dedicated to your application which means that your important outbound mail will not be placed at the bottom of the queue of mail already being processed by your main mail server.  Among other benefits, SMTP Express will automatically retry failed messages, enable you to monitor the progress of your mail blast, and even send up to 256 messages simultaneously.  For more information on SMTP Express, visit http://www.quiksoftcorp.com/smtpexpress.

3. Configure your application to authenticate itself with a user name and password 

Please read on to find out how to configure your application to authenticate itself with a user name and password...

If your server requires you to authenticate with a user name and password...

If your server will allow you to authenticate with a user name and password, you can configure your application to do so.  We have been using the FreeSMTP.Net classes thus far, however one feature it does not support is SMTP authentication with a user name and password.  For the following example we will use the SMTP class of EasyMail .Net Edition to do the authentication.  EasyMail .Net Edition is the big brother to FreeSMTP.Net.  It can be downloaded here.  The interface is the same as FreeSMTP.Net and is therefore compatible with it.  So if you develop your application with FreeSMTP.Net and then want to add more power or features later, upgrading to EasyMail .Net Edition is a snap.  Here is the code, using EasyMail .Net Edition which does the authentication:

VB Sample		
Quiksoft.EasyMail.SMTP.License.Key = _
   "Put your license key here"
Dim msg As New EmailMessage( _
   "recipient@domain.com", _
   "sender@domain.com", "Subject...", _
   "Message text.", BodyPartFormat.Plain)
Dim smtp As New SMTP()
Dim server As New SMTPServer()
server.Name = "mail.yourdomain.com"
server.AuthMode = SMTPAuthMode.AuthLogin
server.Account = "user"
server.Password = "password"
SMTP.SMTPServers.Add(server)
smtp.Send(msg)
		
C# Sample	
Quiksoft.EasyMail.SMTP.License.Key=
   "Put your license key here";
EmailMessage msg = new EmailMessage(
   "recipient@domain.com",
   "sender@domain.com", "Subject...",
   "Message text.", BodyPartFormat.Plain);
SMTP smtp = new SMTP();
SMTPServer server = new SMTPServer();
server.Name="mail.yourdomain.com";
server.AuthMode=SMTPAuthMode.AuthLogin;
server.Account="user";
server.Password="password";
smtp.SMTPServers.Add(server);
smtp.Send(msg);

The code here is somewhat different to what we have seen in the past.  I want to note that the same code we previously wrote for FreeSMTP.Net will compile and run perfectly with the EasyMail .Net Edition classes.  But for this example, I wanted to change the code a bit to show you some of the advanced capabilities of EasyMail .Net Edition.

The first difference you will notice is the assignment of a LicenseKey property in the first line of code.  EasyMail .Net Edition requires a license key to operate.  You can obtain a trial license key or purchase a permanent one from Quiksoft.  Another item to note is the creation of the SMTPServer object which is added to the SMTPServers collection.  EasyMail .Net Edition enables you to specify an unlimited number of servers for your outgoing message.  This is for backup or failsafe operations.  Each server in the list is tried until the message is sent successfully.  Therefore if your primary mail server is down, the message may still be delivered.  In this example however we have only specified one server.  The AuthMode, Account and Password properties of the SMTPServer class are used to setup the authentication.

EasyMail .Net Edition supports many more features than FreeSMTP.Net or System.Web.Mail.  You can view a comparison here.

Conclusion...

That's really it - it's pretty simple.  Armed with the knowledge I have supplied and the software such as FreeSMTP.Net or EasyMail .Net Edition you will have your .Net applications sending world class e-mail in no time.  In a future edition I will tackle more advanced SMTP topics such as mass mailings, dealing with international character sets, tracking the delivery status of your messages, importing HTML content and more...  If you have suggestions for newsletter material involving any other SMTP issue, please let me know.

 


John Alessi has specialized in e-mail development for the past 6 years and has helped many large companies such as Microsoft, Boeing and EarthLink with their e-mail needs. He can be reached at john@quiksoftcorp.com.

 

 

 

©2003 Quiksoft Corporation. All rights reserved. Unauthorized duplication or distribution prohibited. Quiksoft, EasyMail, EasyMail Objects, EasyMail .Net Edtion, EasyMail Advanced API, EasyMail SMTP Express, and MailStore are trademarks of Quiksoft Corporation. Other trademarks mentioned are the property of their legal owner.