C#.Net How To: Send email in asp.net using c#

C#.Net How To: Send email in asp.net using c#,email sending ,ASP.net,how to send email using Gmail,SMTP server,SendEmail method
Share it:
In this article, we are going to see how we can send an email in ASP.net using C# code. To send an email using C# is not a big task and following the steps given in this article, anyone can send emails in asp.net using c#.

In this article, we will first create an ASP.net page that will accept some information like To address and Message body. Have a look at the below image, which will be the final output.

Send email in asp.net using c#


  • Open Visual Studio and create a new Website project. To create a new website click File -> New -> Project. Or simply clicking Ctrl+Shift+N keys together, .net IDE will allow you to create a new project.
  • Select Web from Installed Templates on the left pane, select ASP.NET Web Application from the right pane, enter your desired project name, location of the project, and click on the OK button.

How To: Send email in asp.net using c#


It will create a new ASP.net website application. By default Default.aspx page will be opened with default lines of code.


  • We need to create a new aspx page that will have the To and Body field. To add a new aspx page, right-click on your project name, then select Add and then select New Item. Or click Ctrl+Shift+A keys together; it will open an “Add New Item” window.
  • Select Web Form and name it as “ComposeMail.aspx” and click on Add  Button.

How To: Send email in asp.net



  • As soon as you click on the Add button, it will create a new page with the name “ComposeMail.aspx” and the default source code will be visible on the screen.
  • Now copy below source code to ComposeMail.aspx file. I have added To and Body textboxes to the page. Please see the screenshot given in the next step for more details.
<%@ Page Title=”Compose Email” Language=”C#” MasterPageFile=”~/Site.master” AutoEventWireup=”true”
    CodeBehind=”ComposeMail.aspx.cs” Inherits=”SendEmailFromAsp.Net.ComposeMail” %>

<asp:Content ID=”HeaderContent” runat=”server” ContentPlaceHolderID=”HeadContent”>
    <style type=”text/css”>
        .style1
        {
            width: 62px;
            text-align: right;
        }
        .style2
        {
            width: 24px;
            text-align: right;
        }
        .style3
        {
            width: 62px;
            height: 140px;
            text-align: right;
        }
        .style4
        {
            width: 24px;
            height: 140px;
            text-align: right;
        }
        .style5
        {
            height: 140px;
            width: 489px;
        }
        .style6
        {
            width: 489px;
        }
    </style>
</asp:Content>
<asp:Content ID=”BodyContent” runat=”server” ContentPlaceHolderID=”MainContent”>
    <h2>
        Welcome to Simple email send application in ASP.NET using C#.
    </h2>
    <p>
        To learn more about ASP.NET visit <a href=”http://a1ashiish-csharp.blogspot.com/”
            title=”C# Tutorials”>C# Tutorials</a>.
    </p>
    <p>
        <table style=”width: 100%;” width=”2″ >
            <tr>
                <td class=”style1″>
                    <strong></strong>
                </td>
                <td class=”style2″>
                    <strong></strong>
                </td>
                <td align=”center” class=”style6″>
                    &nbsp;
                    <asp:Label ID=”lblResult” runat=”server” Text=”"></asp:Label>
                </td>
                <td></td>
            </tr>
            <tr>
                <td class=”style1″>
                    <strong>To </strong>
                </td>
                <td class=”style2″>
                    <strong>: </strong>
                </td>
                <td class=”style6″>
                    &nbsp;
                    <asp:TextBox ID=”txtTo” runat=”server” Width=”475px”></asp:TextBox>
                </td>
                <td></td>
            </tr>
            <tr>
                <td class=”style1″>
                    <strong>Subject </strong>
                </td>
                <td class=”style2″>
                    <strong>: </strong>
                </td>
                <td class=”style6″>
                    &nbsp;
                    <asp:TextBox ID=”txtSubject” runat=”server” Width=”475px”></asp:TextBox>
                </td>
                <td></td>
            </tr>
            <tr>
                <td class=”style3″>
                    <strong>Message </strong>
                </td>
                <td class=”style4″>
                    <strong>: </strong>
                </td>
                <td class=”style5″>
                    &nbsp;
                    <asp:TextBox ID=”txtBody” runat=”server” Height=”132px” Width=”474px” TextMode=”MultiLine”></asp:TextBox>
                </td>
                <td></td>
            </tr>
            <tr>
                <td class=”style1″>
                </td>
                <td class=”style2″>
                    &nbsp;
                </td>
                <td class=”style6″>
                    &nbsp;&nbsp;
                    <asp:Button ID=”btnSend” runat=”server” Text=”Send” Width=”103px” OnClick=”btnSend_Click” />
                </td>
                <td></td>
            </tr>
        </table>
    </p>
    <p>
        &nbsp;</p>
</asp:Content>

  • Now click on Design, you will notice the below screenshot. As shown in the screenshot user will enter a To email address into the textbox and actual message (body) will enter in the Message textbox



sendmail in c#



  • Now we are going to write a SendEmail method that will accept three parameters i.e. To email id, subject, and body of an email. Double click on the Send button to open “ComposeMail.aspx.cs” file. To send an email please use below namespace -
using System.Net.Mail;

Now, write a SendEmail method. A complete listing of code of SendEmail the method is given below -

  protected string SendEmail(string toAddress, string subject, string body)
        {
            string result = “Message Sent Successfully..!!”;

            string senderID = “SenderEmailID“;// use sender’s email id here..
            const string senderPassword = “Password“; // sender password here…

            try
            {
                SmtpClient smtp = new SmtpClient
                {
                    Host = “SmtpServerAddress“, // smtp server address here…
                    Port = 587,
                    EnableSsl = true,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    Credentials = new System.Net.NetworkCredential(senderID, senderPassword),
                    Timeout = 30000,

                };

                MailMessage message = new MailMessage(senderID, toAddress, subject, body);

                smtp.Send(message);
            }
            catch (Exception ex)
            {
                result = “Error sending email.!!!”;
            }

            return result;
        }
  • Don’t forget to change the highlighted part of the above code, i.e. in, the above code, you need to change the Sender email id, password, and the SMTP server address. If you are using Gmail as your SMTP server, then follow my other article on HTML“>how to send email using Gmail.
  • In the above code, I have used the “EnableSsl” property. Use this property if your server needs SSL authentication. Otherwise, comment on the line or make it a false.
  • In the above steps we have added a method to send emails, however, we need to call the SendEmail method from send button click event. Write below code in btnSend_Click event in ComposeMail.aspx.cs file.
  • As per the above code, if the email is successfully transmitted then below message will appear on screen just above the “To” textbox –
Message Sent Successfully..!!

If any error occurred then below message will appear –

Error sending email.!!!



Now we are done with all design and coding parts of the email sending application in ASP.net. Hit the F5 button on the keyboard to execute the application, enter your recipient's address, type your message in body box, and click on send button to send the message.


Complete code of ComposeMail.aspx.cs files are given below and find complete design source code in step 6.

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;

namespace SendEmailFromAsp.Net
{
    public partial class ComposeMail : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnSend_Click(object sender, EventArgs e)
        {
            lblResult.BackColor = System.Drawing.Color.Red;
            lblResult.Text = SendEmail(txtTo.Text, txtSubject.Text, txtBody.Text);
        }

        protected string SendEmail(string toAddress, string subject, string body)
        {
            string result = “Message Sent Successfully..!!”;

            string senderID = “SenderEmailID”;// use sender’s email id here..
            const string senderPassword = “Password”; // sender password here…

            try
            {
                SmtpClient smtp = new SmtpClient
                {
                    Host = “SmtpServerAddress”, // smtp server address here…
                    Port = 587,
                    EnableSsl = true,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    Credentials = new System.Net.NetworkCredential(senderID, senderPassword),
                    Timeout = 30000,

                };

                MailMessage message = new MailMessage(senderID, toAddress, subject, body);

                smtp.Send(message);
            }
            catch (Exception ex)
            {
                result = “Error sending email.!!!”;
            }

            return result;
        }
    }
}

Read More:-
If you like the tutorial, then please share this tutorial with your friends on social media.

Share it:

aspnet

C#.Net How To: Send email in asp.net using c#

Post A Comment:

0 comments: