Introduction
One of the most commonly asked questions at ASPMessageboard.com is along the lines of, "How do I send an email through an ASP page?" The wide array of email FAQs on ASPFAQs.com is also proof of this being a commonly asked question. In this article, we will look at how to send email from an ASP.NET Web page! (For more information about ASP.NET be sure to check out the ASP.NET Article Index.)
In order to send an email from an ASP.NET Web page, you need to use the SmtpMail class, found in the System.Web.Mail namespace, which contains a static method Send. (More on this class later in the article!) In any case, the simplest way to send an email is to call this Send method passing in an instance of the MailMessage class. What's the MailMessage class, you ask? It's a class (also in the System.Web.Mail namespace) that represents an email message.
Creating a MailMessage
The MailMessage class contains properties very similar to those found in CDONTS (the often-used component to send emails from a classic ASP page). Such properties include: To, From, Cc, Bcc, BodyFormat, Subject, Priority, Body, etc. So, to send an email, we should create an instance of the MailMessage class and set its properties.
'Create an instance of the MailMessage class |
Note that you will need to import the System.Web.Mail namespace in your ASP.NET Web page in order to be able to utilize the above code as-is: <% @Import Namespace="System.Web.Mail" %>.
Sending the MailMessage
Once we have a MailMessage class instance with the correct properties set, sending the actual email is a breeze. We simply need to call the static Send method of the SmtpMail class, passing in the MailMessage class instance:
'Now, to send the message, use the Send method of the SmtpMail class |
The SmtpMail class uses the SMTP Service built into Windows 2000 to do the work of actually sending the email message. By using the Send method above, the local SMTP server is used to send the email message. In order to specify a different SMTP mail server to use to send the message, set the SmtpServer property:
SmtpMail.SmtpServer = emailServerName |
Be careful, though. Since this is a static property, changing this value in one ASP.NET Web page will affect all ASP.NET Web pages using sending emails via the SmtpMail object. That is, if in one ASP.NET Web page you set the SmtpServer property to myMailServer, and then, in another ASP.NET Web page, do not specify the SmtpServer property, intending to use the default SMTP server, myMailServer will be used instead. For that reason, you should probably always specify the SmtpServer property - if you want to use the default SMTP server, simply do:
SmtpMail.SmtpServer = "" |
No comments:
Post a Comment