How ASP.NET Sends Mail
One of the most common uses of forms in a website is to send email. Sending email from a website used to be a complex and difficult task, but as with so many other tasks that used to be complex, ASP.NET makes sending email easy.
In this chapter you'll see two different classes from the .NET Framework used to send email with ASP.NET; the System.Net.SmtpClient class and the System.Net.MailMessage class.
The System.Net.SmtpClient Class
The SmtpClient class facilitates the sending of email with the Simple Mail Transfer Protocol or SMTP. The SmtpClient class is used to connect your ASP.NET application to the network (either the Internet or another network) and to authenticate you (if necessary) to the SMTP mail server.
We will use a few properties of the SmtpClient class to connect to the SMTP server on the network:
-
Host Property— The Host property is used to specify the name of the SMTP server to which you are connecting.
-
Port Property— Every connection on a network takes place over a specific channel on the network called a port. SMTP communication takes place on port 25 by default. The Port property defaults to a value of 25, but if your SMTP server requires a different port, you can specify that by using the Port property.
Tip: It's uncommon for an SMTP server to not use port 25. Ask your network administrator, ISP, or hosting company if you're not sure what port your SMTP server uses.
-
Credentials Property— Most SMTP servers require that you provide a username and password or otherwise authenticate yourself before you can send email.
Some SMTP servers (usually on corporate networks) allow you to use the credentials of the account running your ASP.NET code. In those cases, you can specify to use the default credentials, but in this web application, we'll specify a username and password.
The System.Net.MailMessage Class
The MailMessage class (as you've likely guessed) represents the actual message that is sent. The following list shows some of the properties of the MailMessage class, all of which should be self-explanatory:
-
To— The destination email address(es) for the message.
-
From— The email address of the sender.
-
Cc— The email address(es) that appear on the CC line.
-
Bcc— The email address(es) that appear on the BCC line.
-
Subject— The email's subject.
-
Attachments— A list of file attachments included with the email.
-
IsBodyHtml— A Boolean property that specifies whether or not the Body property uses HTML code.
-
Body— The body of the email being sent. This is the actual text of the email message.
After you set the properties of the MailMessage class, you call the Send method and the SmtpClient class is used to send the message.
Modifying the Configuration File for internal Email Settings
In a real-world ASP.NET application, you may be sending email from many pages in your application. If the SMTP properties (such as server name, username, password, and so on) change, it's not efficient to have to make changes on each page that sends email.
Fortunately, many of the properties of the SmtpClient class can be specified in the configuration file for your ASP.NET application. If you specify properties in the configuration file, you have to modify only the configuration file if any of those properties change, and all pages that send email will automatically use the new settings.
Tip: If you specify a setting in your server-side code that's already been specified in your configuration file, the setting that you specify in code overrides the setting in the configuration file.
Adding Email Configuration to the web.config File
Mail configuration is specified in the <system.net> section of the web.config file. The web.config file doesn't contain a <system.net> section by default, so you need to add one.
Open the web application and then open the web.config file in Visual Web Developer. Add the following code to the web.config file directly before the opening <system.web> element:
<system.net>
<mailSettings>
<smtp>
<network host="smtp.yourServer.com"
password="yourPassword"
userName="yourUsername" />
</smtp>
</mailSettings>
</system.net>
Tip: The settings you specify for your SMTP server are often the same settings you use in your email client for the outgoing mail server for your domain. Your hosting company probably has instructions for setting up email clients on their website that you can use to find settings for your configuration file.
Using the Web Site Administration Tool
You can also use the Web Site Administration Tool to configure your SMTP settings. The Web Site Administration Tool enables you to add and edit SMTP settings while minimizing the possibility of errors due to incorrect configuration or typographical errors.
Tip: When using the Web Site Administration Tool to configure SMTP settings, all entries are optional. If you don't provide a value for a required property in the configuration file, you need to provide it in your ASP.NET server-side code.
To use the Web Site Administration Tool to configure your SMTP settings, follow these steps:
1. Open your website and click the ASP.NET Configuration button at the top of the Solution Explorer window
2. Click the Application tab or the Application Configuration link in the Web Site Administration Tool.
3. Click the Configure SMTP Email Settings link on the Application page of the Web Site Administration Tool.
4. Enter your SMTP server name, as shown in Figure 1.
Figure 1. SMTP configuration can be modified on the Application tab of the Web Site Administration Tool.
5. Enter the port if necessary. In most cases, the default value of 25 should not be changed.
6. Enter an email address in the From text box if desired. The email address you enter here will show up as the sender of the email that ASP.NET sends.
7. Select an authentication method. Choose None if your SMTP server doesn't require authentication. Choose Basic if your SMTP server requires authentication that differs from the credentials of the account that your ASP.NET code is using. Choose NTLM if you want to use the credentials of the account running your ASP.NET code.
8. Click Save to save the configuration settings to the web.config file in your application.
After you click Save, the Web Site Administration Tool automatically updates your web.config file with the changes, and they take effect immediately.
What Happens When a Configuration File Is Saved
Every ASP.NET application runs inside a special area set aside in memory called an application domain. The purpose of the application domain is to provide isolation between different ASP.NET applications. The application domain ensures that one ASP.NET application doesn't access protected areas of another ASP.NET application.
When an application domain starts up, ASP.NET reads the information in the configuration file to set up the application domain. It then begins monitoring certain folders and files within the application for any changes. If a change is detected, ASP.NET shuts down the application domain and restarts it again so that any changes will take effect.
When you make a modification to the application's web.config file (whether by directly modifying the file or by modifying it indirectly with a tool such as the Web Site Administration Tool), ASP.NET immediately recycles the application pool so that the new configuration applies immediately to the application.
Sample Code to send Email in Asp.net without ASP.net web.config settings:
try
{
MailMessage msg = new MailMessage();
msg.To.Add(toId);
MailAddress frmAdd = new MailAddress(frmyahoo);
msg.From = frmAdd;
//Check user enter CC address or not
if (ccId != "")
{
msg.CC.Add(ccId);
}
//Check user enter BCC address or not
if (bccId != "")
{
msg.Bcc.Add(bccId);
}
msg.Subject = msgsubject;
//Check for attachment is there
if (FileUpload1.HasFile)
{
msg.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
}
msg.IsBodyHtml = true;
msg.Body = mailContent;
SmtpClient mailClient = new SmtpClient("smtp.mail.yahoo.com", 25);
NetworkCredential NetCrd = new NetworkCredential(frmyahoo, frmpwd);
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = NetCrd;
mailClient.EnableSsl = false;
mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
mailClient.Send(msg);
clear();
Label1.Text = "Mail Sent Successfully";
}
catch (Exception ex)
{
Label1.Text = "Unable to send Mail Please try again later";
}
}
Sample Code to send email in ASP.net with web.config with <mailsettings>
try
{
MailMessage mailMessage = new System.Net.Mail.MailMessage();
mailMessage.To.Add(userEmailAddress);
mailMessage.Subject = "Subject";
mailMessage.Body = "Body Text";
var smtpClient = new SmtpClient();
smtpClient.Send(mailMessage);
return "Mail send successfully";
}
catch (SmtpException ex)
{
return "Mail send failed:" + ex.Message;
}
manual MailSettings for web.config
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="from@yourdomain.com">
<network host="smtp server addresss" userName="username" password="password"
defaultCredentials="false" port="xxx" enableSsl="true" />
</smtp>
</mailSettings>
</system.net>