How to send Bulk Email to all recipients in a list or gridview using c#

In this blog I am going to show how we could send Bulk Emails at a single click in c#. I Have taken just 4 records in gridview and sending mail to all the emailIds in the gridview in a single click
Added a gridview in which I have added few records with Name and their Email Ids. One button has been added which I am using to send mail to all the records having Email ids. Below is my code for sample, change according to your requirements.


1. First of all add below code in your .aspx page::
    <div>
            <asp:Panel ID="Panel1" runat="server" Width="100%" ScrollBars="Horizontal">
                <asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="False" CellPadding="4" EnableModelValidation="True" ForeColor="#333333" GridLines="None">
                    <AlternatingRowStyle BackColor="White" />
                    <Columns>
                        <asp:BoundField DataField="Name" HeaderText="Name" />
                        <asp:BoundField DataField="Email" HeaderText="Email" />
                    </Columns>
                    <EditRowStyle BackColor="#2461BF" />
                    <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                    <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                    <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                    <RowStyle BackColor="#EFF3FB" />
                    <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                </asp:GridView>
                <br />
                <asp:Button ID="btnSend" runat="server" Text="Send Email to all Recepients" OnClick="btnSend_Click" />
                <br />
            </asp:Panel>
        </div>



2. Now, paste below code in your config page and made changes in Keys fields according to your domainName and details ::

  <appSettings>
    <add key="SmtpHostName" value="smtp.domainName.com"/>
    <add key="SmtpPort" value="25"/>   <!--Your PortNumber Here-->
    <add key="SmtpUserName" value="sendersEmailId@domainName.com"/>
    <add key="SmtpPassword" value="SendersPassword"/>
    <add key="IsSmtpEnableSsl" value="true"/>
  </appSettings>

3. Now, paste the below code in your Code window page::


using System.Net.Mail;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

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

            try
            {
                if (!Page.IsPostBack)
                {
                    BindGrid();
                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
        }

        void ShowMessage(string sErrorMsg)
        {
            ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('" + sErrorMsg + "');</script>");
        }

        private void BindGrid()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Email", typeof(string));

            DataRow dr = dt.NewRow();
            dr["Name"] = "Aayush";
            dr["Email"] = "a.singh@domainName.com";
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr["Name"] = "Sanjeev Sharma";
            dr["Email"] = "sanjeev@domainName.com";
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr["Name"] = "Raja Muraad";
            dr["Email"] = "raja@domainName.com";
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr["Name"] = "Ranjeet";
            dr["Email"] = "ranjeet@domainName.com";
            dt.Rows.Add(dr);

            gvCustomers.DataSource = dt;
            gvCustomers.DataBind();
        }

        public static void SendEmailUsingSmtp(string sFromEmailAddr, string sToEmailAddr, string sSubject, string sHtmlBodyText)
        {
            string sSmtpHostName = System.Configuration.ConfigurationManager.AppSettings["SmtpHostName"];
            int iSmtpPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpPort"]);
            string sSmtpUserName = System.Configuration.ConfigurationManager.AppSettings["SmtpUserName"];
            string sSmtpPassword = System.Configuration.ConfigurationManager.AppSettings["SmtpPassword"];
            bool bIsEnableSsl = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["IsSmtpEnableSsl"]);
            bool bIsBodyHtml = true;

            MailMessage mailPortal = new MailMessage();
            SmtpClient clientServer = new SmtpClient(sSmtpHostName, iSmtpPort);

            mailPortal.From = new MailAddress(sFromEmailAddr);
            mailPortal.To.Add(sToEmailAddr);
            mailPortal.Subject = sSubject;
            mailPortal.IsBodyHtml = bIsBodyHtml;


            mailPortal.Body = sHtmlBodyText;
            clientServer.EnableSsl = bIsEnableSsl;
            ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
            clientServer.Credentials = new NetworkCredential(sSmtpUserName, sSmtpPassword);
            clientServer.Send(mailPortal);

            if (clientServer != null)
                clientServer.Dispose();

                if (mailPortal != null)
                    mailPortal.Dispose();
        }

        protected void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (GridViewRow grow in gvCustomers.Rows)
                {
                    string strContactName = grow.Cells[0].Text.Trim();
                    string strEmail = grow.Cells[1].Text.Trim();
 
     //Event.html is a page which I have addded in my project and contains the format and message which would be sent to receivers
                    string filename = Server.MapPath("~/Event.html");
                    string mailbody = System.IO.File.ReadAllText(filename);
                    mailbody = mailbody.Replace("Receiver Mail", strContactName);
                    string to = strEmail;
                    string from = "SenderMailID@domainName.com";
                    try
                    {
                        SendEmailUsingSmtp(from, to, "Auto Generated Email", mailbody);
                    }
                    catch (Exception ex)
                    {
                        ShowMessage(ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
        }
    }
}

Below is the 4 mails which i received after executing above code(Email id has been changed above)


Comments

Post a Comment

Popular posts from this blog

Search data in Gridview on Textbox Key press event using JQuery in Asp.Net- C#

StateCode and StatusCode Values for mostly used entities in Microsoft Dynamics CRM 2013

Dumps for Microsoft Dynamics CRM MB2-703 Practice Exam Questions Free

How to import CSV files into DataTable in C#

How to show enlarge image when mouse hover on image or link in Asp.Net(c#) using JavaScript

go to top image