Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4039982
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T12:41:31+00:00 2026-05-20T12:41:31+00:00

I have code written for sending email in C#, but the application hangs up

  • 0

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

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

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T12:41:32+00:00Added an answer on May 20, 2026 at 12:41 pm

    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());
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have written some code in my VB.NET application to send an HTML e-mail
I have the source code of an application written in C++ and I just
I have written following code for the client of RMI. But getting java.rmi.ConnectException: Connection
I have written code that automatically creates CSS sprites based on the IMG tags
I have a code snippet written in PHP that pulls a block of text
I have some code I've written in PHP for consuming our simple webservice, which
Put it another way: what code have you written that cannot fail. I'm interested
I have just been re-working an old bit of compiler-like code written using bison.
I have written jQuery code, in files Main.html and ajax.php . The ajax.php file
We’ve found that the unit tests we’ve written for our C#/C++ code have really

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.