使用从数据库列中检出的电子邮件发送多封电子邮件

时间:2015-04-24 01:57:51

标签: c# .net winforms

我正在尝试编写一个Windows窗体应用程序,其中我需要向用户列表发送电子邮件。从数据库表返回/检索用户列表。我可以向一个用户发送电子邮件,但我无法在多个用户上复制/使用相同的逻辑。

这是我用来向单个用户发送电子邮件的代码:

class MailModule
    {
        public static void CreateMessage(string Server, int Port, string From, string to, string Subject, string Body)
        {


            System.Net.NetworkCredential basicAuthenticationInfo = new System.Net.NetworkCredential("username", "password");

            MailMessage message = new MailMessage(From, to, Subject, Body);
            SmtpClient client = new SmtpClient(Server);
            client.Port = Port;
            client.Credentials = basicAuthenticationInfo;
            try
            {

                client.Send(message);
                MessageBox.Show("Shout Sent", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                message.Dispose();
            }
            catch (Exception ex)
            {
                message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                MessageBox.Show(message.DeliveryNotificationOptions.ToString());
                MessageBox.Show(ex.Message);
            }
        }


    } 

3 个答案:

答案 0 :(得分:0)

您可以使用多线程发送消息:

var tasks = new List<Task>();
foreach(var mailTo in mailList)
{
   var task =  Task.Factory.StartNew(() => CreateMessage(server, port, from, mailTo, subject, body);

   tasks.Add(task);
}

// You can wait till all tasks are done

答案 1 :(得分:0)

假设您要将相同的消息发送给多个收件人。

使用MailMessage集合添加多个地址,而不是使用To构造函数。

class MailModule
{
    public static void CreateMessage(string Server, int Port, string From, IList<string> to, string Subject, string Body)
    {


        System.Net.NetworkCredential basicAuthenticationInfo = new System.Net.NetworkCredential("username", "password");

        var message = new MailMessage();

        message.From = new MailAddress(From);
        message.Subject = subject;
        message.Body = body;
        to.ForEach(x => message.To.Add(x));

        SmtpClient client = new SmtpClient(Server);
        client.Port = Port;
        client.Credentials = basicAuthenticationInfo;
        try
        {

            client.Send(message);
            MessageBox.Show("Shout Sent", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
            message.Dispose();
        }
        catch (Exception ex)
        {
            message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
            MessageBox.Show(message.DeliveryNotificationOptions.ToString());
            MessageBox.Show(ex.Message);
        }
    }


}

答案 2 :(得分:0)

也许您需要在每次发送电子邮件之间设置一些延迟,因为服务器在这段时间内无法发送这么多电子邮件。