none
Cannot access a disposed object. Object name : System.Net.Mail.MailMessage RRS feed

  • Question

  • Hi,

    I am trying to send email message in C# using this MSDN article:

    http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient(v=vs.110).aspx

    but I am getting this error:

    Cannot access a disposed object. Object name : System.Net.Mail.MailMessage

    can anyone help please...

    private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
    {
        // Get the unique identifier for this asynchronous operation.
        String token = (string)e.UserState;
    
        if (e.Cancelled)
        {
            Console.WriteLine("[{0}] Send canceled.", token);
        }
        if (e.Error != null)
        {
            MessageBox.Show(String.Format("[{0}] {1}", token, e.Error.ToString()));
        }
        else
        {
            Console.WriteLine("Message sent.");
        }
    
        mailSent = true;
    }
            
    private static void send_message()
    {
        // Command line argument must the the SMTP host.
        SmtpClient client = new SmtpClient("smtp.gmail.com");
        client.Port = 587;
        client.Credentials = new System.Net.NetworkCredential("it@mydomain.com", "my_password");
        client.EnableSsl = true;
    
        // Specify the e-mail sender. 
        // Create a mailing address that includes a UTF8 character 
        // in the display name.
        MailAddress from = new MailAddress("it@mydomain.com", "My" + (char)0xD8 + " Company", System.Text.Encoding.UTF8);
        // Set destinations for the e-mail message.
        MailAddress to = new MailAddress("jassim@mydomain.com");
        // Specify the message content.
        MailMessage message = new MailMessage(from, to);
        message.Body = "This is a test e-mail message sent by an application. ";
        // Include some non-ASCII characters in body and subject. 
        string someArrows = new string(new char[] { '\u2190', '\u2191', '\u2192', '\u2193' });
        message.Body += Environment.NewLine + someArrows;
        message.BodyEncoding = System.Text.Encoding.UTF8;
        message.Subject = "test message 1" + someArrows;
        message.SubjectEncoding = System.Text.Encoding.UTF8;
        // Set the method that is called back when the send operation ends.
        client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
        // The userState can be any object that allows your callback  
        // method to identify this send operation. 
        // For this example, the userToken is a string constant. 
        string userState = "test message1";
        client.SendAsync(message, userState);
        Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.");
        string answer = Console.ReadLine();
        // If the user canceled the send, and mail hasn't been sent yet, 
        // then cancel the pending operation.
    
        // if (answer.StartsWith("c") && mailSent == false)
        // {
            // client.SendAsyncCancel();
        // }
    
        // Clean up.
        message.Dispose();
        Console.WriteLine("Goodbye.");
    }
    
    private void btnSend_Click(object sender, EventArgs e)
    {
        // XtraMessageBox.Show("You are about to send this message to all contacts!", "Send", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    
        if (XtraMessageBox.Show("Are you sure you want to send this message to all contacts now?", "Send", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
        {
            send_message();
        }
    }
    

    Thursday, November 13, 2014 7:34 AM

Answers

  • You shouldnt be disposing the message in this same method in which you send the message. The send is asynchronous. You can delete the message only after the send is completed.

    You should register a call back for "client.SendCompleted" and delete the message there.

    Thursday, November 13, 2014 8:26 AM

All replies

  • You shouldnt be disposing the message in this same method in which you send the message. The send is asynchronous. You can delete the message only after the send is completed.

    You should register a call back for "client.SendCompleted" and delete the message there.

    Thursday, November 13, 2014 8:26 AM
  • Does the class has to be in a static? or it can be a normal private void class?

    Thursday, November 13, 2014 10:11 AM
  • Does the class has to be in a static? or it can be a normal private void class?

    You can have normal private void method. And as "Sezhiyan" mentioned move "message.Dispose()" method to SendCompletedCallback function.

    Gaurav Khanna | Microsoft VB.NET MVP | Microsoft Community Contributor

    Thursday, November 13, 2014 11:28 AM