Saturday, 13 April 2013

Send Bulk Emails using C# VB.NET in ASP.NET


Send Bulk Emails using C# VB.NET in ASP.NET


have been asked zillion times that How to Send Bulk Emails using C# or VB.NET in ASP.NET.

Well, there are hundreds of tutorials all over the internet on sending bulk emails in ASP.NET using C# or VB.NET.

However, I decided to post a basic "how to" for beginners so that they can easily understand the functionality of send bulk emails in ASP.NET.

For this example I will be using Northwind Database.

Step 1:





ASPX Code:

<form id="form1" runat="server">
    <div>
        Recipient(s):<br />
    <asp:TextBox ID="txtRecipient" runat="server" Height="50px" Width="525px"
            TextMode="MultiLine"></asp:TextBox>
        <br />
        <asp:Button ID="btnRecipientFromDB" runat="server"
            onclick="btnRecipientFromDB_Click" Text="Recipient From Database" />
        <br />
        <asp:CheckBoxList ID="chklstRecipientsFromDB" runat="server"Visible="False">
        </asp:CheckBoxList><asp:Button ID="btnAddSelected" runat="server"
            Text="Add Selected" onclick="btnAddSelected_Click" Visible="False" />
       
        <br />
        Subject:<br />
    <asp:TextBox ID="txtSubject" runat="server" Height="18px" Width="522px"></asp:TextBox>
   
        <br />
        <br />
        Email Body:<br />
        <asp:TextBox ID="txtEmailBody" runat="server" Height="290px"Width="520px"
            TextMode="MultiLine"></asp:TextBox>
        <br />
        <asp:Button ID="btnSend" runat="server" onclick="btnSend_Click"
            Text="Send Email" />
   
    </div>
</form>


This is simple form containing 3 TextBoxes

  1. Recipient(s)
  2. Email Subject
  3. Email Body
"Add Recipients from Database" button will show list of already added contacts from database as shown in image below:

Now, user has two options, either they can select multiple users from list and/or they can add recipients email address manually separated by ";"

Code Behind:
C#:

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

namespace TestApplication
{
    public partial class BulkEmail : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                chklstRecipientsFromDB.Visible = false;
                btnAddSelected.Visible = false;
            }
        }

        protected void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                #region Direct Email to db Recipients
                //if you want to send emails directly to recipient from database, use code below
                //DataSet dsClients = GetClientDataSet();
                //if (dsClients.Tables["Users"].Rows.Count > 0)
                //{
                //    foreach (DataRow dr in dsClients.Tables["Users"].Rows)
                //    {
                //        SendEmail(dr["Email"].ToString());
                //    }
                //}
                #endregion

                char[] splitter = { ';' };
                foreach (string emailAdd in txtRecipient.Text.Split(splitter))
                {
                    SendEmail(emailAdd);
                }
            }
            catch (Exception ex)
            {
            }
        }

        protected void btnRecipientFromDB_Click(object sender, EventArgs e)
        {
            try
            {
                DataSet dsClients = GetClientDataSet();

                chklstRecipientsFromDB.DataSource = dsClients.Tables[0];
                chklstRecipientsFromDB.DataTextField = "Email";
                chklstRecipientsFromDB.DataValueField = "Email";
                chklstRecipientsFromDB.DataBind();

                chklstRecipientsFromDB.Visible = true;
                btnAddSelected.Visible = true;
                btnRecipientFromDB.Visible = false;
            }
            catch (Exception ex)
            {
            }
            finally
            {
            }
        }
        ///
        ///  Creates and returns a DataSet using Ms Access OleDBConnection and an OleDBDataAdapter
        ///
        ///
        /// A DataSet from Ms Access using an OleDBConnection and an OleDBDataAdapter
        ///
        private System.Data.DataSet GetClientDataSet()
        {

            //retrieve the connection string from the ConnectionString Key in Web.Config
            //string connectionString = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
            string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Talha\Documents\Database2.accdb;Persist Security Info=False;";

            //create a new OleDB connection
            System.Data.OleDb.OleDbConnection conn = newSystem.Data.OleDb.OleDbConnection(connectionString);

            //pass the Select statement and connection information to the initializxation constructor for the OleDBDataAdapter
            System.Data.OleDb.OleDbDataAdapter myDataAdapter = newSystem.Data.OleDb.OleDbDataAdapter("SELECT Email FROM Employees", conn);

            //Create a new dataset with a table : CLIENTS
            System.Data.DataSet myDataSet = new System.Data.DataSet("Users");

            //Fill the dataset and table with the data retrieved by the select command
            myDataAdapter.Fill(myDataSet, "Users");

            //return the new dataset created
            return myDataSet;
        }
        private void SendEmail(string EmailAddress)
        {
            //Send Email Functionality here
            MailMessage mail = new MailMessage();
            mail.To.Add(EmailAddress);
            mail.From = new MailAddress("admin@codeshode.com");
            mail.Subject = txtSubject.Text;
            mail.Body = txtEmailBody.Text;

            mail.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com"//Or Your SMTP Server Address
            smtp.Credentials = newSystem.Net.NetworkCredential("YourUserName@gmail.com""YourGmailPassword");//Or your Smtp Email ID and Password
            smtp.EnableSsl = true;
            smtp.Send(mail);
        }

        protected void btnAddSelected_Click(object sender, EventArgs e)
        {
            StringBuilder strRecipientEmails = new StringBuilder();
            foreach (ListItem chk in chklstRecipientsFromDB.Items)
            {
                if (chk.Selected)
                {
                    strRecipientEmails.Append(chk.Value);
                    strRecipientEmails.Append(";");
                }
            }
            txtRecipient.Text = strRecipientEmails.ToString();
            chklstRecipientsFromDB.Visible = false;
            btnAddSelected.Visible = false;
        }
    }
}


VB.NET:

Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Data
Imports System.Text
Imports System.Net.Mail

Partial Public Class BulkEmail
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(sender As Object, e As EventArgs)
        If Not IsPostBack Then
            chklstRecipientsFromDB.Visible = False
            btnAddSelected.Visible = False
        End If
    End Sub

    Protected Sub btnSend_Click(sender As Object, e As EventArgs)
        Try
            '#Region "Direct Email to db Recipients"
            'if you want to send emails directly to recipient from database, use code below
            'DataSet dsClients = GetClientDataSet();
            'if (dsClients.Tables["Users"].Rows.Count > 0)
            '{
            '    foreach (DataRow dr in dsClients.Tables["Users"].Rows)
            '    {
            '        SendEmail(dr["Email"].ToString());
            '    }
            '}
            '#End Region

            Dim splitter As Char() = {";"c}
            For Each emailAdd As String In txtRecipient.Text.Split(splitter)
                SendEmail(emailAdd)
            Next
        Catch ex As Exception
        End Try
    End Sub

    Protected Sub btnRecipientFromDB_Click(sender As Object, e As EventArgs)
        Try
            Dim dsClients As DataSet = GetClientDataSet()

            chklstRecipientsFromDB.DataSource = dsClients.Tables(0)
            chklstRecipientsFromDB.DataTextField = "Email"
            chklstRecipientsFromDB.DataValueField = "Email"
            chklstRecipientsFromDB.DataBind()

            chklstRecipientsFromDB.Visible = True
            btnAddSelected.Visible = True
        Catch ex As Exception
        Finally
        End Try
    End Sub
    '''
    '''  Creates and returns a DataSet using Ms Access OleDBConnection and an OleDBDataAdapter
    '''
    '''
    ''' A DataSet from Ms Access using an OleDBConnection and an OleDBDataAdapter
    '''
    Private Function GetClientDataSet() As System.Data.DataSet

        'retrieve the connection string from the ConnectionString Key in Web.Config
        'string connectionString = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
        Dim connectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Talha\Documents\Database2.accdb;Persist Security Info=False;"

        'create a new OleDB connection
        Dim conn As New System.Data.OleDb.OleDbConnection(connectionString)

        'pass the Select statement and connection information to the initializxation constructor for the OleDBDataAdapter
        Dim myDataAdapter As New System.Data.OleDb.OleDbDataAdapter("SELECT Email FROM Employees", conn)

        'Create a new dataset with a table : CLIENTS
        Dim myDataSet As New System.Data.DataSet("Users")

        'Fill the dataset and table with the data retrieved by the select command
        myDataAdapter.Fill(myDataSet, "Users")

        'return the new dataset created
        Return myDataSet
    End Function
    Private Sub SendEmail(EmailAddress As String)
        'Send Email Functionality here
        Dim mail As New MailMessage()
        mail.[To].Add(EmailAddress)
        mail.From = New MailAddress("admin@codeshode.com")
        mail.Subject = txtSubject.Text
        mail.Body = txtEmailBody.Text

        mail.IsBodyHtml = True
        Dim smtp As New SmtpClient()
        smtp.Host = "smtp.gmail.com"
        'Or Your SMTP Server Address
        smtp.Credentials = NewSystem.Net.NetworkCredential("YourUserName@gmail.com""YourGmailPassword")
        'Or your Smtp Email ID and Password
        smtp.EnableSsl = True
        smtp.Send(mail)
    End Sub

    Protected Sub btnAddSelected_Click(sender As Object, e As EventArgs)
        Dim strRecipientEmails As New StringBuilder()
        For Each chk As ListItem In chklstRecipientsFromDB.Items
            If chk.Selected Then
                strRecipientEmails.Append(chk.Value)
                strRecipientEmails.Append(";")
            End If
        Next
        txtRecipient.Text = strRecipientEmails.ToString()
        chklstRecipientsFromDB.Visible = False
        btnAddSelected.Visible = False
    End Sub
End Class



Now you may type Email Subject, Email Body and press "Send Email" to send bulk emails!


Thats It!!

No comments:

Post a Comment