c# - 需要使用后台工作进程发送电子邮件

标签 c# winforms multithreading smtp backgroundworker

我用 C# 编写了用于发送电子邮件的代码,但是当应用程序发送邮件的附件大小超过 2 MB 时,应用程序挂断了。 SO 用户建议我使用后台工作进程。

我已经通过 MSDN 的后台工作进程示例进行了搜索,但我不知道如何将其集成到我的代码中。

请指导我...

谢谢

更新:添加了电子邮件代码

public static void SendMail(string fromAddress, string[] toAddress, string[] ccAddress, string[] bccAddress, string subject, string messageBody, bool isBodyHtml, ArrayList attachments, string host, string username, string pwd, string port)
{
  Int32 TimeoutValue = 0;
  Int32 FileAttachmentLength = 0;
  {
    try
    {
      if (isBodyHtml && !htmlTaxExpression.IsMatch(messageBody))
        isBodyHtml = false;
      // Create the mail message
      MailMessage objMailMsg;
      objMailMsg = new MailMessage();
      if (toAddress != null) {
        foreach (string toAddr in toAddress)
          objMailMsg.To.Add(new MailAddress(toAddr));
      }
      if (ccAddress != null) {
        foreach (string ccAddr in ccAddress)
          objMailMsg.CC.Add(new MailAddress(ccAddr));
      }
      if (bccAddress != null) {
        foreach (string bccAddr in bccAddress)
          objMailMsg.Bcc.Add(new MailAddress(bccAddr));
      }
      if (fromAddress != null && fromAddress.Trim().Length > 0) {
        //if (fromAddress != null && fromName.trim().length > 0)
        //    objMailMsg.From = new MailAddress(fromAddress, fromName);
        //else
        objMailMsg.From = new MailAddress(fromAddress);
      }
      objMailMsg.BodyEncoding = Encoding.UTF8;
      objMailMsg.Subject = subject;
      objMailMsg.Body = messageBody;
      objMailMsg.IsBodyHtml = isBodyHtml;
      if (attachments != null) {
        foreach (string fileName in attachments) {
          if (fileName.Trim().Length > 0 && File.Exists(fileName)) {
             Attachment objAttachment = new Attachment(fileName);
             FileAttachmentLength=Convert.ToInt32(objAttachment.ContentStream.Length);
             if (FileAttachmentLength >= 2097152) {
               TimeoutValue = 900000;
             } else {
                TimeoutValue = 300000;
             }
             objMailMsg.Attachments.Add(objAttachment);
             //objMailMsg.Attachments.Add(new Attachment(fileName)); 
           }
        }
      }
      //prepare to send mail via SMTP transport
      SmtpClient objSMTPClient = new SmtpClient();
      if (objSMTPClient.Credentials != null) { } else {
        objSMTPClient.UseDefaultCredentials = false;
        NetworkCredential SMTPUserInfo = new NetworkCredential(username, pwd);
        objSMTPClient.Host = host;
        objSMTPClient.Port = Int16.Parse(port);
        //objSMTPClient.UseDefaultCredentials = false;
        objSMTPClient.Credentials = SMTPUserInfo;
        //objSMTPClient.EnableSsl = true;
        //objSMTPClient.DeliveryMethod = SmtpDeliveryMethod.Network;
      }
      //objSMTPClient.Host = stmpservername;
      //objSMTPClient.Credentials
      //System.Net.Configuration.MailSettingsSectionGroup mMailsettings = null;
      //string mailHost = mMailsettings.Smtp.Network.Host;
      try {
        objSMTPClient.Timeout = TimeoutValue;
        objSMTPClient.Send(objMailMsg);
        //objSMTPClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
        objMailMsg.Dispose();
      }
      catch (SmtpException smtpEx) {
        if (smtpEx.Message.Contains("secure connection")) {
           objSMTPClient.EnableSsl = true;
           objSMTPClient.Send(objMailMsg);
        }
      }
    }
    catch (Exception ex)
    {
       AppError objError = new AppError(AppErrorType.ERR_SENDING_MAIL, null, null, new AppSession(), ex);
       objError.PostError();
       throw ex;
    }
  }
}

我无法修改此处的代码,因为这是从我的应用程序发送邮件时调用的常用方法。

最佳答案

您可以启动一个后台线程来不断循环和发送电子邮件:

private void buttonStart_Click(object sender, EventArgs e)
{
    BackgroundWorker bw = new BackgroundWorker();
    this.Controls.Add(bw);
    bw.DoWork += new DoWorkEventHandler(bw_DoWork);
    bw.RunWorkerAsync();
}

private bool quit = false;
void bw_DoWork(object sender, DoWorkEventArgs e)
{
    while (!quit)
    {
        // Code to send email here
    }
}

另一种方法:

private void buttonStart_Click(object sender, EventArgs e)
{
    System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
    client.SendCompleted += new System.Net.Mail.SendCompletedEventHandler(client_SendCompleted);
    client.SendAsync("from@here.com", "to@there.com", "subject", "body", null);
}

void client_SendCompleted(object sender, AsyncCompletedEventArgs e)
{
    if (e.Error == null)
        MessageBox.Show("Successful");
    else
        MessageBox.Show("Error: " + e.Error.ToString());
}

特定于您的示例,您应该替换以下内容:

try
{
    objSMTPClient.Timeout = TimeoutValue;
    objSMTPClient.Send(objMailMsg);
    //objSMTPClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
    objMailMsg.Dispose();
}
catch (SmtpException smtpEx)
{
    if (smtpEx.Message.Contains("secure connection"))
    {
        objSMTPClient.EnableSsl = true;
        objSMTPClient.Send(objMailMsg);
    }
}

具有以下内容:

objSMTPClient.Timeout = TimeoutValue;
objSMTPClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
objSMTPClient.SendAsync(objMailMsg, objSMTPClient);

再往下,包括:

void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
    if (e.Error == null)
        MessageBox.Show("Successful");
    else if (e.Error is SmtpException)
    {
        if ((e.Error as SmtpException).Message.Contains("secure connection"))
        {
            (e.UserState as SmtpClient).EnableSsl = true;
            (e.UserState as SmtpClient).SendAsync(objMailMsg, e.UserState);
        }
        else
            MessageBox.Show("Error: " + e.Error.ToString());
    }
    else
        MessageBox.Show("Error: " + e.Error.ToString());
}

关于c# - 需要使用后台工作进程发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5242306/

相关文章:

c# - Windows 窗体程序在运行查询时突然关闭。如何在错误停止/崩溃之前捕获错误?

c# - 如何在 C# winform 应用程序中将子窗口置于最前面?

java - 寻找开发互斥锁的解决方案

java - 锁定文件并读取它

c# - 启用片段级一致性时忽略 XML 模式验证?

c# - C#中的多线程CPU使用率

c# - 调用可能会在 catch 中抛出的方法

c# asp.net 'must declare the scalar variable' 问题

C# - winform - 如何在 app.config 中加密端点地址

java - 从随机持续时间获取平均值