E-mail is often a standard part of Web-based applications. You may use it to send logon information to users or even to send error messages to application administrators.

ASP.NET makes it easy to utilise e-mail in an application with the System.Web.Mail namespace. Let's take a closer look at putting this namespace to work in your applications.

System.Web.Mail namespace
The Microsoft documentation provides a good overview of the System.Web.Mail namespace. It's composed of classes that allow you to create and send messages using the Collaboration Data Objects for Windows 2000 (CDOSYS) message component. The actual message may be delivered via the SMTP (Simple Mail Transfer Protocol) mail service built into Microsoft Windows 2000 and beyond or through an arbitrary SMTP server. The classes in this namespace aren't restricted to an ASP.NET application.

The namespace includes three classes:

  • MailAttachment: Provides properties and methods for constructing an e-mail attachment.
  • MailMessage: Provides properties and methods for constructing an e-mail message.
  • SmtpMail: Provides properties and methods for sending messages using the CDOSYS message component.

MailAttachment class
The basic approach is the creation of a MailMessage object followed by sending it on its way via a SmtpMail object. The MailMessage class contains numerous methods and properties for working with an e-mail message. Properties such as From, Subject, and Body provide everything you need to create an e-mail message, but a SmtpMail object is still necessary for sending it on its way.

SmtpMail class
The SmtpMail class includes the SmtpServer property that gets or sets the name of the SMTP relay mail server to use to send messages, and the Send method actually sends the message. The Send method is overloaded. It allows a message to send using two approaches:

A MailMessage object is passed to the SmtpServer object. Four string objects may be passed to the SmtpServer object with the first being the From field followed by the Recipient, Subject, and the message's Body.

You'll use the MailAttachment and SmtpMail classes together to create the necessary messages in your application, but make sure the Web server is properly configured to send a message via SMTP. Since IIS (Internet Information Services) is the most popular platform for ASP.NET applications, go ahead and use both the IIS and SMTP services to send messages from your application.

Using SMTP with IIS
You can set up both IIS and SMTP services via the Windows control panel. The SMTP service's role is to accept and deliver the messages using the server's configuration. It may deliver the messages directly, or utilise a smart host to deliver the message instead. When a smart host is enlisted, all messages are forwarded to it for delivery.

A little more information is appropriate for debugging. The SMTP service uses a directory structure to contain messages prior to delivery with the default directory being C:\Inetpub\mailroot. It contains numerous subdirectories including Queue, Drop, and Badmail. If you're unable to configure your instance of the SMTP Service for delivery, you can find the message in an EML file in the Queue subdirectory. The Badmail directory contains messages that that couldn't be delivered. Now, let's take a look at sending mail messages from your code.

Sending e-mail messages
To compose an e-mail message in your code, you need to start by creating an instance of the MailMessage class, as shown in the following C# snippet:

MailMessage msg = new MailMessage();

Be sure to include the System.Web.Mail namespace in your code:

using System.Web.Mail;

Once the object is instantiated, the various properties of the MailMessage class are used per your application. The following lines set the recipient, sender, and subject of the message:

msg.To = "test@test.com";
msg.From = "me@test.com";
msg.Subject = "Test Message";

The next step is setting our mail server via the SmtpServer object's SmtpServer property:

SmtpMail.SmtpServer = "smtp server name or address";

The final step is sending the message by passing our MailMessage object to the SmtpMail object's Send method:

SmtpMail.Send(msg);

The previous code used C#. Here's a more complete listing via a Web form's Page_Load event coded in VB.NET:

Notice a try/catch block is used to catch any exceptions raised during e-mail message composition. The equivalent C# code follows:

A straightforward approach to e-mail
The .NET platform makes the task of sending e-mail messages easier. The System.Web.Mail namespace includes everything necessary to send these messages--that is, except the actual SMTP server.

You must set up an SMTP server on the application's host box, or you must redirect it to the appropriate address. IIS provides one approach with its SMTP add-on service, allowing an SMTP server to be set up to handle the messages or to utilise a smarthost indicating what server will handle the processing.

Comments

1

Nahed - 11/04/05

hi i need to making sending and receiving mail in my application and am stuck nothing is working with me so if u can help me plz and 10x alot

» Report offensive content

2

vinayagam - 31/05/05

hi , i am using the above example code and set the servername "smtp.yahoo.co.uk " and from ,to email address . but doesn't work .i got the follwing error Msg .so plz give me the solution to solve this problem
HTTP Error: System.Web.HttpException: Could not access 'CDO.Message' object. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Runtime.InteropServices.COMException (0x80040213): The transport failed to connect to the server. --- End of inner exception stack trace --- at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters) at System.RuntimeType.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters) at System.Type.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args) at System.Web.Mail.LateBoundAccessHelper.CallMethod(Type type, Object obj, String methodName, Object[] args) at System.Web.Mail.LateBoundAccessHelper.CallMethod(Object obj, String methodName, Object[] args) --- End of inner exception stack trace --- at System.Web.Mail.LateBoundAccessHelper.CallMethod(Object obj, String methodName, Object[] args) at System.Web.Mail.CdoSysHelper.Send(MailMessage message) at System.Web.Mail.SmtpMail.Send(MailMessage message) at sample1.WebForm2.Page_Load(Object sender, EventArgs e) in c:\inetpub\wwwroot\sample1\webform2.aspx.cs:line 31

» Report offensive content

3

ravindarreddy - 08/08/05

Hi This RavindarReddy,a programmer From Hyderbad

my problem:iam sending mail from my application but it's getting error like this:

Error: System.Web.HttpException: Could not access 'CDO.Message' object. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Runtime.InteropServices.COMException (0x80040213): The transport failed to connect to the server. --- End of inner exception stack trace --- at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters) at System.RuntimeType.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters) at System.Type.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args) at System.Web.Mail.LateBoundAccessHelper.CallMethod(Type type, Object obj, String methodName, Object[] args) at System.Web.Mail.LateBoundAccessHelper.CallMethod(Object obj, String methodName, Object[] args) --- End of inner exception stack trace --- at System.Web.Mail.LateBoundAccessHelper.CallMethod(Object obj, String methodName, Object[] args) at System.Web.Mail.CdoSysHelper.Send(MailMessage message) at System.Web.Mail.SmtpMail.Send(MailMessage message) at WebApplication4.viewpostreq.btnsubmit_Click(Object sender, EventArgs e) in C:\Inetpub\wwwroot\WebApplication4\viewpostreq.aspx.vb:line 91

» Report offensive content

4

Nilesh Thakur - 16/09/05

Hi
i am use the code you provided, in my application. it work fine but i want to know that what is the "smtp server name or Address" why it

SmtpMail.SmtpServer="smtp server name or address";


is reqired with example can you send me this information ??

Regards,
Nilesh Thakur.

» Report offensive content

5

sriraghavan - 22/10/05

I am a beginner in sending and receiving mail using asp.net. Well can u plz tell me how to find out the name of the smpt mail server
What to set for SmptMail.SmtpServer = ?
Plz help me

» Report offensive content

6

Sterling W. Camden - 01/11/05

When using the Yahoo smtp server, we have run into the same error message that a couple of the other respondents noted (cannot access CDO.Message object). We think it may be because Yahoo wants authentication on the connection, but we aren't sure. We changed over to using the default SMTP server provided in IIS, and that works fine. Don't set the SmtpServer property, and make sure that the local IIS SMTP server allows relaying.

» Report offensive content

7

Rajat - 01/12/05

hi,
thx for the code but i have a confusion.
can we send mail to diffrent domain also. in my application its not working.

» Report offensive content

8

Chris - 05/12/05

Can i set a different address for bounce backs ion this component

» Report offensive content

9

sameer - 07/12/05

hi
i need to test my application and want the mail not to be fired Actually and should remain in the queue folder.
how wil i have to change the smtp configuration.

» Report offensive content

10

sameer - 07/12/05

hi
i need to test my application and want the mail not to be fired Actually and should remain in the queue folder.
how wil i have to change the smtp configuration.

» Report offensive content

11

Sudhan - 20/12/05

when i am trying to run the code given bellow i find cannot access CDO.Message can any one say the solution in this mail id jr.suthan@gmail.com

» Report offensive content

12

rajesh - 15/09/06

What if the mail-message is Undelivered or Bounce can i get any notification abt it.
Please tell me if you have any idea.

» Report offensive content

13

sunil - 18/10/06

Hi all,
I have created application in ASP.Net using c#. The application is working well on my local machine. But when I deploy it on QA server I Gives me following error.

Could not access 'CDO.Message' object.
-----------------------------------------------------------
at System.Web.Mail.LateBoundAccessHelper.CallMethod(Object obj, String methodName, Object[] args)
at System.Web.Mail.CdoSysHelper.Send(MailMessage message)
at System.Web.Mail.SmtpMail.Send(MailMessage message)
at GetOtis.ContactUs.btnsendMail_ServerClick(Object sender, EventArgs e)
-----------------------------------------------------------

Please suggest solution.
Thanks in advance.

			string body = ConfigureMessage();
string name = txtName.Text;

MailMessage message = new MailMessage();

message.Body = body;
message.From = name + "<"+txtEmailId.Text.Trim()+">";

message.To = System.Configuration.ConfigurationSettings.AppSettings["ToString"].Trim();
message.Cc = System.Configuration.ConfigurationSettings.AppSettings["CcString"].Trim();
message.Subject = "GETOtis query / Suggestion";


message.BodyEncoding = Encoding.UTF8;
message.BodyFormat = MailFormat.Text;
message.Priority = MailPriority.Normal;

try
{
SmtpMail.SmtpServer = "";
SmtpMail.Send(message);

txtError.Text = "mail has been sent successfully";
txtQuery.Text = "";
}
catch(System.Web.HttpException ex)
{
//throw new HttpException("check Smtp Server Configuration OR Destination address : Contact GETOtis", ex);
if(Session["UserId"]== null)
Server.Transfer("Login.aspx");
else
{
string messageEx = ex.Message + "-- " + ex.StackTrace;
txtError.Text = messageEx;
}
}

» Report offensive content

14

shabnam khan - 11/12/06

I want to convert this code to asp.net
It is in asp

<!-- #INCLUDE FILE="HeaderLoginPage.asp" -->
<HTML>
<HEAD></HEAD>
<BODY>
<form method="POST">
<p> <b><font color="#7264B0"> <img border="0" src="images/mail.gif" width="32" height="27"> Emails for UPM User Request Action </font><font color="#787EC9">.

» Report offensive content

15

Anil - 12/01/07

hello Sir/madam,

i want to extract the data from the E-mail attachment..if u have any solution please help me..

Thank you

» Report offensive content

16

Sunitha - 02/02/07

Hi
I want to know how to trace the undelivered messages using smtp in vb.net.The undelivered is not being stored in bad mail folder of the mailroot folder.
Plz do help me as soon as possible.

regards,
Sunitha

» Report offensive content

17

nit - 03/02/07

solved my problem thanx

» Report offensive content

18

Ripen - 22/02/07

hi all, can any body tell me how should i come to know that my e mail tha i hav sent is bounced and how to handles or update my database that ..this user or email Id is bounced..I have to do all this in the asp.net using C# ....by the way i could find that the mail i sent is whether red or not but i dont hav idea how to find the bounced mail..........please give idead about this things....thank you all in advanced ..please reply soon its very very very urgent...............Ripen

» Report offensive content

19

Nice - 24/02/07

I am getting this error



StackTrace " at System.Web.Mail.CdoSysHelper.Send(MailMessage message)
at System.Web.Mail.SmtpMail.Send(MailMessage message)
at RealEstate._Default.btnEmail_Click(Object sender, EventArgs e) in D:\Projects\Real Estate\RealEstate\Default.aspx.vb:line 99" String


please help me/
Please find code below.

Dim eMail As New System.Web.Mail.MailMessage
Dim smtpServer As System.Web.Mail.SmtpMail
Try
With eMail
.To = "nicebrilliant@gmail.com"
'.Body = "test Body"
.Body = "Body - Test Mail"
.Subject = "test mail"
.BodyFormat = Mail.MailFormat.Html
End With
With smtpServer
.SmtpServer = "smtp server address"
.Send(eMail)
End With
Catch ex As Exception
Response.Write(ex.ToString)
Finally
End Try

» Report offensive content

20

e.sumilang - 08/06/07

is used this code and it work! the problem is the enail will not sent and it stock to queue folder!

» Report offensive content

21

Ajay Yadav - 04/08/07

When we click on Button for send mail then generate Runtime error
if comment on smtpserver then no error generate but mail is not send

<% @import Namespace="System.net" %>
<% @Import Namespace="System.Web.Mail" %>
<% @import Namespace="System.IO" %>
<script language="vb" runat="server">

Sub btnSendFeedback_Click(sender as Object, e as EventArgs)


Dim objMM as New MailMessage()

'Dim emailServerName As String = "127.0.0.1"

objMM.To = "ajayb@saamarth.com"
objMM.From = txtEmail.Text


objMM.BodyFormat = MailFormat.Text

objMM.Priority = MailPriority.Normal


objMM.Subject = "saamarth.com - Check"


objMM.Body = "At " + DateTime.Now + " This was sent from an ASP.NET " & _
"Web page. " & _
"send by " & txtName.Text & "." & vbCrLf & vbCrLf & _
"---------------------------------------" & vbCrLf & vbCrLf & _
txtMessage.Text & vbCrLf



SmtpMail.SmtpServer =""
smtpMail.Send(objMM)
'server=mail.etgdirect.com
panelSendEmail.Visible =false
panelMailSent.Visible =true
End Sub

</script>

<html>
<body>
<asp:panel id="panelSendEmail" runat="server">
<form runat="server">


<b>Your Name:</b>
<asp:textbox id="txtName" runat="server" />
<br>

<b>Your Email Address:</b>
<asp:textbox id="txtEmail" runat="server" />
<p>

<b>Your Message:</b><br>
<asp:textbox id="txtMessage" TextMode="MultiLine"
Columns="40" Rows="10" runat="server" />
<p>


<asp:button runat="server" id="btnSendFeedback" Text="Send Feedback!"
OnClick="btnSendFeedback_Click" />
</form>
</asp:panel>


<asp:panel id="panelMailSent" runat="server" Visible="False">
An email has been sent to the email address you specified. Thanks!
</asp:panel>
</body>
</html>

» Report offensive content

22

Ajay Yadav - 04/08/07

When we click on Button for send mail then generate Runtime error
if comment on smtpserver then no error generate but mail is not send

<% @import Namespace="System.net" %>
<% @Import Namespace="System.Web.Mail" %>
<% @import Namespace="System.IO" %>
<script language="vb" runat="server">

Sub btnSendFeedback_Click(sender as Object, e as EventArgs)


Dim objMM as New MailMessage()

'Dim emailServerName As String = "127.0.0.1"

objMM.To = "ajayb@saamarth.com"
objMM.From = txtEmail.Text


objMM.BodyFormat = MailFormat.Text

objMM.Priority = MailPriority.Normal


objMM.Subject = "saamarth.com - Check"


objMM.Body = "At " + DateTime.Now + " This was sent from an ASP.NET " & _
"Web page. " & _
"send by " & txtName.Text & "." & vbCrLf & vbCrLf & _
"---------------------------------------" & vbCrLf & vbCrLf & _
txtMessage.Text & vbCrLf



SmtpMail.SmtpServer =""
smtpMail.Send(objMM)
'server=mail.etgdirect.com
panelSendEmail.Visible =false
panelMailSent.Visible =true
End Sub

</script>

<html>
<body>
<asp:panel id="panelSendEmail" runat="server">
<form runat="server">


<b>Your Name:</b>
<asp:textbox id="txtName" runat="server" />
<br>

<b>Your Email Address:</b>
<asp:textbox id="txtEmail" runat="server" />
<p>

<b>Your Message:</b><br>
<asp:textbox id="txtMessage" TextMode="MultiLine"
Columns="40" Rows="10" runat="server" />
<p>


<asp:button runat="server" id="btnSendFeedback" Text="Send Feedback!"
OnClick="btnSendFeedback_Click" />
</form>
</asp:panel>


<asp:panel id="panelMailSent" runat="server" Visible="False">
An email has been sent to the email address you specified. Thanks!
</asp:panel>
</body>
</html>

» Report offensive content

23

Senthilkumar N - 08/08/07

I need to find bounce email in ASP.NET using c#, how can i do?

» Report offensive content

24

Senthilkumar N - 08/08/07

I need to find bounce email in ASP.NET using c#, how can i do?

» Report offensive content

25

VARINDER SINGH - 08/08/07

i am a beginner in seding and recieving mails using asp.net. Plaese suggest me the shortest and right way of doing this

» Report offensive content

26

VARINDER SINGH - 08/08/07

i am a beginner in seding and recieving mails using asp.net. Plaese suggest me the shortest and right way of doing this

» Report offensive content

27

BRAHMAM - 28/03/08

about mail sending to smtp server

» Report offensive content

28

BRAHMAM - 28/03/08

about mail sending to smtp server

ghfh

» Report offensive content

29

imtiyaz - 06/05/08

it to god for me and my fellow

» Report offensive content

30

alexia - 24/05/08

i want to get ba new computer

to good luck

» Report offensive content

31

gopal 03/10/08 - 03/10/08

hai i want to convert asp code into asp.net

<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"

myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.TextBody="This is a message."

myMail.Send
set myMail=nothing
%>
this is an asp code please tell how to convert it into asp.net

» Report offensive content

Leave a comment

You must read and type the 6 chars within 0..9 and A..F

* indicates mandatory fields.

31

gopal 03/10/08 - 10/03/08

hai i want to convert asp code into asp.net <% Set myMail=CreateObject("CDO.Message") myMail.Subject="Sending email with CDO" myMail.From="mymail@mydomain.com" myMail.To="someone@somedomain.com" myMail.TextBody="This is a message." myMail.Send set myMail=nothing %> this is an asp ... more

30

alexia - 24/05/08

i want to get ba new computer to good luck ... more

29

imtiyaz - 05/06/08

it to god for me and my fellow ... more

Log in


Sign up | Forgot your password?

  • Staff Microsoft prescribes more REST

    Details have begun to emerge about the next versions of Visual Studio and Windows Server this week -- and the message from Redmond is to REST up Read more »

    -- posted by Staff

  • Chris Duckett .NET looks to REST

    With news that REST will play a big part in the next version of the .NET Framework, it is timely to take a look at ADO.NET. Read more »

    -- posted by Chris Duckett

  • Renai LeMay Spellr.us needs a new dictionary

    One of the only Australian start-ups to present at the recent round of conferences in the US was Sydney-based spellr.us, which has launched a Web-based tool to check and monitor websites for spelling mistakes. Read more »

    -- posted by Renai LeMay

Most popular tags

What's on?