【问题标题】:Need to send emails to multiple users需要向多个用户发送电子邮件
【发布时间】:2018-06-15 06:34:52
【问题描述】:

我开发了一个简单的警报系统,它将读取 SQL 中的表格并相应地发送电子邮件。该 SQL 表中有要发送的用户名、电子邮件地址和消息。系统将每 20 分钟读取一次表格,并根据用户各自的电子邮件地址向用户发送电子邮件。但目前系统仅向一位用户发送电子邮件。我想进一步开发这个系统,以便在一组完成后向多个用户发送电子邮件。我不知道该怎么做。有没有人可以帮助我解决这个问题。代码 sn -p 会更有助于理解。

下面是SQL表模板

Name  | Email              | Factory| AlertTime| Description
User1 | user1@mydomain.com | FAC1   | 01:50:00 | UserMessage1
User1 | user1@mydomain.com | FAC2   | 01:50:00 | UserMessage2
User1 | user1@mydomain.com | FAC3   | 03:00:00 | UserMessage3

User2 | user2@mydomain.com | FAC1   | 01:20:00 | UserMessage1
User2 | user2@mydomain.com | FAC2   | 01:50:00 | UserMessage2
User2 | user2@mydomain.com | FAC3   | 03:00:00 | UserMessage3

User3 | user3@mydomain.com | FAC1   |  01:20:00 | UserMessage1
User3 | user3@mydomain.com | FAC2   |  01:50:00 | UserMessage2
User3 | user3@mydomain.com | FAC3   |  03:00:00 | UserMessage3

下面是我的 C# 代码

    using System;
    using System.Timers;
    using System.Windows.Forms;
    using System.Net.Mail;
    using System.Data;
    using System.Speech.Synthesis;
    using System.Collections.Generic;

    namespace Alerts
    {
        public partial class frmAlerts : Form
        {
            SpeechSynthesizer speechSynthesizerObj;
            Common ComMsg = new Common();
            DataSet DatMsg = new DataSet();
            AlertException error = new AlertException();
            List<string> AlertList = new List<string>();
            string ToName;
            string ToEmail;
            string TotMsg;

            public frmAlerts()
            {
                InitializeComponent();
                this.WindowState = FormWindowState.Minimized;
            }
            private void frmAlerts_Load(object sender, EventArgs e)
            {
                try
                {
                    System.Timers.Timer timer = new System.Timers.Timer(20 * 60 * 1000);
                    timer.Elapsed += new ElapsedEventHandler(SendAlerts);
                    timer.Start();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error in application Load: " + ex.Message);
                }

            }
            public void SendAlerts(object source, ElapsedEventArgs e)
            {
                try
                {
                    DatMsg = ComMsg.ReturnDataSet("SELECT RptAlertRecipient.Name,  RptAlertRecipient.Email,  RptAlerts.Factory,  RptAlerts.AlertTime,  RptAlerts.Description " +
                                             "FROM RptAlerts " +
                                             "INNER JOIN RptAlertTypes ON  RptAlerts.AlertTypeID = RptAlertTypes.ID " +
                                             "INNER JOIN RptAlertType_RecipientMapping ON  RptAlertTypes.ID = RptAlertType_RecipientMapping.AlertTypeID " +
                                             "INNER JOIN RptAlertRecipient ON  RptAlertType_RecipientMapping.AlertRecipientID = RptAlertRecipient.ID " +
                                             "WHERE RptAlertRecipient.Name= 'User1' " +
                                             "ORDER BY RptAlertRecipient.Name ASC");
                    for (int j = 0; j < DatMsg.Tables[0].Rows.Count; j++)
                    {
                        ToEmail = DatMsg.Tables[0].Rows[j].ItemArray.GetValue(1).ToString();
                        ToName = DatMsg.Tables[0].Rows[j].ItemArray.GetValue(0).ToString();
                        AlertList.Add(DatMsg.Tables[0].Rows[j].ItemArray.GetValue(4).ToString() + "<br/>");
                        TotMsg = (j + 1).ToString();
                    }

                    string to = ToEmail;
                    string from = "helpdesk@mydomain.com";
                    string subject = "Alert In Time : You Have "+TotMsg+ " Alerts";
                    string msgBody = "Dear " + ToName + ",<br/><br/>";
                    msgBody += "<b>You Have " + TotMsg + " Alerts</b><br/><br/>";
                    msgBody += string.Join("<br/>", AlertList);
                    msgBody += "<br/><br/>Regards<br/>Sent by Alert Service<br/>(Please do not reply to this email.)";
                    MailMessage msg = new MailMessage(from, to, subject, msgBody);
                    msg.IsBodyHtml = true;
                    SmtpClient clnt = new SmtpClient("outlook.mydomain.local", 25);
                    clnt.EnableSsl = false;
                    clnt.Credentials = new System.Net.NetworkCredential("helpdesk@mydomain.com", "password");
                    clnt.Send(msg);
                }
                catch (Exception ex)
                {
                    error.ExceptionMessage = ex.ToString();//gets the exception message to a separate class
                    speechSynthesizerObj = new SpeechSynthesizer();
                    speechSynthesizerObj.SpeakAsync(ex.Message);//Speaks the Error
                }
            }

        }
    }

【问题讨论】:

  • 如果您删除"WHERE RptAlertRecipient.Name= 'User1' " + 部分,您可以向所有人发送邮件。不过,请重新考虑您的 for 循环,因为您只是覆盖了您找到的每条记录的值。如果您想发送多个电子邮件,请在该循环内发送电子邮件。
  • 您的期望是什么?您想连接所有警报消息、警报计数,然后只向每组(user1、user2、user3)发送一封电子邮件还是每组发送 3 封电子邮件?
  • @oerkelens 我尝试删除 WHERE RptAlertRecipient.Name= 'User1' " + 部分,然后它只会发送给最后一个用户。
  • @Kavin 我需要检查用户名并通过给定的电子邮件地址在电子邮件中发送属于该用户的所有相关消息。
  • 你有没有试过把邮件发送逻辑放在那个for循环里面?

标签: c# sql email


【解决方案1】:

我想您当前的代码只向列表中的最后一个用户发送邮件?

您必须在 for 循环中包含生成和发送邮件的代码。

for (int j = 0; j < DatMsg.Tables[0].Rows.Count; j++)
{
    ToEmail = DatMsg.Tables[0].Rows[j].ItemArray.GetValue(1).ToString();
    ToName = DatMsg.Tables[0].Rows[j].ItemArray.GetValue(0).ToString();
    AlertList.Add(DatMsg.Tables[0].Rows[j].ItemArray.GetValue(4).ToString() + "<br/>");
    TotMsg = (j + 1).ToString();

    string to = ToEmail;
    string from = "helpdesk@mydomain.com";
    string subject = "Alert In Time : You Have "+TotMsg+ " Alerts";
    string msgBody = "Dear " + ToName + ",<br/><br/>";
    msgBody += "<b>You Have " + TotMsg + " Alerts</b><br/><br/>";
    msgBody += string.Join("<br/>", AlertList);
    msgBody += "<br/><br/>Regards<br/>Sent by Alert Service<br/>(Please do not reply to this email.)";
    MailMessage msg = new MailMessage(from, to, subject, msgBody);
    msg.IsBodyHtml = true;
    SmtpClient clnt = new SmtpClient("outlook.mydomain.local", 25);
    clnt.EnableSsl = false;
    clnt.Credentials = new System.Net.NetworkCredential("helpdesk@mydomain.com", "password");
    clnt.Send(msg);
}

【讨论】:

  • 他不应该在foreach之外只使用一个SmtpClient对象而不是每次都创建一个新对象吗?
  • 这是一个很好的观点,这段代码可能还可以进一步改进。但这不是问题。
  • 是的,但solve the problem in a right way 而不是just solve the problem 总是一个好习惯
  • 如果我在循环中使用 SmtpClient,它会一一发送电子邮件。但这不是问题。
【解决方案2】:

我找到了解决方案。我对代码做了一些更改,现在它按照我希望的方式工作。下面是我的代码。感谢大家的帮助。

    using System;
    using System.Data;
    using System.Timers;
    using System.Net.Mail;
    using System.Windows.Forms;
    using System.Speech.Synthesis;
    using System.Collections.Generic;

    namespace Alerts
    {
        public partial class frmAlerts : Form
        {
            SpeechSynthesizer speechSynthesizerObj;
            Common ComMsg = new Common();
            DataSet DatMsg = new DataSet();
            DataSet DatNames = new DataSet();
            AlertException error = new AlertException();
            List<string> AlertList = new List<string>();
            string ToName;
            string ToEmail;
            string TotMsg;
            string _Name;
            public frmAlerts()
            {
                InitializeComponent();
                this.WindowState = FormWindowState.Minimized;
            }
            private void frmAlerts_Load(object sender, EventArgs e)
            {
                try
                {
                    System.Timers.Timer timer = new System.Timers.Timer(20 * 60 * 1000);
                    timer.Elapsed += new ElapsedEventHandler(SendAlerts);
                    timer.Start();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error in application Load: " + ex.Message);
                    SendtoAdmin();
                }
            }
            public void SendAlerts(object source, ElapsedEventArgs e)
            {
                try
                {
                    DatNames = ComMsg.ReturnDataSet("SELECT Name FROM RptAlertRecipient ORDER BY Name DESC");

                    for (int i = 0; i < DatNames.Tables[0].Rows.Count; i++)
                    {
                        _Name = DatNames.Tables[0].Rows[i].ItemArray.GetValue(0).ToString();

                        DatMsg = ComMsg.ReturnDataSet("SELECT RptAlertRecipient.Name,  RptAlertRecipient.Email,  RptAlerts.Factory,  RptAlerts.AlertTime,  RptAlerts.Description " +
                                           "FROM RptAlerts " +
                                           "INNER JOIN RptAlertTypes ON  RptAlerts.AlertTypeID = RptAlertTypes.ID " +
                                           "INNER JOIN RptAlertType_RecipientMapping ON  RptAlertTypes.ID = RptAlertType_RecipientMapping.AlertTypeID " +
                                           "INNER JOIN RptAlertRecipient ON  RptAlertType_RecipientMapping.AlertRecipientID = RptAlertRecipient.ID " +
                                           "WHERE RptAlertRecipient.Name ='" + _Name + "'" +
                                           "ORDER BY RptAlertRecipient.Name DESC");
                        for (int j = 0; j < DatMsg.Tables[0].Rows.Count; j++)
                        {
                            ToEmail = DatMsg.Tables[0].Rows[j].ItemArray.GetValue(1).ToString();
                            ToName = DatMsg.Tables[0].Rows[j].ItemArray.GetValue(0).ToString();
                            AlertList.Add(DatMsg.Tables[0].Rows[j].ItemArray.GetValue(4).ToString() + "<br/>");
                            TotMsg = (j + 1).ToString();
                        }
                        string to = ToEmail;
                        string from = "helpdesk@mydomain.com";
                        string subject = "Alert In Time : You Have " + TotMsg + " Alerts";
                        string msgBody = "Dear " + ToName + ",<br/><br/>";
                        msgBody += "<b>You Have " + TotMsg + " Alerts</b><br/><br/>";
                        msgBody += string.Join("<br/>", AlertList);
                        msgBody += "<br/><br/>Regards<br/>Sent by Alert Service<br/>(Please do not reply to this email.)";
                        MailMessage msg = new MailMessage(from, to, subject, msgBody);
                        msg.IsBodyHtml = true;
                        SmtpClient clnt = new SmtpClient("outlook.mydomain.local", 25);
                        clnt.EnableSsl = false;
                        clnt.Credentials = new System.Net.NetworkCredential("helpdesk@mydomain.com", "password");
                        clnt.Send(msg);
                        AlertList.Clear();
                    }
                }
                catch (Exception ex)
                {
                    error.ExceptionMessage = ex.ToString();
                    speechSynthesizerObj = new SpeechSynthesizer();
                    speechSynthesizerObj.SpeakAsync(ex.Message);//Speaks the Error
                    SendtoAdmin();
                }
            }
            #region SendMails
            protected void SendtoAdmin()
            {
                //Send mail to Admin
                string to = "admin@mydomain.com";
                string from = "helpdesk@mydomain.com";
                string subject = "System Failure";
                string msgBody = "Dear Admin,<br/><br/>System Failure in Alert System.<br/>Please Attend Immediately.<br/>"+ error.ExceptionMessage + "<br/><br/>Regards<br/>Sent By Alert System";
                MailMessage msg = new MailMessage(from, to, subject, msgBody);
                msg.IsBodyHtml = true;
                SmtpClient clnt = new SmtpClient("outlook.mydomain.local", 25);
                clnt.EnableSsl = false;
                clnt.Credentials = new System.Net.NetworkCredential("helpdesk@mydomain.com", "sl@ithd");
                clnt.Send(msg);
            }
            #endregion      
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-11
    • 2012-02-22
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 2012-07-22
    相关资源
    最近更新 更多