我如何...这是我的代码,我想通过一次点击向所有客户发送邮件。我的代码如下.. [英] How do i...this is my code and I wants to send a mail to ALL customers with a single click. My code is as below..

查看:76
本文介绍了我如何...这是我的代码,我想通过一次点击向所有客户发送邮件。我的代码如下..的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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;

    }

}





我的尝试:



我试过,这段代码工作正常但有问题,

如果有4个客户那么....

第一位客户获得4条相同的消息,

第二位客户获得3条相同的消息,

第三位收到300万条消息,最后一位收到1条消息br />


请帮我解决这个问题。因为我的英语不好。 ;)



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. ;)

推荐答案

此行正在为您的邮件添加新收件人

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



您需要在发送前清除收件人列表下一条消息。

否则

消息1发送给收件人1

消息2发送给收件人1和2

消息3发送给收件人1,2和3

消息4发送给收件人1,2,3和4


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


这篇关于我如何...这是我的代码,我想通过一次点击向所有客户发送邮件。我的代码如下..的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆