Sending Email From ASP.Net
By Brad Kingsley
May 16, 2005
Sending email from ASP.Net 1.0 and 1.1 was very easy. It is still easy with ASP.Net
2.0 - assuming you know the new class names. I'm not sure why Microsoft changed these classes - certainly there is a reason, I just don't know it yet.
The System.Net.Mail class is what replaced the System.Web.Mail class. There are a number of classes within this class and it wasn't exactly clear to me at first
what was needed to send email. I messed with a number of the classes trying to Dim
a New object and then set properties like the way I'm used to doing it, but no combinations
I tried would work.
What I did find was the System.Net.Mail.SmtpClient class which has a method named
Send. Rather than setting properties and calling this method, I just wound up passing
the values I wanted into this method - doing all the "real" work on a single line.
One property that you do need to set before calling Send is the Host property so
the class knows where to send the SMTP email for delivery.
I won't bore you with the simple form I created to test this. I had four textboxes
- "EmFrom" for the sender email address, "EmTo" for the email address I'm sending
to, "EmSubj" for the subject of the email, and "EmMsg" for the body text of the
email.
These three lines do all of the work:
Dim MailObj As New System.Net.Mail.SmtpClient
MailObj.Host = "localhost"
MailObj.Send(EmFrom.Text, EmTo.Text, EmSubj.Text,
EmMsg.Text)
The above assumes you
are using the local SMTP service on the machine where this code is running. You
can also specify a remote host but I don't know (yet) how to authenticate against
a remote host with SMTP-Auth (which most SMTP hosts are running now).
Hopefully this will help someone else and save them the time that I spent digging
into this. If anyone reading this understands the value of all the other System.Net.Mail
classes, please either send feedback to me and I'll write something up, or put it
in an article for the rest of us to see.
Happy coding!
~Brad
Brad Kingsley is founder and president
of ORCS Web, Inc.
- a company that provides managed hosting solutions for clients who develop and deploy their applications on Microsoft Windows platforms. Services include shared hosting, dedicated hosting, and webfarm hosting, with specialty in .Net, SQL Server, and architecting highly scalable solutions.