1

New to programming; I want an app to send mails with attachments and close automatically as soon as it's done. Using the code below but it throws up the "Exception Unhandled: System.ObjectDisposedException: 'Cannot access a disposed object.'"

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Mail;

namespace Automail
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        {
            MailMessage message = new MailMessage("abc@xyz.com", "bcd@xyz.com");
            message.To.Add("abc@gmail.com");
            message.Subject = "Exeption Reports";
            message.Body = @"Find attached generated exception reports.";
            message.Attachments.Add(new Attachment("C:/New folder/STOCKS_NOT_MOVED.txt"));
            SmtpClient client = new SmtpClient();
            client.Host = "smtp.xyz.com";
            client.Port = 25;
            client.Credentials = new NetworkCredential("abc@xyz.com", "password");
            client.EnableSsl = true;

            // client.UseDefaultCredentials = true;

            try
            {
                client.Send(message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception caught in SendEmail(): {0}",
                        ex.ToString());
                MessageBox.Show("Goodbye!");
            }
            Close();
        }
    }
}

}

Ikenna
  • 35
  • 5

1 Answers1

0

This happens because you are trying to close a form in the constructor. InitializeComponent is called from constructor I believe.

actually you do not need a form, try ordinary class

class MailHelper
{
    public void SendMail()
    {
            MailMessage message = new MailMessage("abc@xyz.com", "bcd@xyz.com");
            message.To.Add("abc@gmail.com");
            message.Subject = "Exeption Reports";
            message.Body = @"Find attached generated exception reports.";
            message.Attachments.Add(new Attachment("C:/New folder/STOCKS_NOT_MOVED.txt"));
            SmtpClient client = new SmtpClient();
            client.Host = "smtp.xyz.com";
            client.Port = 25;
            client.Credentials = new NetworkCredential("abc@xyz.com", "password");
            client.EnableSsl = true;

            // client.UseDefaultCredentials = true;

            client.Send(message);
    }
}

you can use it like new MailHelper().SendMail();

oleksa
  • 3,688
  • 1
  • 29
  • 54