Sending SMTP-Authenticated Email From ASP.Net
Brad Kingsley
August 15, 2005
I wrote an article in May 2005 on
how to send email via ASP.Net v2.0.
This is a quick follow-up to that article with additional information specifically addressing the issue of SMTP-Authentication against a remote mail server.
Many web hosts now have their servers "locked down" and require a username and password to send email from their servers. If you have code that uses "localhost" (the SMTP service running on the local machine) then this shouldn't be an issue, but if you have a situation where you need to relay email off a remote mail server that is secured, this article should help you.
The real work is done by the NetworkCredential object. According to MSDN this object "provides credentials for password-based authentication schemes such as basic, digest, NTLM, and Kerberos authentication". The benefit of making this a two-step process rather than passing username and password to the .Credentials property of the SmtpClient object isn't clear, but that is what's required.
Here is a fully working quick code sample that you can use to get started on your own SMTP-Auth supporting email code.
'Create a new MailMessage object and specify the "From" and "To" addresses
Dim Email As New System.Net.Mail.MailMessage("Brad.Kingsley@orcsweb.com", "Brad@KingsleyTeam.com")
Email.Subject = "test subject"
Email.Body = "this is a test"
Dim mailClient As New System.Net.Mail.SmtpClient()
'This object stores the authentication values
Dim basicAuthenticationInfo As New System.Net.NetworkCredential("username", "password")
'Put your own, or your ISPs, mail server name on this next line
mailClient.Host = "Mail.RemoteMailServer.com"
mailClient.UseDefaultCredentials = False
mailClient.Credentials = basicAuthenticationInfo
mailClient.Send(Email)
I would like to thank Marcus McConnell of BV Software and also Brian Linden from CastAds Inc for their tips on how to integrate the SMTP-Authentication process.
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.