You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C#实现多SMTP服务器批量发送邮件给多收件人?

多SMTP服务器批量发邮件代码修改方案

我是C#新手,正在开发邮件发送工具,需要实现通过多个SMTP服务器逐个给多个收件人发送邮件。当前代码仅支持单个SMTP服务器发送,希望改用DataGridView中每行的SMTP配置(服务器地址、端口、用户名、密码、SSL设置)来实现该功能,求代码修改方案。

当前使用的代码如下:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    CheckForIllegalCrossThreadCalls = false;

    SmtpClient client = new SmtpClient();
    client.Timeout = 30000;
    client.AuthenticationMechanisms.Remove("XOAUTH2");

    BodyBuilder builder = new BodyBuilder();
    builder.HtmlBody = textBoxHTMLBody.Text;

    MimeMessage mail = new MimeMessage();
    mail.Subject = textBoxSubject.Text;
    mail.Body = builder.ToMessageBody();

    client.Connect(textBoxSMTP.Text, int.Parse(textBoxPORT.Text), CheckBoxSSL.Checked);
    client.Authenticate(textBoxUser.Text, textBoxPassword.Text);
    
    foreach (string email in listBoxEMails.Items)
    {
        mail.From.Add(new MailboxAddress("hello", textBoxUser.Text));
        mail.To.Add(new MailboxAddress("",email));
        client.Send(mail);

        Thread.Sleep(1000);
    }

    client.Disconnect(true);
}

核心修改思路

  • 提取SMTP配置实体类,统一存储每行的服务器信息
  • 遍历DataGridView所有行,读取可用的SMTP配置
  • 修复原代码中邮件收件人累加的问题,每次发送创建新邮件对象
  • 增加异常捕获,避免单个服务器出错中断整个流程

修改后的完整代码

// 定义SMTP配置实体类,用来存储DataGridView每行的配置信息
public class SmtpConfig
{
    public string Server { get; set; }
    public int Port { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public bool UseSsl { get; set; }
}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    CheckForIllegalCrossThreadCalls = false;

    // 1. 从DataGridView读取所有SMTP配置
    List<SmtpConfig> smtpConfigs = new List<SmtpConfig>();
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        // 跳过DataGridView的空行
        if (row.IsNewRow) continue;
        
        smtpConfigs.Add(new SmtpConfig
        {
            Server = row.Cells["ServerColumn"].Value?.ToString(),
            Port = int.TryParse(row.Cells["PortColumn"].Value?.ToString(), out int port) ? port : 25,
            Username = row.Cells["UsernameColumn"].Value?.ToString(),
            Password = row.Cells["PasswordColumn"].Value?.ToString(),
            UseSsl = bool.TryParse(row.Cells["SslColumn"].Value?.ToString(), out bool ssl) ? ssl : false
        });
    }

    // 2. 准备邮件基础内容(主题、正文只需创建一次)
    BodyBuilder builder = new BodyBuilder();
    builder.HtmlBody = textBoxHTMLBody.Text;
    string emailSubject = textBoxSubject.Text;

    // 3. 遍历每个SMTP服务器,给所有收件人发送邮件
    foreach (var config in smtpConfigs)
    {
        // 跳过配置不完整的行
        if (string.IsNullOrEmpty(config.Server) || string.IsNullOrEmpty(config.Username) || string.IsNullOrEmpty(config.Password))
            continue;

        // 使用using自动释放SmtpClient资源
        using (SmtpClient client = new SmtpClient())
        {
            client.Timeout = 30000;
            client.AuthenticationMechanisms.Remove("XOAUTH2");

            try
            {
                // 连接当前SMTP服务器
                client.Connect(config.Server, config.Port, config.UseSsl);
                client.Authenticate(config.Username, config.Password);

                // 遍历所有收件人发送
                foreach (string email in listBoxEMails.Items)
                {
                    if (string.IsNullOrEmpty(email)) continue;

                    // 每次发送创建新邮件对象,避免收件人累加
                    MimeMessage mail = new MimeMessage();
                    mail.Subject = emailSubject;
                    mail.Body = builder.ToMessageBody();
                    mail.From.Add(new MailboxAddress("hello", config.Username));
                    mail.To.Add(new MailboxAddress("", email));

                    client.Send(mail);
                    Thread.Sleep(1000);
                }

                client.Disconnect(true);
            }
            catch (Exception ex)
            {
                // 捕获异常,可根据需求改成UI提示或日志记录
                Console.WriteLine($"SMTP服务器 {config.Server} 发送失败: {ex.Message}");
            }
        }
    }
}

注意事项

  • 确保DataGridView的列名和代码中row.Cells["XXXColumn"]的名称一致,比如需创建ServerColumn(服务器)、PortColumn(端口)、UsernameColumn(用户名)、PasswordColumn(密码)、SslColumn(SSL开关)的列
  • 代码中增加了异常捕获,单个SMTP服务器出错不会影响其他服务器的发送流程
  • 每次发送创建新的MimeMessage,解决了原代码中收件人不断累加的问题

内容的提问来源于stack exchange,提问作者Aman Choudhary

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 13:27:20