Thursday, 31 March 2011

Email using ASP.NET


Introduction
The Email is important in the web site. When you are create a new website you have to implement in the email sending features as well. So in this article I will explain how to send email using ASP.NET with SMTP.
Implementation
As usual create a simple asp.net web project and then add following html code to design page accept the user input such as subject, to email address, from email address, body.In this demonstration I going to use the sample contact us page email sending.
Note: I have used the required validation controls to make sure subject, to email, body are must enter by users.

Figure:Contact us
HTML Code

<body>
    <form id="form1" runat="server">
        <div>
            <table width="700" border="0" cellpadding="1" cellspacing="1">
                <tr>
                    <td colspan="2" valign="middle">
                        <h2>
                            Contact us</h2>
                    </td>
                </tr>
                <tr>
                    <td width="254" valign="middle">
                        Name:</td>
                    <td width="446" valign="middle">
                        <asp:TextBox ID="txt_name" Width="300px" runat="server" ></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="txt_name"
                            ErrorMessage="Required"></asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td valign="middle">
                        Email Address:</td>
                    <td valign="middle">
                        <asp:TextBox ID="txt_email" runat="server" Width="300px" ></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="txt_email"
                            ErrorMessage="Required"></asp:RequiredFieldValidator>
                        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Enter Valid Email Address"
                            ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="txt_email"></asp:RegularExpressionValidator>
                    </td>
                </tr>
                <tr>
                    <td valign="middle">
                        Phone Number:</td>
                    <td valign="middle">
                        <asp:TextBox ID="txt_phone" Width="300px" runat="server" ></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server" ControlToValidate="txt_phone"
                            ErrorMessage="Required"></asp:RequiredFieldValidator>
                        &nbsp;
                        <asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ControlToValidate="txt_phone"
                            ErrorMessage="Enter numbers only" ValidationExpression="^\d+$"></asp:RegularExpressionValidator>
                    </td>
                </tr>
                <tr>
                    <td valign="middle">
                        Type of Service required:</td>
                    <td valign="middle">
                        <label>
                            <asp:DropDownList ID="dd_select" runat="server" >
                                <asp:ListItem Selected="True">Select type of Service required</asp:ListItem>
                                <asp:ListItem Value="Web Development">Web Development</asp:ListItem>
                                <asp:ListItem Value="Software Development">Software Development</asp:ListItem>
                                <asp:ListItem Value="Graphicd DEsign">Graphicd DEsign</asp:ListItem>
                            </asp:DropDownList>
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="dd_select"
                                ErrorMessage="Required" InitialValue="Select type of Service required"></asp:RequiredFieldValidator>
                        </label>
                    </td>
                </tr>
                <tr>
                    <td valign="middle">
                        Estimated Budget</td>
                    <td valign="middle">
                        <asp:DropDownList ID="dd_budget" runat="server" >
                            <asp:ListItem Selected="True">Select your budget</asp:ListItem>
                            <asp:ListItem Value="$500 to $1000">$500 to $1500</asp:ListItem>
                            <asp:ListItem Value="$1500 to $2500">$1500 to $2500</asp:ListItem>
                            <asp:ListItem Value="$2500 to $5000">$2500 to $5000</asp:ListItem>
                            <asp:ListItem Value="$5000 +">$5000 +</asp:ListItem>
                        </asp:DropDownList>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="dd_budget"
                            ErrorMessage="Required" InitialValue="Select your budget"></asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td valign="middle">
                        Comments:</td>
                    <td valign="middle">
                        <label>
                            <asp:TextBox ID="txt_comment" runat="server" class="textarea" Width="300px" Height="90px"
                                TextMode="MultiLine"></asp:TextBox>
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ErrorMessage="Required"
                                ControlToValidate="txt_comment"></asp:RequiredFieldValidator>
                        </label>
                    </td>
                </tr>
                <tr>
                    <td valign="middle">
                        How did you hear about us?</td>
                    <td valign="middle">
                        <asp:TextBox ID="txtget_id" Width="300px" runat="server" ></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td valign="middle" style="border-bottom: 0;">
                    </td>
                    <td valign="middle" style="border-bottom: 0;">
                        <label>
                            <asp:Button ID="btn_submit" runat="server" Text="Submit" class="btn" OnClick="btn_submit_Click" />
                            <asp:Button ID="btn_reset" runat="server" Text="Reset" class="btn" CausesValidation="false" OnClick="btn_reset_Click" />
                            <br />
                        </label>
                    </td>
                </tr>
                <tr>
                    <td valign="middle" style="border-bottom: 0;">
                        &nbsp;</td>
                    <td valign="middle" style="border-bottom: 0;">
                        &nbsp;<asp:Label ID="lbl_msg" runat="server" ForeColor="Black"></asp:Label>
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
We have designed contact us page to send email, now let’s start write code for send email, before that we have to configure the SMTP server to send email through the .NET, for the Microsoft made easy for us, just add the SMTPserver IP Address, port username and password in web.config file as like below,
<appSettings>
            <add key="to" value="bharti222000@yahoo.com"/>
            <add key="from" value="your_email_address_gmail"/>
            <add key="id" value="your_email_address_gmail"/>
            <add key="pswd" value="password of your gmail id"/>
            <add key="port" value="587"/>
            <add key="smtp" value="smtp.gmail.com"/>
      </appSettings>

If you are setup by this way, you don’t need specify settings details to SMTPclient object.ASP.NET automatically pickup configuration.
now write code for send email.
C# code

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
// these nemaespaces are used for email.
using System.Web.Mail;
using System.Net.Mime;
using System.IO;
//this namespace is used for the StringBuilder
using System.Text;

public partial class _Default : System.Web.UI.Page
{
    // here i declared a object of the string builder class
    StringBuilder str_mailer = new StringBuilder();
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void btn_submit_Click(object sender, EventArgs e)
    {
        // here i am calling method in which i  am completed coding for the email send.
        sendmail();
        // here i am calling method in which i  am completed coding to blank the all the textboxes.
        clr_rec();
    }
    protected void btn_reset_Click(object sender, EventArgs e)
    {
        // here i am calling method in which i  am completed coding to blank the all the textboxes.
        clr_rec();
    }
    private void clr_rec()
    {
        // In this method completed coding to blank the all the textboxes
        txt_name.Text = "";
        txt_email.Text = "";
        txt_phone.Text = "";
        txt_comment.Text = "";
        txtget_id.Text = "";
        dd_select.SelectedIndex = 0;
        dd_budget.SelectedIndex = 0;
    }
  
    private void sendmail()
    {
        try
        {

            // inside the str_mailer(StringBuilder) i am adding the data that will send through the email.
            // StringBuilder is the best class  to adding the complete string.
             str_mailer.Append(@"<b>Name : </b>  " + txt_name.Text);
             str_mailer.Append(@"\n\n\n\ <b>Email Address : </b>" + txt_email.Text );
             str_mailer.Append(@"<br/><b>Phone No : </b>" + txt_phone.Text);
             str_mailer.Append(@"<br/><b>Type Of Service : </b>" + dd_select.Text );
             str_mailer.Append(@"<br/><b>Estimated Budget : </b>" + dd_budget.Text);
             str_mailer.Append(@"<br/>" + "<b>Comment : </b>" + txt_comment.Text );
             str_mailer.Append(@"<br/>" + "<b>How Did You hear about Us : </b>" + txtget_id.Text);
             //below line m giving  sender's email address  and receiever's email address  that is also mentioned inside the <appSettings></appSettings> in the web.config file
             // and m also giving str_mailer.ToString() , in the str_mailer.ToString() coming  completed message with the html tags
             System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(ConfigurationManager.AppSettings["id"], ConfigurationManager.AppSettings["to"], "Info", str_mailer.ToString());
             //below line m giving  sender's email address and password of that email that is mentioned inside the <appSettings></appSettings> in the web.config file
             System.Net.NetworkCredential mailAuthentication = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["id"], ConfigurationManager.AppSettings["pswd"]);
             //below line m giving  smtp and port no: that is also mentioned inside the <appSettings></appSettings> in the web.config file
            System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient(ConfigurationManager.AppSettings["smtp"], Convert.ToInt32(ConfigurationManager.AppSettings["port"]));
            //System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587);
            //below m setting some important properties that is necessary to send the email
            mailClient.EnableSsl = true;
            //below property IsBodyHtml in true because inside the stringbuilder am using some HTMl tags
            mail.IsBodyHtml = true;
            mailClient.UseDefaultCredentials = false;
            mailClient.Credentials = mailAuthentication;
            mailClient.Send(mail);
            // when all the process will be completed then a message will be displayed inside the label
            lbl_msg.Text = "Thank you, your enquiry has been sent successfully. We will be in contact with you soon.";
        }
        catch
        {

            
           
                lbl_msg.Text = "Please wait..";
                sendmail();
           
          
        }

    }

}

Note:I'm using here SMTP Configuration.
In above code, just create smtpclient object and then set smtp server settings and user credential to accept the connection client and server.Then compose the email message from users input and call Send() method to  send email to address.
Conclusion
Through this article, you have learned how to send email for contact us operation in web site using asp.net

8 comments:

  1. This is great!

    Very nicely explained and easy to follow.

    However, I have a question: how do you automatically clear the text boxes after the form has been submitted, so you don't have to reset it manually?

    Many thanks

    Mark

    ReplyDelete
    Replies
    1. Hi!! Mark. Thanks a lot. For the automatically clear the text boxes after the form has been submitted, Call the function named
      clr_rec() at the end of the sendmail() function code, The function clr_rec() is same like as reset button code. Once again thanks you so much and please feel free to get in touch with my blog and you can also give us your expensive suggestions to improve this blog.

      Regards
      Using asp.net

      Delete
  2. i am using an html contact form, how can i use this code in html,where i have to place the C# code in my html contact page ?

    ReplyDelete
  3. thanks a lot sir this code is excellent and so simple works fine

    ReplyDelete