Sending SMTP Email with Authentication using ASP.NET
One of the topics I teach in my ASP.NET course is the process of sending email using SMTP. The process is relatively simple, you create a new instance of the MailMessage class, passing in two required parameters into the constructor: To and From email addresses. Next you set the Subject property, optionally set the IsBodyHtml property, and finally set the Body property with the content of your email that your recipients will actually read. To send the email you create a new instance of the SmtpClient class, passing in the path to the SMTP host and optionally set the port number. To send the email you simply call the Send() method, passing in the MailMessage object and you’re good to go. A generic implementation of this script begins to look something like this:
Dim oMail As New MailMessage("zak@modulemedia.com", "zak@modulemedia.com")
oMail.Subject = "CONTACT FORM"
oMail.IsBodyHtml = True
oMail.Body = "Message: " & txtMessage.Text
Dim oSend As New SmtpClient("localhost")
oSend.Send(oMail)
As you can see from this script, the code assumes that you’re using Localhost (127.0.0.1) as the SMTP mail server. This is fine if you’re using Windows 2000 or Windows XP Pro where the SMTP Virtual Mail server was still part of IIS. But what if you’re developing in Windows Vista or Windows 7 where SMTP Virtual Mail was eliminated for many reasons including security? What if you’re building an application that you’ll actually be deploying to a remote Web host and need to configure SMTP to use a mail server that requires authentication? Perhaps you want to use your Internet Service Provider’s (ISP) SMTP mail server for relaying email for the Web application you are building? In these scenarios, you’ll need to configure authentication in an effort to connect to your Exchange server or ISP’s mail server. This can be done easily in ASP.NET thanks to the NetworkCredential class. Accepting your username and password as parameters into the constructor, the NetworkCredential class assures authentication with your mail server. The above code can be modified accordingly as follows:
Dim oMail As New MailMessage("zak@modulemedia.com", "zak@modulemedia.com")
oMail.Subject = "CONTACT FORM"
oMail.IsBodyHtml = True
oMail.Body = "Message: " & txtMessage.Text
Dim oSend As New SmtpClient("mail.yourserver.com")
Dim oUser As New System.Net.NetworkCredential("admin@yourserver.com", "password")
oSend.UseDefaultCredentials = False
oSend.Credentials = oUser
oSend.Send(oMail)
As you can see we modify the parameter passed into the SmtpClient class to use the mail server that you want to authenticate to. Second, we create a new instance of the NetworkCredential class, passing in the username and password as parameters into the constructor. Next we set the important UseDefaultCredentials property to False. By default, this property is set to True which means anonymous credentials are passed to the mail server…this is usually why you’ll receive an error message in regards to authenticating to the mail server. Setting this property to False guarantees that our username and password are passed in instead. Finally we set the Credentials property of our SmtpClient object variable equal to our NetworkCredential object variable, call the Send method, and we’re done. Email should send successfully!
Comments:
0 Tags:
asp.net,
smtp
Reading the syndication.axd file from your BlogEngine.NET powered blog
If you’re reading this blog entry, chances are you’re unaware (and probably don’t care) of how it was built. The questions don’t start popping up until it’s time for you to create your own blog and when that time comes, you’ll have tons of options to choose from. The one I use, primarily because of my fondness of ASP.NET, is BlogEngine.NET. BlogEngine.NET, like most blogging applications is free to download, easy to install and customize, and more importantly offers just about all of the same options as some of the other popular blogging applications built using competing technologies like PHP. My purpose of this entry is not to compare blogging applications, but to present a solution to a dilemma that I had while attempting to integrate BlogEngine.NET with the Module Media site redesign. That is, how do I take my latest blog entries and make them available directly within the front page of my web site so that the user can go directly to the front page of my web site and see whether a new blog entry exists. And if one does, allow them to directly link to that new blog entry. The answer to this problem wasn’t as simple as I had imagined it would be. In the end, I had to resurrect my XSL skills and put my XML and VB.NET skills to the test to get the job done. Let’s take a look.
BlogEngine.NET, like all blogging applications generates a file that is used to syndicate blog entries via RSS, called syndication.axd. This file, which is generated at the root of your blog, can be read in my any feed reader application, including your browser, simply by “subscribing” to it. For instance, if you browse to mine http://www.modulemedia.com/blog/syndication.axd, you’ll see the RSS feed for the Module Media blog. Pretty straight forward right? The question I had was how do I take the top 5 headlines, including their dates from this syndication file and make them available as the latest entries on the main page of the Module Media site? To add to this dilemma, I also wanted to make it so that each entry linked back directly to the blog posting. Since most of the work is done by the syndication.axd file, reading it is simply a matter of writing a XSL file to “transform” the data in the XML-based syndication.axd file into something meaningful that our web page index.aspx can use and ultimately display. I started off with a XSL file in a scripts folder on my site called rssTransform.xsl. Here’s what it looks like:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" />
<xsl:template match="/">
<ul id="lbptext">
<xsl:for-each select="rss/channel/item[position() < 5]">
<li>
<span>
<xsl:call-template name="getDate">
<xsl:with-param name="dateTime" select="pubDate" />
</xsl:call-template>
</span>
<xsl:element name="a">
<xsl:attribute name="href">
<xsl:value-of select="link" />
</xsl:attribute>
<xsl:value-of select="title" />
</xsl:element>
</li>
</xsl:for-each>
</ul>
</xsl:template>
<xsl:template name="getDate">
<xsl:param name="dateTime" />
<xsl:value-of select="substring($dateTime,9,4)" />
<xsl:value-of select="substring($dateTime,6,2)" />,
<xsl:value-of select="substring($dateTime,13,5)" />
</xsl:template>
</xsl:stylesheet>
To make a long and complex file short, the XSL file’s primary responsibility is to take XML data (syndication.axd) and transform it into something that is a bit more meaningful to a browser (HTML). If you look at the file closely, you’ll see actual HTML tags combined with XSL tags. For instance, the portion of code that does the majority of the work is the for-each loop. Essentially what we’re doing is looping through each item in the syndication.axd file. We do this operation five times to read in the top 5 entries. We then display the date (which is formatted by calling a function called getDate written out near the bottom of the page) and a hyperlinked version of the title within a HTML <li> tag. Of course this is possible because all syndication files outline names for each of their entries. Each entry is called “item”, each item has a “title”. Each entry also has a “link” and published “dateTime” amongst others.
With the data now being transformed into something meaningful, it’s now time to associate the XSL file to the syndication.axd (XML) file and more importantly display the data within a the page. This is done using VB.NET on the main page of our web site index.aspx as follows:
<script language="VB" runat="server">
Sub Page_Load(sender As Object, e As EventArgs)
Dim strXmlSrc As String = "http://www.modulemedia.com/blog/syndication.axd"
Dim strXslFile As String = Server.MapPath("scripts/rssTransform.xsl")
Dim myXmlDoc As New XmlDocument()
myXmlDoc.Load(strXmlSrc)
Dim myXslDoc As New XslCompiledTransform()
myXslDoc.Load(strXslFile)
Dim myStringBuilder As StringBuilder = New StringBuilder()
Dim myStringWriter As StringWriter = New StringWriter(myStringBuilder)
myXslDoc.Transform(myXmlDoc, Nothing, myStringWriter)
litModuleMediaRSS.Text = myStringBuilder.ToString()
End Sub
</script>
In order of operation, we read in both syndication.axd and rssTransform.xsl files and set them to string variables called strXmlSrc and strXslFile respectively. We then create a new instance of the XmlDocument() c lass. This gives us access to the Load() method which we use to load up our XML (syndication.axd) file by passing in the strXmlSrc variable as a parameter into the method. We do the same for the XSL file, creating a new instance of the XslCompiledTransform() class and then passing in the strXslFile variable as a parameter into the Load() method of this class.
Next we create new instances of the StringBuilder() and StringWriter() classes, used to format and output programmatically constructed strings. We then call the Transform() method of myXslDoc object variable, passing in the XML document, represented by the myXmlDoc object variable and the instance of the string writer object, myStringWriter. Finally, we set the Text property of a Literal control that I have on the page equal to the string builder object. The final result is formatted using CSS to appear like what you see on the main page of the Module Media site.
I've attached a working version of these files to this entry titled mm_readingrssfiles.zip. Have fun!
Comments:
700 Tags:
asp.net,
xsl,
xml,
rss,
blogengine.net