Click here to Skip to main content
15,907,392 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.SqlClient;
using System.Data;
using System.Drawing;
using System.IO;
using System.Net.Mail;
using System.Configuration;

public partial class ShopOwner_SendMail : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection("Data Source=.\\sql2008;initial catalog=DB;user id=sa;password=123456");
    //string MailId = "";
   // public static string name;
    string[] CustNameArray = new string[2000];
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["emailid"] == null || Session["emailid"].ToString() == "")
        {
            Response.Redirect("Default.aspx");

        }
        if (!Page.IsPostBack)
        {
            Panel1.Visible = false;
            Panel2.Visible = true;
            GetData();
            //getemails();
            //clearall();
        }


    }
    /*Functons that helps to send mail*/
    protected void SendEmail(object sender, EventArgs e)
    {
        try
        {

            if (ddlgender.SelectedIndex == 0 || ddlScheme.SelectedIndex == 0)
            {
                lblmsg2.ForeColor = Color.Red;
                lblmsg2.Text = "Please select Scheme and Cutomer Gender Whom You wants to send mail";
            }
            else 
            {


                string qr1 = "select * from SchemeMast where SchemeId ='"+ ddlScheme.SelectedValue+"'";
                SqlDataAdapter adp1 = new SqlDataAdapter(qr1, con);
                DataTable dt = new DataTable();
                adp1.Fill(dt);
                
               


                string cn = "";
                string n = Session["ShopName"].ToString();
                string d = ddlScheme.SelectedItem.Text;

                string startDate = dt.Rows[0]["StartDate"].ToString();
                string endDate = dt.Rows[0]["EndDate"].ToString();


                string img = "ShopOwner/Uploads_FireMonkey/TanesH/jim-morrison-quote.jpg";
                string sn = Session["ShopNumber"].ToString();
                string flor = Session["FloorId"].ToString();
                string dr = "";

                string body = this.PopulateBody(cn, n, img, d, startDate , endDate , sn, flor, dr);
                
                this.SendHtmlFormattedEmail("recipient@gmail.com", "Special Offer For you..!!!  Hurry..!!", body);

                string script = @"<script language=""javascript""> alert('Mailed successfully....!!!');
                    </script>;";
                Page.ClientScript.RegisterStartupScript(this.GetType(), "myJScript1", script);
                //Response.Write(name);

            }
            

        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);

        }
    }
    private string PopulateBody(String CustName,string ShopName, string imgpath, string Discp, string std, string etd, string ShopNo, string FLoor, string un)
    {
        string body = string.Empty;
        body = body + "<br/><img src=cid:SchemePic>";

        using (StreamReader reader = new StreamReader(Server.MapPath("~/SchemeMailFormet.htm")))
        {
            body = reader.ReadToEnd();
        }

        body = body.Replace("{UserName}", CustName );
        body = body.Replace("{ShopName}", ShopName);
        body = body.Replace("{ImagePath}", imgpath);
        body = body.Replace("{SchemeDiscription}", Discp);

        body = body.Replace("{StartDate}", std);
        body = body.Replace("{EndDate}", etd);
        
        body = body.Replace("{ShopNo}", ShopNo);
        body = body.Replace("{FloorNo}", FLoor);
        body = body.Replace("{Description}", un);
        return body;
    }
    private void SendHtmlFormattedEmail(string recepientEmail, string subject, string body)
    {
        using (MailMessage mailMessage = new MailMessage())
        {

            mailMessage.From = new MailAddress(ConfigurationManager.AppSettings["UserName"]);
            mailMessage.Subject = subject;
            mailMessage.Body = body;
            mailMessage.IsBodyHtml = true;

            if (ddlgender.SelectedValue == "Male")
            {

                    string qr1 = "select * from CustMast where Gender ='Male'";
                    SqlDataAdapter adp1 = new SqlDataAdapter(qr1, con);
                    DataTable dt = new DataTable();
                    adp1.Fill(dt);
                    int i;
                    for (i = 0; i < dt.Rows.Count ; i++)
                    {
                        //mailMessage.To.Add(new MailAddress(dt.Rows[i]["EmailId"].ToString()));
                        CustNameArray[i] = dt.Rows[i]["EmailID"].ToString();
                        //  name = CustNameArray[i].ToString();
                        //SmtpClient smtp = new SmtpClient();
                        //smtp.Host = ConfigurationManager.AppSettings["Host"];
                        //smtp.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]);
                        //System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
                       // NetworkCred.UserName = ConfigurationManager.AppSettings["UserName"];
                       // NetworkCred.Password = ConfigurationManager.AppSettings["Password"];
                        //smtp.UseDefaultCredentials = true;
                       // smtp.Credentials = NetworkCred;
                       // smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);
                        //smtp.Send(mailMessage);

                    }
                    for (i = 0; i < dt.Rows.Count; i++)
                    {
                        mailMessage.To.Add(new MailAddress(CustNameArray[i]));
                        SmtpClient smtp = new SmtpClient();
                        smtp.Host = ConfigurationManager.AppSettings["Host"];
                        smtp.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]);
                        System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
                        NetworkCred.UserName = ConfigurationManager.AppSettings["UserName"];
                        NetworkCred.Password = ConfigurationManager.AppSettings["Password"];
                        smtp.UseDefaultCredentials = true;
                        smtp.Credentials = NetworkCred;
                        smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);
                        smtp.Send(mailMessage);
                    }

                    
                    //name = CustNameArray[1].ToString();

                }
                else if (ddlgender.SelectedValue == "Female")
                {
                    string qr1 = "select * from CustMast where Gender ='Female'";
                    SqlDataAdapter adp1 = new SqlDataAdapter(qr1, con);
                    DataTable dt = new DataTable();
                    adp1.Fill(dt);
                    
                    int i;
                    for (i = 0; i < dt.Rows.Count; i++)
                    {
                        mailMessage.To.Add(new MailAddress(dt.Rows[i]["EmailId"].ToString()));
                        //CustNameArray[i] = dt.Rows[i]["CustName"].ToString();
                       // name = CustNameArray[i].ToString();
                        SmtpClient smtp = new SmtpClient();
                        smtp.Host = ConfigurationManager.AppSettings["Host"];
                        smtp.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]);
                        System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
                        NetworkCred.UserName = ConfigurationManager.AppSettings["UserName"];
                        NetworkCred.Password = ConfigurationManager.AppSettings["Password"];
                        smtp.UseDefaultCredentials = true;
                        smtp.Credentials = NetworkCred;
                        smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);
                        smtp.Send(mailMessage);

                    }
                 //   name = CustNameArray[1].ToString();


                }
                else if (ddlgender.SelectedValue == "All")
                {
                    string qr1 = "select * from CustMast";
                    SqlDataAdapter adp1 = new SqlDataAdapter(qr1, con);
                    DataTable dt = new DataTable();
                    adp1.Fill(dt);
                    int i;
                    for (i = 0; i < dt.Rows.Count; i++)
                    {
                        mailMessage.To.Add(new MailAddress(dt.Rows[i]["EmailId"].ToString()));
                       // CustNameArray[i] = dt.Rows[i]["CustName"].ToString();
                       // name = CustNameArray[i].ToString();
                        SmtpClient smtp = new SmtpClient();
                        smtp.Host = ConfigurationManager.AppSettings["Host"];
                        smtp.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]);
                        System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
                        NetworkCred.UserName = ConfigurationManager.AppSettings["UserName"];
                        NetworkCred.Password = ConfigurationManager.AppSettings["Password"];
                        smtp.UseDefaultCredentials = true;
                        smtp.Credentials = NetworkCred;
                        smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);
                        smtp.Send(mailMessage);

                    }
                    



                }

            


        }
    }



    protected void GetData()
    {
        string qr = "select  CustName,gender,EmailID,add1,phno from CustMast";
        SqlDataAdapter adp = new SqlDataAdapter(qr, con);
        DataTable dt = new DataTable();
        adp.Fill(dt);
        GvCustList.DataSource = dt;
        GvCustList.DataBind();

        string qr1 = "select * from SchemeMast where shopId = '" + Session["ShopId"].ToString() + "'";
        SqlDataAdapter adp1 = new SqlDataAdapter(qr1, con);
        DataSet ds = new DataSet();
        adp1.Fill(ds);
        ddlScheme.DataSource = ds;
        ddlScheme.DataTextField = "SchemeDiscp";
        ddlScheme.DataValueField = "SchemeId";
        ddlScheme.DataBind();
        ddlScheme.Items.Insert(0, new ListItem("--Select Scheme Here--", "0"));
    }
    protected void btnVisable_Click(object sender, EventArgs e)
    {
        Panel1.Visible = true;
        Panel2.Visible = false;

    }

}


What I have tried:

I tried , this code works fine but there is a problem,
if there are 4 customers then....
1st customer get 4 same messages,
2nd customer gets 3 same messages,
3rd recievs 3m messages and last one will get 1.

please help me how to solve this. sory for my bad english. ;)
Posted
Updated 19-Mar-16 7:23am
Comments
PIEBALDconsult 19-Mar-16 12:56pm    
I doubt you want the customers to see the addresses of the other customers, so be sure to use Blind Copy or send separate emails.
FireMonkey018 19-Mar-16 13:20pm    
how can ii make this possible using this code??
using
CC
BCC is that posible then how?


And I solved the question i posted just.
FireMonkey018 19-Mar-16 13:39pm    
mailMessage.Bcc.Add("Noreplay@productivePlus.com");

This Did helped .. thanks for helpin me bro..:)

It was my first question on Code Project... :):)

1 solution

This line is adding a new recipient to your mail
C#
mailMessage.To.Add(new MailAddress(CustNameArray[i]));

You need to clear the list of recipients before sending the next message.
otherwise
Message 1 is sent to recipient 1
Message 2 is sent to recipient 1 and 2
Message 3 is sent to recipient 1, 2 and 3
Message 4 is sent to recipient 1, 2, 3 and 4
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900