3 May 2013

Send emails in Asp.net sample code



Send emails in asp.net with C# in four easy steps.
Follow this steps to send mail in asp.net

Step1 :- Add maill settings in your configuration section of the web.cofig. The settings should look like this: 

<configuration>
    <system.net>
      <mailSettings>
         <smtp from="mail_id">
            <network host="mail.myDomain.com" port="25" userName="test@myDomain.com" password="myPassword"/>
         </smtp>
      </mailSettings>
   </system.net

Step2 :-Design your .aspx page to look as shown below
image of send mail form with controls laid out
Step3 :-Doube-click the Send button and add the following code

using System.Net.Mail; //this library contains necessary method to send mail

protected void cmdSend_Click(object sender, EventArgs e)
{
    MailMessage mMailMessage = new MailMessage();
    // address of sender
    mMailMessage.From = new MailAddress(txtFrom.Text);
    // recipient address
    mMailMessage.To.Add(new MailAddress(txtTo.Text));
    // Check if the bcc value is empty
    if (txtBcc.Text != string.Empty)
    {
        // Set the Bcc address of the mail message
        mMailMessage.Bcc.Add(new MailAddress(txtBcc.Text));
    }
    // Check if the cc value is empty
    if (txtCc.Text != string.Empty)
    {
        // Set the CC address of the mail message
        mMailMessage.CC.Add(new MailAddress(txtCc.Text));
     } // Set the subject of the mail message
    mMailMessage.Subject = txtSubject.Text;
    // Set the body of the mail message
    mMailMessage.Body = txtBody.Text;
    // Set the format of the mail message body as HTML
    mMailMessage.IsBodyHtml = true;
    // Set the priority of the mail message to normal
    mMailMessage.Priority = MailPriority.Normal;
    // Instantiate a new instance of SmtpClient
    SmtpClient mSmtpClient = new SmtpClient();
    // Send the mail message
    try
    {
        mSmtpClient.Send(mMailMessage);
    }
    catch (Exception ex)
    {
        ;//log error
        lblMessage.Text = ex.Message;
    }
    finally
    {
        mMailMessage.Dispose();
    }

Step4 :-Run the project, fill in the fields and click the Send button.

No comments:

Post a Comment