Working with Email Using ASP.NET 2.0
 
Published: 01 Sep 2006
Unedited - Community Contributed
Abstract
In this article Jason examines the various aspects involved with sending of emails using ASP.NET 2.0.
by Jason N. Gaylord
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 55894/ 44

Introduction

In ASP.NET 1.x sending email was fairly simple.  The only issue was that there were different ways to send email depending on whether the application was web or windows based.  Windows developers used MAPI to send emails using an email client like Outlook.  Web developers used CDOSYS to send rich emails.  Microsoft realized that a change was warranted.  In ASP.NET 2.0 Microsoft released a new set of classes to handle email.  The only issue is that to many developers, sending email became much more complex.  Within this article, we will walk through the changes to the web.config file, the new classes that are available and how to send email using the new MailMessage class.

Examining the Web.config

By now you should be familiar with the system.web section group that is found in the web.config file.  In ASP.NET 2.0 a new group was added that contains configurable sections for the System.Net namespace called the system.net section group.  This group allows email settings to be established by using the mailSettings section group.  Since we are sending emails and not receiving emails, we will use the SMTP protocol.  To define the SMTP settings, we will add the SMTP section group to the mailSettings section group.  The SMTP section group then contains a network section that specifies attributes for the SMTP network settings.  These attributes include host, port, username, and password.  An example of the system.net section group can be found in listing 1.

Listing 1

<system.net>
  <mailSettings>
    <smtp>
      <network host="mail.contoso.com" 
      userName="email@contoso.com" password="password" />
    </smtp>
  </mailSettings>
</system.net>
Accessing the Web.config from Code

To prevent confusion, in ASP.NET 2.0 the System.Web.Mail namespace has been marked deprecated.  All of the classes are still accessible using IntelliSense and will still function properly.  However, they too are marked obsolete.  Instead, a new namespace found at System.Net.Mail should be used.  This new namespace contains classes to manage your mail client and messages.  The SmtpClient class is used to establish a host, port, and network credentials for your SMTP server.  The MailMessage class is similar to the MailMessage class found in the old System.Web.Mail namespace.  This class allows a full email message to be built.  There is also an Attachment class that allows an attachment to be generated so it can later be added to the MailMessage object.  In addition to these three most commonly used classes, you will find that System.Net.Mail contains an AlternateView and LinkedResource class.

Unfortunately, ASP.NET 2.0 does not provide a clean and easy way to access the system.net section group from the web.config file within code.  The SmtpClient object contains a UseDefaultCredentials boolean property, but that specifies whether the SmtpClient object is to use the credentials of the user currently running the application.  Before we begin accessing the attributes in the web.config file, we will need to determine what credentials will be required to connect to the SMTP server and ensure that the values we will use will work.  In many cases, the credentials that would be used to connect to a Microsoft Exchange server would be different than those to connect to many ISP email systems.  In the example to follow we will use a username, password, and hostname.

The first task on our plate is to read the mailSettings section group from the web.config file.  To accomplish this task, we will need to create a new object of type System.Configuration.Configuration.  This object will store our web.config file.  We will assign this new object to the applications web.config by using the OpenWebConfiguration method of the WebConfigurationManager class.  The OpenWebConfiguration method will look for a relative path. We will pass in the HttpContext.Current.Request.ApplicationPath since we will want to load the web.config file for the current application.

The second task is to load the specific section group from the object that contains our web.config file into a new object.  A new object of type System.Net.Configuration.MailSettingsSectionGroup will be created.  This object will be assigned to the mailSettings section in the web.config file.  We will use the GetSectionGroup method of our configuration object to obtain this section.  ASP.NET does not know that the mailSettings section is found under system.net so we must specify the full section group as system.net/mailSettings.  An example of this can be seen in listing 2.

Listing 2

Dim config As System.Configuration.Configuration = _ 
    WebConfigurationManager.OpenWebConfiguration( _
    HttpContext.Current.Request.ApplicationPath)
Dim settings As System.Net.Configuration.MailSettingsSectionGroup = _ 
    CType(config.GetSectionGroup("system.net/mailSettings"), _
    System.Net.Configuration.MailSettingsSectionGroup)
Creating the SMTP Client

A new object of type SmtpClient will be created to act as the SMTP server for mail being sent out.  The SmtpClient object will need to have the network credentials passed into it.  Thus, we will need to create a new object of type System.Net.NetworkCredential and pass in the username and password values from the web.config.  These values can be found by assessing the Smtp.Network.Username and Smtp.Network.Password properties of the settings object defined earlier.  The NetworkCredential object will be assigned to the Credentials property of the SmtpClient object.  The other property we must set is the SmtpClient object's host property.  This too will be assigned a value from the settings object created earlier.  An example of this can be seen in the listing given below.

Listing 3

'Obtain the Network Credentials from the mailSettings section
Dim credential As New System.Net.NetworkCredential( _
    settings.Smtp.Network.UserName, settings.Smtp.Network.Password)
 
'Create the SMTP Client
Dim client As New SmtpClient()
client.Host = settings.Smtp.Network.Host
client.Credentials = credential
Creating a MailMessage Object

The MailMessage object in ASP.NET 2.0 is much more robust than the one found in the CDOSYS libraries in ASP.NET 1.x.  The new MailMessage object still contains all of the common properties that an email message has including To, From, Subject, and Body.  The To and From properties have changed a bit.  The From property is no longer "just a string."  Instead, the From property is of type MailAddress.  The To property is similar in that it is a collection of MailAddress objects.  Since the CC and Bcc properties have the same requirements as the To property, they too are a collection of MailAddress objects.  The MailMessage object contains some additional properties including, but not limited to, AlternateViews, Attachments, BodyEncoding, DeliveryNotificationOptions, IsBodyHtml, Priority, and ReplyTo.

The AlternateViews property allows an alternate view to be specified by passing in either a filename or a stream and assigning a MIME type to the view.  The Attachments property allows attachments to be added to the message.  The BodyEncoding property is a value that can specify the System.Text.Encoding type of the email message.  The DeliveryNotificationOptions property specifies when delivery notifications should be received.  The IsBodyHtml property is a boolean value signifying whether the email's body is HTML or plain text.  The Priority property specifies whether this email is of high, low, or normal importance.  The ReplyTo property is the email address that the reply message would go to.

To send the MailMessage object, the object must be passed into the Send method of the SmtpClient object.  An example of this can be seen in the listing below.

Listing 4

'Build Email Message
Dim email As New MailMessage
email.From = New MailAddress("email@contoso.com")
email.To.Add("steveb@contoso.com")
email.CC.Add("billg@contoso.com")
email.Subject = "Test Email"
email.IsBodyHtml = True
email.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure
email.Body = "<strong>Hello Steve!</strong>"
 
'Send Email
client.Send(email)
Conclusion

As you can see now, sending email in ASP.NET 2.0 is much more complex.  However, it is also much more robust.  Many of the email options that you could not access before without adding an email header to the email message can now be added with properties.  Hopefully the team will continue to enhance this namespace and add additional functionality in the future.



User Comments

Title: Sending email from ASP.NET v2.0 application using SMTp Server   
Name: Rajaraman
Date: 2012-05-23 2:15:32 AM
Comment:
Sending email from ASP.NET v2.0 application using SMTp Server
Title: SP   
Name: SP
Date: 2010-04-16 8:31:14 AM
Comment:
SV TELECOM
" soluções para redução de custo de celulares corporativos "

" OFERTA LIBERTY " APROVEITE !!!!!!!!!!!


Fale Ilimitado com seu grupo e mais 40 milhões de celulares no BRASIL por apenas R$ 19,00.

Temos Pós venda ( auxilia seu atendimento e a manutenção do seu contrato junto a Operadora )

Isenção para deslocamento em Roaming

Diminua o custo da conta de celular de sua empresa em mais de 30%

acesse agora e solicite maiores informações através do nosso site

www.svtelecom.com.br

se desejar não receber mais este informativo, envie REMOVER para svtelecom@svtelecom.com.br
(11) 2741-1098
svtelecom@svtelecom.com.br
Title: How to send to a Email Group   
Name: Abdul
Date: 2009-10-01 2:40:05 PM
Comment:
Hello, any body let me know in asp.net 1.1 , how do you send email to a group name. The group is logical email list. can change an point of time and which is managed in Outlook or Lotus notes etc..
Iam using SmtpMail and send()
Title: email.ReplyTo   
Name: Fathima
Date: 2009-04-16 4:54:21 AM
Comment:
Hello,

I have added email.replyto = new mailaddress("xxx@gmail.com")

Its working perfectly in gmail,yahoo etc.

But in Thunderbird it showing from address as replyto address instead "xxx@gmail.com"

How to solve this issue?

Thanks in advance.
Title: implementing code for email   
Name: sunil
Date: 2009-04-12 10:27:10 PM
Comment:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;

public partial class Student_invite : System.Web.UI.Page
{
const int googleMailPortNumber = 587;
const string username="sunil.ss@gmail.com";
const string password = "9416717917";
protected void Page_Load(object sender, EventArgs e)
{

}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{

MailMessage mail = new MailMessage(username, TextBox2.Text, "Invitation for e-future force.com", TextBox7.Text);
SmtpClient client = new SmtpClient("smtps.gmail.com", googleMailPortNumber);
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Credentials=new System.Net.NetworkCredential(username, password);
client.Send(mail);
Label3.Text = "The invitation has been sent.";
}
}
this is my code to send invitation for using my website

but when i run it then a runtime error occurs: mail sending failure


Please help me to remove this error
Title: dd   
Name: dd
Date: 2009-04-07 5:53:28 AM
Comment:
how send an sms using vb,net
Title: remove name from emails that are sent   
Name: cathy szomolyai
Date: 2009-02-18 3:35:44 PM
Comment:
i want to remove my name from appearing on emails I am sending. how do i do this? where do i go to remove this information?
Title: Reply to "Setting email.From" From Curt   
Name: Sachih Chandrasiri
Date: 2008-11-06 1:13:06 AM
Comment:
There is a very simple way to achieve this.
Please try this and see.
email.From = new MailAddress(MailFrom);

Thanks.
Title: mail is not sending   
Name: avi
Date: 2008-10-21 6:35:57 AM
Comment:
some error occured
Title: Remote Server not available   
Name: George
Date: 2008-09-02 12:01:44 PM
Comment:
Good suggestions and thanks.... But I am getting an error message that the remote server is not available when I try send the mail from Windows 2K server SP4.....
Title: Hello   
Name: Deepa
Date: 2008-08-06 3:07:32 AM
Comment:
i try the code in ASP.NET web form. It sends mail out but did not reach in inbox of given recipients address
Title: Excellent Article   
Name: Rick Gabrielli
Date: 2008-06-24 3:55:23 PM
Comment:
thanks
Title: Domain problem   
Name: konac
Date: 2008-05-20 11:23:28 AM
Comment:
i have a problem. the script only sends emails to domains which reside on my hosting server but not to gmail.com, yahoo.com...please help
Title: smtp settings in web.config   
Name: KarinJ
Date: 2008-05-13 12:47:38 AM
Comment:
Thank you for showing the code on how to get the SMTP stuff from web.config. Most articles don't include that. I have my 'From' email address in the mailSettings section and was stuck on how to retrieve it until I read this article. Thanks again! Karin.
Title: EMAIL RECEIVEING IN HTML FORMAT   
Name: rohit Shrivastava
Date: 2008-04-23 1:30:49 AM
Comment:
Hi
Can any one tell me how i can receive and view the mail which is in HTML format..
I am not-concern in sending HTML mail .. I am concern in only receiveing the HTML format mail.
Can any one tell me how i can do this. its urgent

Thanks
Title: Hi   
Name: Welly
Date: 2008-04-17 11:41:36 PM
Comment:
Can I send email into a POP3 email server using ASP.NET 2.0?
Title: Answere: Working with Email...   
Name: RiZk
Date: 2008-03-31 2:25:12 PM
Comment:
The MailMessage To property is a collection, use Add!
mail.To.Add("email@mymail.com")
Title: Working with Email Using ASP.NET 2.0   
Name: vineeth
Date: 2008-03-24 4:06:55 AM
Comment:
how to send more than one mail at a time?
Title: Sending email from ASP.NET v2.0 application using SMTp Server   
Name: Rajaraman
Date: 2008-03-20 5:04:24 AM
Comment:
Sending email from ASP.NET v2.0 application using SMTp Server
Title: find   
Name: pallav
Date: 2008-01-30 7:23:01 AM
Comment:
it's gr8t

thanks
Title: Sending email from ASP.NET v1.1 application using Gmail SMTp Server   
Name: Sethupathy
Date: 2008-01-11 4:42:14 AM
Comment:
Sending email from ASP.NET v1.1 using Gmail SMTP Server:

MailMessage mail = new MailMessage();

mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1;
mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = "username@gmail.com";
mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = "password";
mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = "465";
mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"]= "True";

mail.From = "asfa@asdf.com";
mail.To = "asfa@asdf.com";

mail.Subject = "Sample" mail.BodyFormat = MailFormat.Html;
mail.Body = "Sample"
SmtpMail.SmtpServer = "smtp.gmail.com";

SmtpMail.Send(mail);
Title: send emails to group of people   
Name: Malakool
Date: 2007-11-10 1:13:53 AM
Comment:
Hi,

i want to sent emails or newsletter in group wise plz help me for that
Title: Error Sys.WebForm.PageRequestManagerServerErrorException   
Name: kumaraatish
Date: 2007-07-17 6:32:02 AM
Comment:
Hi, I am using c# asp.net 2.0 for this purpose...
Now i have a problem. my code mails the specific email address only when i am in debud mode....that is if i upload the site on a server, it gives an error..
Sys.WebForm.PageRequestManagerServerErrorException
How do i do this? what is the flaw?
Title: Very good   
Name: Yahsaar
Date: 2007-07-15 2:39:58 PM
Comment:
very very nice
Title: hi   
Name: sumanth
Date: 2007-07-04 1:57:35 AM
Comment:
can you do this by using C# codes coz now a days almost all companies are using C# languages not only this article. All articles from ASP ALLIANCE
Title: tovario solutions   
Name: thomas freeman
Date: 2007-06-24 1:37:41 PM
Comment:
very clear step by step directions.... could have done a better job myself
Title: clairest abicale im reed   
Name: Raja
Date: 2007-06-19 1:30:19 PM
Comment:
Thankjous for mooking these abicale vevy clear. I overstand it weal. Goud Wok!!
Title: how to avoid the messages to be spam   
Name: Mohan Raja
Date: 2007-06-10 9:19:33 AM
Comment:
Hai plz help me, I am sending Bulk Mail using asp.net1.1. when i send the single message to all receiptants, the messages are stored in bulk folder in yahoo domain. Other id's are not received the message. Plz help me how to rectify it...
My code is...
message.From = "mohanraja1983@gmail.com"
message.To = toAddress
message.Subject = TextBox1.Text
message.Body = TextBox2.Text
message.Priority = MailPriority.High
message.BodyFormat = MailFormat.Html
'SmtpMail.SmtpServer = "192.168.1.254"
SmtpMail.SmtpServer = "127.0.0.1"
SmtpMail.Send(message)
Title: how to change the oulook address   
Name: sudheer
Date: 2007-06-07 7:50:17 AM
Comment:
actually this is good article.this is very useful to me.
but i have some other quereys about this article.
1) i am placed one button control and one one textbox control.if i want change the outlook address at that time i am place the email address into the textbox whenever i am click the button that time the outlook To address is dynamically change how is it possible please send the code for this problem into boddapati.sudheer@gmail.com
Title: Great explain   
Name: Cemal Safi
Date: 2007-05-29 4:32:38 AM
Comment:
Avcikahvesi.Com - That is the greatest explain i have ever seen. thank you for everything :)
Title: Error msg   
Name: Udana
Date: 2007-05-07 2:53:36 AM
Comment:
whan i run the app i get a msg as" smtpEception was unhandled by user code" (im new to this asp.net)... have u got anything to say
Title: perferct way to make it understood   
Name: Renu singal
Date: 2007-04-05 4:15:39 AM
Comment:
thnaks , for amking my concept clear abt this .
Title: Great Article   
Name: SuperbDotNetDeveloper
Date: 2007-03-28 7:46:14 AM
Comment:
Hi Jason

Finally a decent article were someone actually knows what they are on about!
I’m a classic ASP developer so still quite new to the ASP.NET technology and I must say “I’m really enjoying ASP.Net”. So for this sending mail with ASP.NET has been really confusing because in ASP we used CDONTS.NewMail (yeah I know that’s really old school). So yeah thanks, the article has been very helpful.

Thanks

MFB
Title: to hardcode or not to hardcode   
Name: McGuire
Date: 2007-02-05 2:09:58 PM
Comment:
Curt - to not have to hardcode the email address create a variable to capture the email address. for example:
Dim strEmail As String = txtEmail.Text
msg.To.Add(strEmail)
Title: How To send Group mail   
Name: Dhaksh
Date: 2007-01-29 11:53:38 PM
Comment:
How to Send a Group mail for example yahoo groups like that.
I want to send a Group mail using outlook can anyone give me a suggestion.Please Reply me at dhaksh@gmail.com.
Title: Excellant explaination. thanks. but i cant sent to yahoo id   
Name: Gowsi
Date: 2007-01-22 2:09:53 AM
Comment:
Excellant explaination. thanks. but i cant sent to yahoo id.
can u tell me why. plz send response to this id: gowsi32@yahoo.co.in
Title: Setting email.From   
Name: Curt
Date: 2007-01-09 7:08:22 PM
Comment:
How do you set the value of email.From without having to hardcode the address?

I've tried the following and it won't accept the email.From = MailFrom:
Dim MailFrom As String
MailFrom = Request.Form.Item("from")
email.From = MailFrom

I've tried the following but it says that the Address property is read-only:
email.From.Address = MailFrom

Any suggestions? I've spend all day today just trying to migrate my ASP code to ASP.NET 2.0 for simply sending emails. This migration has consumed my life. I've never experienced anything more user-hostile than ASP.NET 2.0.
Title: n how to send emails using asp.net 2.0 version   
Name: DotNetSpace
Date: 2006-12-05 9:15:14 PM
Comment:
Very simple example on how to send emails using asp.net 2.0 with C#.

http://www.dotnetspace.com/articles/general-articles/sending-emails.html

the code example works for asp.net 2.0 version.
Title: Got problem when sending email to Yahoo or Gmail!   
Name: Ky Thanh Pham
Date: 2006-11-04 12:26:53 PM
Comment:
I did follow your tutorial but when I send email to Yahoo or Gmail account, I got this error message: Mailbox unavailable. The server response was: Requested action not taken: mailbox unavailable.
Could you tell me why?
Title: Specify more than one SMTP server   
Name: Veselina Radeva
Date: 2006-10-02 4:17:50 AM
Comment:
Thanks for this article, it works fine for me till now.
I need to specify more than one SMTP server. In case the first one specifies cannot send the email, the second one must be used.

Does anybody have an idea if this is possible?
Title: simple and Clean   
Name: soft tester
Date: 2006-09-11 2:36:23 AM
Comment:
This article is very simple to read and easy to understand how to send e-mail with advanced features using asp.net 2.0

Great

Thanks
Soft Tester[Always have mentality for testing any kind of software instead of using it]
Title: Asp.net 2.0: i can not send mail via google pop3 account   
Name: hoangchau
Date: 2006-09-11 1:06:04 AM
Comment:
In asp.net 1.1 i's easy to send mail via gmail account by change port and ssl param, but 2.0 i can't do that.
to change port and ssl pram in asp.net 1.1:
Dim objMail As New MailMessage
....
objMail.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = [newport]
objMail.Fields("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
....
Title: No need for all that code in section 3   
Name: Rob Teegarden
Date: 2006-09-09 11:14:35 AM
Comment:
Good article, however for section 3 this is all you need:

Dim client As SmtpClient = New SmtpClient()

The settings will automatically get picked up from the web.config
Title: Good   
Name: vp
Date: 2006-09-08 9:03:14 AM
Comment:
Really useful
Title: article feedback did not include the url   
Name: DotNetManiac
Date: 2006-09-07 6:40:31 AM
Comment:
so i put it in the comments...

http://www.dotnetmaniac.com/ArticleViewer.aspx?Key={fc57945a-a859-4015-88d6-16938b829b74}
Title: Sending mail with windows forms 2.0   
Name: DotNetManiac
Date: 2006-09-07 6:39:26 AM
Comment:
great article for beginners sending mail with asp.net. I have an example using windows forms at this url.
Title: Simple and good Article for sending mail   
Name: Vikram Lakhotia
Date: 2006-09-07 4:08:20 AM
Comment:
This is good and simple article for sending mail. But we can do many more complicated stuff in asp.net 2.0 with the smpt namespace

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-03-28 9:40:55 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search