c# - 使用 SmtpClient 发送邮件列表

标签 c# .net winforms

我在发送电子邮件列表时使用 SmtpClient 的 SendCompletedEventHandler。

SendCompletedEventHandler 仅在已发送列表中的所有电子邮件时调用。

我解释说,发送电子邮件时会调用 SendCompletedEventHandler。

我的代码有问题吗?

    public void SendAllNewsletters(List<string> recipients)
    {
        string mailText  = "My Text";
        foreach(string recipient in recipients)
        {
            //if this loop takes 10min then the first call to
            //SendCompletedCallback is after 10min
            SendNewsletter(mailText,recipient);
        }
    }

    public bool SendNewsletter(string mailText , string emailaddress)
    {

            SmtpClient sc = new SmtpClient(_smtpServer, _smtpPort);
            System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(_smtpuser, _smtppassword);
            sc.Credentials = SMTPUserInfo;
            sc.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);

            MailMessage mm = null;
            mm = new MailMessage(_senderemail, emailaddress );
            mm.IsBodyHtml = true;
            mm.Priority = MailPriority.Normal;
            mm.Subject = "Something";
            mm.Body = mailText ;
            mm.SubjectEncoding = Encoding.UTF8;
            mm.BodyEncoding = Encoding.UTF8;

            //Mail 
            string userState = emailaddress;
            sc.SendAsync(mm, userState);

            return true;
    }


    public void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
    {
        // Get the unique identifier for this asynchronous operation.
        String token = (string)e.UserState;
        if (e.Error != null)
        {
            _news.SetNewsletterEmailsisSent(e.UserState.ToString(), _newslettername, false, e.Error.Message); 
        }
        else
        {
            _news.SetNewsletterEmailsisSent(e.UserState.ToString(), _newslettername, true, string.Empty);
        }            
    }

最佳答案

您每次都在创建一个新的 SmtpClient 实例(然后重新分配处理程序)。使用范围更大的静态变量。

关于c# - 使用 SmtpClient 发送邮件列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2684415/

相关文章:

c# - 无法使用 NumericUpDown 更新 ZedGraph 中的 YAxis

c# - 解析Json字符串并根据C#中的属性排序

c# - 如何删除 MenuStrip 控件下绘制的白线?

c# - 引用自定义组件的设计时程序集

c# - 在 C# 中将多个 Parallel.ForEach 合并为一个

c# - 用于匹配短语中单个单词的正则表达式

.net - 在 OpenFileDialog (WindowsAPICodePack) 上设置 'My Computer' 位置

c# - 如何在维护域驱动设计架构的同时使用 WCF 服务设置 Ninject?

c# - 写入没有读取权限的文件

java - .net 的 GC.KeepAlive 的 Java 等价物是什么?