Send bulk Email in asp.net using excel file

When you want to send the mail to multiple person email id and your data exists in the excel file like email address and his name. you can accomplish this task using asp.net and c#. In C# under System.Net.Mail and System.Net namespace you can use classes which can help us to send mail effortlessly.

I am giving some sample code to understand the concept

Following is aspx design Page Sample


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="LogDatails.aspx.cs" Inherits="LogDatails" %> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

<html xmlns="http://www.w3.org/1999/xhtml" > 
<head runat="server"> 
    <title>Untitled Page</title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <div> 
    <a href="Default.aspx">Back</a> 
        <asp:GridView ID="GridView1" runat="server" AllowPaging="True"  PageSize="6" AutoGenerateColumns="False" CellPadding="4" DataSourceID="XmlDataSource1" ForeColor="#333333" GridLines="None"> 
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" /> 
            <Columns> 
                <asp:BoundField DataField="Message" HeaderText="Message" SortExpression="Message" /> 
                <asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date" /> 
            </Columns> 
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> 
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /> 
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" /> 
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> 
            <EditRowStyle BackColor="#999999" /> 
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" /> 
        </asp:GridView> 
        <asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/myLog.xml"></asp:XmlDataSource> 
    </div> 
    </form> 
</body> 
</html> 


and the following is aspx.cs Page sample



using System; 
using System.Data; 
using System.Configuration; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Web.UI.WebControls.WebParts; 
using System.Web.UI.HtmlControls; 
using System.Net.Mail; 
using System.Net; 
using System.Data.OleDb; 
using System.Xml; 
using System.IO; 
public partial class _Default : System.Web.UI.Page
{ 
    XmlTextWriter writer; 
    protected void Page_Load(object sender, EventArgs e)
    { 

    } 
    protected void btnSend_Click(object sender, EventArgs e)
    {  
        SmtpClient client = new SmtpClient("smtp.gmail.com");//Host Name 
        MailMessage msg = new MailMessage(); 
        NetworkCredential account = new NetworkCredential("something@gmail.com", ""); //User Name Password of Ur Email  

        bool fileExist = false;


        MailAddress from = new MailAddress("something@gmail.com", "something"); //From Name 



        OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.oledb.4.0;Data Source=" + Server.MapPath("~/Email.xls") + ";Extended Properties=Excel 8.0"); 
        string temp = OleDbMetaDataCollectionNames.Tables; 
        con.Open(); 
        DataTable dtsheetNames = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,null); 
        con.Close(); 
        OleDbDataAdapter Sda = new OleDbDataAdapter("Select * from ["+dtsheetNames.Rows[0]["TABLE_NAME"]+"]",con); 
        DataTable dt=new DataTable("hello"); 
         
        Sda.Fill(dt); 
         
        lblStatus.Text = dt.Rows[0]["Name"].ToString(); 

        if (File.Exists(Server.MapPath(".") + "/myLog.xml") == true) 
        { 
            fileExist = true; 
         
        } 
        if (fileExist != true)
        { 
            createXml("", "", Server.MapPath(".") + "/myLog.xml", false, false);
        } 
        foreach (DataRow dr in dt.Rows)
        { 
             
          
            msg.From = from; 
              
            msg.To.Add(dr["Email"].ToString()); 
            msg.Body = txtBody.Text; 
            msg.IsBodyHtml = true; 
            msg.Subject = txtSubject.Text; 
            client.EnableSsl = true; 
            client.UseDefaultCredentials = false; 
            client.Credentials = account; 
            try 
            { 
                client.Send(msg); 
                lblStatus.Text =  lblStatus.Text+"Successully Sent Mail To \"" + dr["Name"].ToString() + "\" for the Email Id \"" + dr["Email"].ToString() + "\" <br>"; 
                if (fileExist != true)
                    createXml("Successully Sent Mail To \"" + dr["Name"].ToString() + "\" for the Email Id \"" + dr["Email"].ToString() + "\"", DateTime.Now.ToString("dd-MMM-yyyy hh:mm"), Server.MapPath(".") + "/myLog.xml", true, false); 
                else 
                    getxml("Successully Sent Mail To \"" + dr["Name"].ToString() + "\" for the Email Id \"" + dr["Email"].ToString() + "\"", DateTime.Now.ToString("dd-MMM-yyyy hh:mm"), Server.MapPath(".") + "/myLog.xml"); 
                  
            } 
            catch (Exception ex) 
            { 
                lblStatus.Text = lblStatus.Text + "Error sending Mail To \"" + dr["Name"].ToString() + "\" for the Email Id \"" + dr["Email"].ToString() + "\"<br>"; 

                if (fileExist != true)
                    createXml("Error sending Mail To \"" + dr["Name"].ToString() + "\" for the Email Id \"" + dr["Email"].ToString() + "\"", DateTime.Now.ToString("dd-MMM-yyyy hh:mm"), Server.MapPath(".") + "/myLog.xml", true, false); 
                else 
                    getxml("Error sending Mail To \"" + dr["Name"].ToString() + "\" for the Email Id \"" + dr["Email"].ToString() + "\"", DateTime.Now.ToString("dd-MMM-yyyy hh:mm"), Server.MapPath(".") + "/myLog.xml"); 
            
            } 
          
        } 
        if(!fileExist) 
        createXml("", "", Server.MapPath(".") + "/myLog.xml", false, true); 
    } 
    public void getxml(string message,string date,string fileName) 
    { 
        XmlDocument doc = new XmlDocument(); 
        doc.Load(fileName); 
        XmlElement el = doc.CreateElement("LogTable"); 
        el.SetAttribute("Message",message); 

        el.SetAttribute("Date", date); ; 
         
        doc.DocumentElement.AppendChild(el); 
        doc.Save(fileName); 
    } 
    public void createXml(string message, string date, string fileName, bool ischild, bool isendEle)
    { 
        if (ischild == false && isendEle==false) 
        { 
            writer = new XmlTextWriter(Server.MapPath(".") + "/myLog.xml", null); 

            writer.WriteStartDocument(); 
            writer.WriteStartElement("EmailLog"); 
        } 
        else 
        { 
            if (isendEle == false)
            { 
                writer.WriteStartElement("LogTable"); 
                writer.WriteAttributeString("Message", message); 
          


            writer.WriteAttributeString("Date", date); 
            writer.WriteEndElement();   } 
        } 
        if (isendEle == true)
        { 
            writer.WriteEndElement(); 
            writer.Close(); 
        } 
    } 
} 

The above code reads the excel file and iterates each email id. This code also stores the logs of each mail sent into xml file for the reference. this code is ideal for the sending bulk emails using code. above code can be used as class library in project to reuse in different modules of project.

I Hope that you will benefited by the above code.

Hoppy Coding:)

Comments

  1. its very nice that i stumbled upon your website..it was really a wonderful read...i will bookmark your website and will take the rss feed also...thanks for sharing...

    bulk email server

    ReplyDelete

Post a Comment

Popular posts from this blog

Implement Logging in CSV file using Nlog in .net core MVC application- part 2

Implement Nlog in .Net core MVC application part 1

Angular User Session Timeout example step by step

Restore the lost focus of Auto post back controls in asp.net update Panel control

Disable backspace key using Jquery