Create new account I forgot my password    

Sending Email In ASP.NET 2.0
Rating: 38 user(s) have rated this article Average rating: 4.0
Posted by: Suprotim Agarwal, on 7/26/2007, in category "ASP.NET 2.0 & 3.5"
Views: this article has been read 64105 times
Abstract: Sending email's from web applications is a very common requirement in most projects. This article explores how to send Emails in ASP.NET 2.0 with attachments.

Sending Email In ASP.NET 2.0
In ASP.NET, sending emails has become simpler. The classes required to send an email are contained in the System.Net.Mail. The steps required to send an email from ASP.NET are as follows :
Step 1: Declare the System.Net.Mail namespace
C# - using System.Net.Mail;
VB.NET - Imports System.Net.Mail
Step 2: Create a MailMessage object. This class contains the actual message you want to send. There are four overloaded constructors provided in this class. We will be using
C# - public MailMessage ( string from, string to, string subject, string body )
VB.NET - public MailMessage (String From, String to, String subject, String body)
The constructor of this MailMessage class is used to specify the sender email, receiver email, subject, body.
C#
MailMessage message = new MailMessage            ("abc@somedomain.com","administrator@anotherdomain.com","Testing","This is a test mail");
VB.NET
Dim message As MailMessage = New MailMessage ("abc@somedomain.com","administrator@anotherdomain.com","Testing","This is a test mail")
                   
Step 3: To add an attachment to the message, use the Attachment class.
 
C#
string fileAttach = Server.MapPath("myEmails") + "\\Mypic.jpg";
Attachment attach = new Attachment(fileAttach);
message.Attachments.Add(attach);
VB.NET
Dim fileAttach As String = Server.MapPath("myEmails") & "\Mypic.jpg"

Dim attach As Attachment = New Attachment(fileAttach) message.Attachments.Add(attach)

Step 4:After creating a message, use the SmtpClient to send the email to the specified SMTP server. I will be using ‘localhost’ as the SMTP server.

 
C#
SmtpClient client = new SmtpClient("localhost");
client.Send(message);
 
Additionally, if required, you
 
client.Timeout = 500;
// Pass the credentials if the server requires the client to authenticate before it will send e-mail on the client's behalf.
client.Credentials = CredentialCache.DefaultNetworkCredentials;
VB.NET
Dim client As SmtpClient = New SmtpClient("localhost")

client.Send(message)

Additionally, if required, you client.Timeout = 500

' Pass the credentials if the server requires the client to authenticate before it will send e-mail on the client's behalf.

client.Credentials = CredentialCache.DefaultNetworkCredentials 

That’s it. It’s that simple.
To configure SMTP configuration data for ASP.NET, you would add the following tags to your web.config file.
 
 <system.net>
    <mailSettings>
      <smtp from="abc@somedomain.com">
        <network host="somesmtpserver" port="25" userName="name" password="pass" defaultCredentials="true" />
      </smtp>
    </mailSettings>
 </system.net>
 
References :
 
Conclusion:
 
In this short article, we explored how easy it is to send Email’s with attachments using the classes in System.Net.Mail. This approach of sending mails will remain the same for web as well as windows application.
 









Page copy protected against web site content infringement by Copyscape


How would you rate this article?

User Feedback
Comment posted by pranav yesane on Tuesday, November 13, 2007 2:25 AM
i am happy with steps that you mentioned i will be more happy if you declar code with VB .net also
Comment posted by Suprotim Agarwal on Thursday, November 15, 2007 8:25 AM
Dear pranav,
The code is now in vb.net
Comment posted by Nickolaos on Friday, November 16, 2007 11:46 AM
   Very useful article.
I need some additional explanations about Step 1 :
- I don't know how to declare namespase
- I don't know where in the application that Step1 takes place
I'm not a programmer I can only read and modify a code .
Can you point me  out the right place to add or modify the code.
   Step 4 says :
To configure SMTP configuration data for ASP.NET, you would add the following tags to your web.config file.
<system.net>
    <mailSettings>
      <smtpfrom="abc@somedomain.com">
        <networkhost="somesmtpserver"port="25"userName="name"password="pass"defaultCredentials="true" />
      </smtp>
    </mailSettings>
</system.net>


   My hosting company wants me to use port 8025 instead of port 25 therefore that particular part from my web.config looks like that:


**** Edited by admin ****
Please do not provide username and passwords to avoid being
hacked.
Comment posted by Suprotim Agarwal on Saturday, November 17, 2007 12:43 AM
Every program that you write in .NET comes with a default namespace. Do for eg: if you have created a file called Default.aspx with code behind, check the Default.aspx.cs or .vb. You will find in the top most sections some using(C#) or Import(vb.net) statements that declare namespace.

You can use the port number the hosting company suggests you to use. I do not see much of a problem in that.

Later in the day, I will try and create an example for you and post the code file over here.

Comment posted by hi on Wednesday, January 09, 2008 5:35 AM
hi
Comment posted by fsdf on Thursday, March 20, 2008 7:53 AM
dfsdfsd
Comment posted by aaaa on Thursday, March 20, 2008 7:53 AM
fgdfg
Comment posted by km' on Thursday, March 27, 2008 7:33 PM
kljnlkkkk
Comment posted by serfer on Tuesday, April 01, 2008 2:29 PM
It's very useful code. I just have one question. In my case, I'm using Exchange Server, and I have McAfee Antivirus, so I had to give permission to my application in the Wormstopper options.  Is it the right thing to do?  Isn't it dangerous?  What are the risks?  ...Does anyone can make a malicious program named as mine to get into my server?  Thanks.
Comment posted by lok on Thursday, April 10, 2008 1:59 AM
fghfgh fghfgh f hfgh
Comment posted by Baji on Monday, April 21, 2008 3:38 AM
while iam sending mail from asp.net page.. it dont send what happend i dont get it..and i also make the proper setting in IIS also...still Mails r not sending out..why?
Comment posted by premsankar on Monday, June 30, 2008 5:42 AM
that code  doesnt work for me....
in 2 nd steo when i declare
  Dim message As MailMessage = New MailMessage("abc@somedomain.com", "administrator@anotherdomain.com", "Testing", "This is a test mail")
Comment posted by kirti on Wednesday, July 23, 2008 6:04 AM
Hi
I want to develop an email application with multipule attchements of listbox in asp.net 2.0
plz help
Thanks
Comment posted by puspanjali jena on Thursday, September 11, 2008 3:32 AM
Hi,
i want detail explanation to send mail.I couldn't implement this amount of codes to develop my project.
plz help
thanks
Comment posted by NITESH SAXENA on Friday, December 19, 2008 2:52 AM
nice article but how can we know the smtp server name
Comment posted by sdfads on Wednesday, February 11, 2009 6:44 AM
r
Comment posted by kkkk on Tuesday, March 10, 2009 3:01 AM
Im use
MailMessage message = new MailMessage ("from id here","to id here","Testing","This is a test mail");

        SmtpClient client = new SmtpClient("localhost");
        client.Send(message);
but i got an error
"No connection could be made because the target machine actively refused it "
Comment posted by Suprotim Agarwal on Tuesday, March 10, 2009 8:22 AM
kkkk: There could be a possibility of firewall blocking your connection.
Comment posted by Alexander Perez on Thursday, April 16, 2009 2:41 PM
I tried the code give no errors but i don't get the message. Im using my desktop to work with the aplication but at smtp i'm giving the exhange smtp but it dosn't do anything. Any security issues tha i'm missing? Please help.
Comment posted by Suprotim Agarwal on Friday, April 17, 2009 5:57 AM
Can you post some code over here. Make sure you remove the actual SMTP details and username/pwds while posting the code, as it is not advisable to post security details on an open site.
Comment posted by Arti on Thursday, May 14, 2009 3:25 AM
in web.config file i wrote
<appSettings>
  
    <add key="MyMailServer" value ="localhost"/>
    <add key="MyMailServerPort" value ="25"/>
  </appSettings>
n in asp.vb page i wrote this


Protected Sub btnSend_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSend.Click

        'send message

        Dim strMsg As String
        strMsg = txtMessage.Text

        mTo = Trim(txtTo.Text)
        mFrom = Trim(txtFrom.Text)
        mSubject = Trim(txtSubject.Text)
        mMsg = Trim(txtMessage.Text)


        mMailServer = ConfigurationManager.AppSettings.Get("MyMailServer")
        mPort = ConfigurationManager.AppSettings.Get("MyMailServerPort")
        mCC = Trim(txtCC.Text)

        Try

            Dim message As New MailMessage(mFrom, mTo, mSubject, mMsg)

            If fileAttachments.HasFile Then
                Dim attached As New Attachment(Trim(fileAttachments.PostedFile.FileName.ToString()))
                message.Attachments.Add(attached)
            End If

            If mCC <> "" Or mCC <> String.Empty Then
                Dim strCC() As String = Split(mCC, ";")
                Dim strThisCC As String
                For Each strThisCC In strCC
                    message.CC.Add(Trim(strThisCC))
                Next
            End If


            Dim mySmtpClient As New SmtpClient(mMailServer, mPort)
            mySmtpClient.UseDefaultCredentials = True
            mySmtpClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis
            mySmtpClient.Send(message)

            MessageBox("The mail message has been sent to " & message.To.ToString())

        Catch ex As FormatException

            MessageBox("Format Exception: " & ex.Message)

        Catch ex As SmtpException

            MessageBox("SMTP Exception:  " & ex.Message)

        Catch ex As Exception

            MessageBox("General Exception:  " & ex.Message)

        End Try
end Sub

  i mgetting the mail sent message But not Getting any mail
in my mailbox
will u All Experts Give me the reason Plzzzzzz
Comment posted by bingo play live on Monday, June 01, 2009 1:00 AM
these steps are really very usefull for me m a software engg.but plz discribe these steps in more detail with example.
Comment posted by binay on Wednesday, June 17, 2009 5:10 AM
hi
Comment posted by sanjay on Monday, June 29, 2009 5:09 AM
I successfuly send mail by gmail but when i send from my company relay server then i failure. my code foolwing way please any one help me.
Web Conf.->
<system.net>
      <mailSettings>
         <smtp deliveryMethod="Network">
            <network host="smtp.hravishkar.com" port="25" defaultCredentials="true" userName="" password=""></network>
         </smtp>
      </mailSettings>
   </system.net>
asp.net file ->
  MailMessage m = new MailMessage();
            SmtpClient smtp = new SmtpClient();
            //  smtp.Host = "127.0.0.1";
            //smtp.Port = 25;

          // Default port will be 25
            smtp.Host = "smtp.hravishkar.com";
             //smtp.Port = 587;
            smtp.Port = 25;
            smtp.EnableSsl = true;

            m.From = new System.Net.Mail.MailAddress(txtFrom.Text, "http://www.hravishkar.com");
            m.To.Add(txtTo.Text);
            m.Priority = MailPriority.High;
            m.Subject = txtSubject.Text;
            m.Body = txtMessage.Text;
            m.IsBodyHtml = false;
            // CC and BCC optional
            // MailAddressCollection class is used to send the email to various users
            // You can specify Address as new MailAddress("admin1@yoursite.com")
            m.CC.Add(txtFrom.Text);
            // You can specify Address directly as string
            m.Bcc.Add(txtFrom.Text);
            smtp.Send(m);
Comment posted by Suprotim Agarwal on Thursday, July 02, 2009 2:15 AM
Sanjay: Check out with your admin if the server requires credentials to send the mail!
Comment posted by Arunkumar on Friday, July 03, 2009 3:26 AM
Dim MAtt As Net.Mail.Attachment
            Dim emailClient As New SmtpClient("localhost server")
            Dim message As New MailMessage
            Dim FromAdd As New MailAddress("ur local host mail id(arun@tech.in)")

            Dim ToAdd As New MailAddress("afaf@gmail.com")



            message.From = FromAdd
            message.To.Add(ToAdd)
            message.Subject = "Request For Quotation E-MAIL On " & Today
            MAtt = New Net.Mail.Attachment(" file path")
            message.Attachments.Add(MAtt)

            emailClient.UseDefaultCredentials = False
            'mension from address and ur password here
            emailClient.Credentials = New Net.NetworkCredential("local host mail id ", "paswd")
            ' Dim userinfo As New CreateUserWizard(
            emailClient.Host = "local host server"
            emailClient.Port = 25
            emailClient.Send(message)

            MsgBox("Mail has sent")
Comment posted by sanjay on Monday, August 10, 2009 8:21 AM
please help me,
  i want to send email by defualt credential but i failure to send and also explai i must to send mail server userName and password if i want to send email using defualt credentia; please reply me for my job.
Comment posted by Suprotim Agarwal on Tuesday, August 11, 2009 1:17 AM
Sanjay: You provide very little information, not enough to help you out.

What error do you get when you send the email? Is it 401? Ask your admin to check the server for events, specifially the 'Security' event log and see if there are any Failure Audits occuring.

This video should also help you out http://www.asp.net/learn/videos/video-416.aspx
Comment posted by sunny on Wednesday, August 12, 2009 6:13 AM
iam getting the error while deleting the file in the localdrive which sent as an attachment. the error system.io.ioexception: the process access the file"C:\abc.xml" because it is used by another process. after sending the mail iam disposing the mail message object also. like mailmessage.dispose().can anybody help me.
Comment posted by Pawan Sugandhi on Monday, October 05, 2009 3:02 AM
l;l;
Comment posted by zenich on Monday, October 12, 2009 3:40 PM
Hi,
I am trying to send mail with attachment..it's perfectly working fine but when i hosted to different web server..i am getting an error saying that "Can not find part of the path " Please advise if anybody knows about the error..Thankx in Advance
Comment posted by dhixa on Wednesday, December 16, 2009 2:22 AM
plz send me detailed code about sending a mail to a particular person whn i press a submit button in my .aspx file
Comment posted by ashwin marthak on Thursday, February 11, 2010 2:24 PM
thanks it is very useful for us....
Comment posted by patel sandip on Monday, March 29, 2010 9:28 AM
i am create the sending mail via asp.net project connected the asp.net
Comment posted by saranya elangovan on Thursday, June 10, 2010 2:46 AM
how to create a sending mail in asp.net with c# sharp coding with run on IIS SERVER without publishing any domain name or Host Server
Comment posted by saranya on Thursday, June 10, 2010 2:54 AM
while iam sending mail from asp.net page.. it dont send what happend i dont get it..and i also make the proper setting in IIS also...still Mails r not sending out..why? if (TextBox12.Text != "" && TextBox13.Text  != "" && TextBox14.Text != "")
        {
            MailMessage mail = new MailMessage();

            mail.To.Add(TextBox14.Text);

            mail.From = new MailAddress("saranya@gmail.com");

            mail.Subject = "Comments from Visitors";

            string Body = TextBox12.Text;

            mail.Body = Body;

            mail.IsBodyHtml = true;

            SmtpClient smtp = new SmtpClient();

            smtp.Host = ""; //Or Your SMTP Server Address

            smtp.Credentials = new System.Net.NetworkCredential("saranya@gmail.com", "123456");//Or your Smtp Email ID and Password

            smtp.EnableSsl = true;

          // smtp.Send(mail);
            Label15.Text = "Your Mail Send Successfully !";

            Label16.Text = TextBox12.Text;

          //Label.Text = txtemailid.Text;

            TextBox12.Text = "";

            TextBox13.Text = "";

            TextBox14.Text = "";

            //llbemailid.Visible = true;

            //llbuser.Visible = true;
        }
but it not send to the prompt msg to the fetching address y? wats the reason? but i'm not hosted any websit but i want to send the mailing to the admin please give the correct coding to me
Comment posted by anand on Monday, July 05, 2010 3:12 AM
Hey saranya u just have mention the port number for gmail...... 587
Comment posted by yuanchao on Thursday, July 08, 2010 2:39 AM
hello
Comment posted by hari on Friday, August 27, 2010 2:07 AM
hai i want sending mail from asp.net using yahoo portnumber and host name only

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel

NEWSLETTER