开发者

Need to send email using background worker process

开发者 https://www.devze.com 2023-02-16 03:56 出处:网络
I have code written for sending email in C#, but the application hangs up when the application is sending mails size of attachments more than 2 MB. I was advised to use background worker process for t

I have code written for sending email in C#, but the application hangs up when the application is sending mails size of attachments more than 2 MB. I was advised to use background worker process for the same by SO users.

I have gone thru the background worker process example from MSDN and google it also, but i don't know how to integrate in my code.

Please guide me in that...

thanks

UPDATED: Email-Code Added

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 mailH开发者_如何学JAVAost = 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;
    }
  }
}

I can't modify the code here as it is common method that is called whenever mail is to be sent from my application.


You could start a background thread to continuously loop and send email:

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
    }
}

Alternative way to do it:

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());
}

Specific to your example, you should replace the following:

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);
    }
}

with the following:

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

and further down, include:

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());
}


There's a great example of how to do this with a "Service Broker" in Chapter 8 of Richard Kiessig's book "Ultra-Fast ASP.NET."

Here's the link to the book on the publisher's website where you can download the sample code from the book. Again, chapter 8...

http://apress.com/book/view/9781430223832

0

精彩评论

暂无评论...
验证码 换一张
取 消