Sending E-Mail ASP.NET and C# in simple steps

Sending email in asp.net is very useful and customizable too.We can send email using some smtp server. And if this is not viable (sometimes we don't have smtp accounts!) we can use our own gmail account to send email .Sending e-mail in asp.net is a simple process.
 First you have to add the mail settings in the web.config file. Adding this will enable your site to send mail. Next, Create a aspx page to send mail using this settings. This code can be used in any other pages to send mail.

Steps to send email



1. Open the web.config file of your website.
2. Add the following code inside the configuration element(<configuration>). To remember just above the </configuration> tag.


<system.net>
  <mailSettings>
  <smtp deliveryMethod="Network" from="MyName &lt;MyName@MyDomain.com&gt;">
  <network host="smtp.MyDomain.com" userName="MyName@MyDomain.com" password="Password"/>
  </smtp>
  </mailSettings>
</system.net>
</configuration>

3. Create an aspx page with C# as the programming language.
4. Open the code behind file and add the System.Net.Mail Namespace on top as show in red bold below.Adding this namespace enables to use the mail class to send mails.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;


5. Add the following code in the page load section. You can add this in any other event.

protected void Page_Load(object sender, EventArgs e)
    {
       MailMessage myMailMessage = new MailMessage();
       myMailMessage.Subject = "My New Mail";
       myMailMessage.Body = "This is my test mail to check";
       myMailMessage.From = new MailAddress("MyName@MyDomain.com", "MyName");
       myMailMessage.To.Add(new MailAddress("receiver@MyDomain.com", "receiver name"));
       SmtpClient mySmtpClient = new SmtpClient();
        mySmtpClient.Send(myMailMessage);
  }


6. The above code creates a mailmessage object. Adds the subject, from address, from name, receiver’s address, receiver’s name to the mail message object.
7. Then creates smtpclient object to send message.
8. The mail is sent by calling the send method with maimessage object.

Things to remember

The username provided in the web.config file and the from address in the myMailMessage object should be same because most of the hosting providers requires authentication to send mail. So the authentication email and from address should be same.


 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Best Hostgator Coupon Code