Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

Asp.net send email using c#

Nov 30, 2010
Introduction:

In this article I will explain how to send email using asp.net.

Description:

In realtime we will use gmail,yahoo,hotmail etc to send mails to particular user here I will show to how to implement mail sending concept in asp.net.

To implement mail concept in asp.net first we need to add following reference to our application System.Web.Mail namespace 

What is System.Web.Mail

System.Web.Mail is a namespace which contains classes that enable us to construct and send messages using the CDOSYS (Collaboration Data Objects for Windows 2000) message component. The mail message is delivered either through the SMTP mail service built into Microsoft Windows 2000 or through an arbitrary SMTP server.

How we can get this reference (System.Web.Mail)

We need to add System.web.dll reference to our application for that follow below steps

a                 a)  On the Project menu, click Add Reference.
b)    On the .NET tab, locate System.Web.dll, and then click Select.
c)     Click OK in the Add References.

After that design your aspx page like this


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Send Mail using asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table style=" border:1px solid" align="center">
<tr>
<td colspan="2" align="center">
<b>Send Mail using asp.net</b>
</td>
</tr>
<tr>
<td>
From:
</td>
<td>
<asp:TextBox ID="txtFrom" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Subject:
</td>
<td>
<asp:TextBox ID="txtSubject" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
To:
</td>
<td>
<asp:TextBox ID="txtTo" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td valign="top">
Body:
</td>
<td>
<asp:TextBox ID="txtBody" runat="server" TextMode="MultiLine" Columns="30" Rows="10" ></asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnSubmit" Text="Send" runat="server" onclick="btnSubmit_Click" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Now add following namcespaces in your codebehind


using System.Web.Mail;
After that write the following code in button click


protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
MailMessage Msg = new MailMessage();
// Sender e-mail address.
Msg.From = txtFrom.Text;
// Recipient e-mail address.
Msg.To = txtTo.Text;
Msg.Subject = txtSubject.Text;
Msg.Body = txtBody.Text;
// your remote SMTP server IP.
SmtpMail.SmtpServer = "10.20.72.1";
SmtpMail.Send(Msg);
Msg = null;
Page.RegisterStartupScript("UserMsg", "<script>alert('Mail sent thank you...');if(alert){ window.location='SendMail.aspx';}</script>");
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
}
Here use your SMTP server address then only it will work for you and check mails in spam also because sometimes mails should be appear in spam folder also.

Demo


Download sample code attached






Other related posts are


i hope it helps you

If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

82 comments :

Anonymous said...

hi i used dis code....but its gvng error as "The transport failed to connect to the server."..
wat mistake i have done...
i wrote as it as code...
even im getting error...

Suresh Dasari said...

hi,
that would be problem with smtp server please give your smtp server address don't use the ip address mentioned in code.

poonam said...

wat do u mean by smtp server..???

poonam said...

can u help me in sending an mail for forgot password

Suresh Dasari said...

@poonam
smtp(simple mail transfer protocol) server are the Email servers to exchange the mails.

Suresh Dasari said...

@poonam
To send mail for forgot password get details of user based on UserName or Email then bind Userdetails to body of email and then send mail like as i explained above

poonam said...

can u send me d coding plzzzz......

poonam said...

whch smtp code should v use...???

Debugger said...

SmtpMail.SmtpServer = "assign the smtpserver address here";
Ex :
It would be something like this '50.22.12.227'

For gmail SmtpServer address as below:

SmtpMail.SmtpServer ="smtp.gmail.com"

Anonymous said...

hi i am getting this error
{System.Web.HttpException: Invalid mail attachment 'file123.pdf'.
at System.Web.Mail.MailAttachment.VerifyFile()
at System.Web.Mail.MailAttachment..ctor(String filename, MailEncoding encoding

Mani USS said...

Hai sir,

Pls send the details about smtp server and how we can get the server address from the system

jayesh said...

The server rejected one or more recipient addresses.

Anonymous said...

Hi. how to get my smpt server? idk what should I replace in the IP. Thanks :)

Anuj said...

Dear Sir
I am having different issue,I have to send a web page like "contact us Form" in email body. If the recipient fill that form when he open the mail,then after submitting the detail all the information should go to admin/the mail sender.I am using C# and sql server 2005.
I am looking forward to hearing from you.

Thanks in advance

Rathinamoorthy said...

Hi first of all thanks for ur incredible works! i got my smtp ip address from cmd prmpt window. i used that address. but still i am not receiving the mail. but wen i click the button the page just reloads;.

Suresh Dasari said...

@Rathinamoorthy...
for smtp server your network people will define some address you need to get that address not ip address of server.

ranjan kumar said...

hey sir,
from where should i get the address of smtp server

Suresh Dasari said...

@rajan kumar...
Please check above comments....

Ankit Dwivedi said...

Hii suresh..In.Net tab system.web.dll is not showing so how can i solve it..

Anonymous said...

when i use this codeing the error comes this... plz tell me the solutions sir....

System.Web.HttpException (0x80004005): The transport failed to connect to the server. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Runtime.InteropServices.COMException: 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 bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams) at System.Web.Mail.SmtpMail.LateBoundAccessHelper.CallMethod(Object obj, String methodName, Object[] args) at System.Web.Mail.SmtpMail.LateBoundAccessHelper.CallMethod(Object obj, String methodName, Object[] args) at System.Web.Mail.SmtpMail.CdoSysHelper.Send(MailMessage message) at System.Web.Mail.SmtpMail.Send(MailMessage message) at withoutattachment.btnSubmit_Click(Object sender, EventArgs e)

Suresh Dasari said...

That is the problem with your mail server. Please check whether you given correct smtp server address or not...

soujanya isaka said...

hi i like this but i didn't get system.web.dll in my add reference window y this happend

Dinesh Chauhan said...

Hello Friends, i have replaced SmtpMail.SmtpServer = "155.152.1.20" with my IP Address but still i am not getting mail

Anonymous said...

sir your code is work but not sending a mail to proper addresss can u help???????

Pramod Saini said...

can u send me d coding plzzzz...
pramod2011eng@gmail.com

deepam said...

hai, me using .net 2008 version, i didnt saw the system.web.dll on .net tab, plz help me
some other options are system.data, system.web service etc

Amar Mane said...

can u help me in sending an mail for forgot password

Anonymous said...

very usefull....
can you please upload application for sending SMS in c#?

Shiva Katta said...

i developed application with system.Net.Mail namespace . I heard system.web.Mail is obsolete from .net 3.5. I used code as below .

" Dim smtpclient As New SmtpClient
Dim mailmsg As New MailMessage
Try

Dim frmAddress As New MailAddress(txtFrm.Text, "test")
mailmsg.From = frmAddress
mailmsg.To.Add(txtTo.Text)
mailmsg.Subject = txtSub.Text
mailmsg.Body = txtBody.Text
mailmsg.IsBodyHtml = False
smtpclient.Send(mailmsg)
Response.Write("Sent Mail successfully")
Catch ex As Exception
Response.Write(ex.Message)
End Try" .
In web.config "





" .


I'm able send mail with in my domail and not able to send google, yahoo . What should i do send emails to google,yahoo etc through my web application.

Yogesh Gautam said...

where is database of this example sir ??
will you please let me knw about this

Anonymous said...
This comment has been removed by a blog administrator.
Anonymous said...

If the to mail id its giving wrong

Anonymous said...

Hi sir,

If we gave wrong To mail id then its giving error.
when mail id is wrong it should to from mail id how to do it

Anonymous said...

For all whose having doubt for mail not sent


If we run the programme on local server it will not work(mail will not sent),even if we have internet facility so.
it needs an smtp server to work this code.

thank you..

OM said...

Hi,
i am using framework 4.0
i'm not getting system.web.dll to add reference in my project.

then what i do.plz help me

Shubhanshu Gupta said...

System.Runtime.InteropServices.COMException: At least one of the From or Sender fields is required, and neither was found.

this error is occured .....what should i do...its urgent please help me..

Constructions in madurai said...

it doesnt send any mail..pls help me...

Anonymous said...

Respected Sir,
thank you,but can i sent mail from diffrent mail server for example i host my web on xyz.com and can
i use mail.abc.com as smtp server or not?

there is any requirements to modify web.config file in above code?

Constructions in madurai said...

i got no errors..but it does send any mail..
give me ur email...i send to u

Anonymous said...

h

sravan said...

am getting this error by using smtp.gmail.com
//error
The server rejected the sender address. The server response was: 530 5.7.0 Must issue a STARTTLS command first. zy5sm32051754pbb.43 - gsmtp

Anonymous said...

can u send me the mail inbox code plzzz...

Anonymous said...

hi
system.mail.dll does not exists system.mail exists so will it work

Anonymous said...

Code works properly for me. Good going.

Above users are beginner I think in ASP.NET.

Good going an in future looking for great codes from you.

Anonymous said...

how to send friend request one person to another .
also show friend request notification. and how like comments and sharing comments by differents users and also write comments different user .
this is a social networking project.
plz tell demo with example or send
my answer my email id -rahulpandey.0171@gmail.com

plz reply fast sir . i am waiting your response

Anonymous said...

how to send friend request one person to another .
also show friend request notification. and how like comments and sharing comments by differents users and also write comments different user .
this is a social networking project.
plz tell demo with example or send
my answer my email id -rajverma.0171@gmail.com

plz reply fast sir . i am waiting your response

surendra nath said...

Hai sir can u explain how to send SMS to mobile using C#




Thank you sir,

JAY said...

MailMessage m = new MailMessage();
m.From = new MailAddress("sendingemail@gmail.com");
m.To.Add(new MailAddress("@gmail.com"));
m.Subject = "this is test message ";
m.Body = "your email body";
SmtpClient smtp = new SmtpClient("smtp.gmail.com");
smtp.Port = 587;
smtp.EnableSsl =true;
smtp.UseDefaultCredentials = true;
smtp.Credentials = new System.Net.NetworkCredential("youresendingmail@gmail.com", "yourpassword");
smtp.Send(m);

try this code to sent mail it works

sarvesh muranjan said...

wow!! Thanks Jay, GOD BLESS U.

sarvesh muranjan said...

hey Jay ,Can u explain me the code in details and why port=587?

www.Deve.Devender.blogspot.com said...

How to find SMTP server address

Anonymous said...

smtp.gmail.com

bhupinder said...

Sir can you plz send me the code to send sms to mobile in asp.net i have account on way2sms.

Santhosh Kumar said...

Hi sir
Can you tell how to retreive emails from only inbox and its attachment,the code that i downloaded on google retreive all the mails form all the folders(inbox,sent,thrash...)

anil said...

sir,thanks for your articles on different topics,i want to ask u is it possible to send email using asp.net program developed using file system not http if so tell me how.

mani21 said...

protected void AddRecord(object sender, EventArgs e)
{










float CalculatedQty = Int64.Parse(TextBox4.Text);

float PhysicalQty = Int64.Parse(txt1.Text);
DateTime StTakdt = Convert.ToDateTime(txtdt1.Text);

bal pBAL = new bal();
int intResult = 0;


try
{
intResult = pBAL.Insert5(int.Parse(TextBox5.Text), int.Parse(TextBox2.Text), CalculatedQty, PhysicalQty, StTakdt);

if (intResult > 0)

lbl.Text = "Record Insert Successfully.";

else
lbl.Text = lbl.Text = "AuditID [" + TextBox5.Text + "] alredy exists, try another name";



}

catch (Exception ee)
{


lbl.Text = ee.Message.ToString();

}
finally
{
pBAL = null;

}


gvdetails.EditIndex = -1;
// Refresh the list
BindGrid();

}

i want to throw exception message plz enter detail when click on button without entering any value kindly help me

Anonymous said...

Hello,I am new in this field.I am coping your exact code and also change smtp port no but again this code give me error please help me.
Give me ans as...Pandey baba

anbu johni said...

pls tel how to find my smtp server address

anbu johni said...

pls tel me after running the project just load and stop the execution. cant send the mail i dont know which problem occur pls help me

Tejaswi G said...

how to know SMTP server IP ???

Tejaswi G said...

sir..i hav used same as your code for signup form but values are getting inserted into the database... what could be the problem ???

Anonymous said...

i got errors like


MailMessage' is an ambiguous reference between 'System.Web.Mail.MailMessage' and 'System.Net.Mail.MailMessage'

Source Error:


Line 23: try
Line 24: {
Line 25: MailMessage ms = new MailMessage();
Line 26: ms.From = txtfromemail.Text;
Line 27: ms.Subject = subjecttxt.Text;

Rajesh P said...

after submitting data, i want to send that particular admin using MVC 4.

Hidayt Rahman said...

Is there any option of mail service. without using c#.
i want to use this service without using C# code..
have you any single asp code?

Ezhilarasi G said...

Really great suresh sir !!! it is very useful to us to do our final year projects.then how to find coding for publishing comments like this.? please help me ...

Sravan Kumar said...

EVEN I used my smtp address, it wont work, 1 got exception like" System.Web.HttpException (0x80004005): The message could not be sent to the SMTP server. The transport error code was 0x800ccc67. The server response was 421 Cannot connect to SMTP server 192.168.0.1 (192.168.0.1:25), NB connect error 1460 ---> S
"

Mayank Desai said...

Hi Suresh,
I want to read data from database then create zip file and attaching zip file in email.
My all file data is storing only in database.
Could you please give me some suggestion ?

Anonymous said...

How to send more then one text field using body sir..

Vinay Kumar Gupta said...

Hi ,please help me ,
How to Send Friend Request And also Accept asp.net c#
My Email Id is :- vinay2010patna@gmail.com.
I have got So many Well and nice Coding Implementation on Your Website ,
Thanks for This Technical help

Rama Gopala Krishna Murthy said...

Hello Suresh, i need to talk with u regarding the project.i am krishna from Vijayawada....my number is 970603289......a small requirement from SMTP Email.Reply me fast.

Dheeraj Kumar said...

sir my message is successfully send but i can't see the message in my gmail , i also check the spam in my account still i couldnot found any thing. what would be the problem??

Teja Guntuku said...

can i use in my websie

Anonymous said...

HAI SIR, I DID NOT FIND 'System.Web.dll' IN MY "ADD REFERENCE". CAN YOU PLEASE HELP ME HOW TO ADD TIS???

Daulat Singh said...

hello sir....
firstly....thanks for u ..providing valuable codeine....tip and trick,
i dont know about smtp ip address ?
i m trying to sending mail from my website bt alwys give exception cause....
and your code is not working properly....
so plese help me.


daulat

Daulat Singh said...

how we can get smtp ip address ???

Anonymous said...

how to get port number

aalia lyon said...

It's really nice blog Its helps you to find error and fix them please go through this site and make good solution of your problem.
How To Remove Rundll Error
Thank you
Aalia lyon

balaji said...

On the Project menu, click Add Reference.i dnt knw how to addd this plz tel me yar

Gaurav said...

When i wrote smtp.gmail.com as SmtpServer Name Then error something like this...
"The server rejected the sender address. The server response was: 530 5.7.0 Must issue a STARTTLS command first. sm8sm4484668pbc.92 - gsmtp"

Please Help me

Nevil patel said...
This comment has been removed by a blog administrator.
Dinesh Famara said...

I have this problem when send mail on click button in asp.net using vs 2012 "The transport failed to connect to the server." please help me.......?

Dinesh Famara said...

how to solve Error : "The message could not be sent to the SMTP server. The transport error code was 0x80040217. The server response was not available"

Give your Valuable Comments

Other Related Posts

© 2010-2012 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.