2017-10-11 71 views
1

編程新手;我想要一個應用程序發送帶有附件的郵件,並在完成後自動關閉。使用下面的代碼,但它拋出了「異常未處理:System.ObjectDisposedException:「無法訪問已釋放的對象。」電子郵件應用程序錯誤:無法訪問處置對象(c#)

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("[email protected]", "[email protected]"); 
      message.To.Add("[email protected]"); 
      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("[email protected]", "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(); 
     } 
    } 
} 

}

+0

沒有ü嘗試this.Close(),而不是關閉()。首先,您需要檢查電子郵件是否使用郵件發送,然後關閉表單。您是否面臨關閉表單或發送電子郵件的問題? –

+0

請看這個https://stackoverflow.com/questions/2204698/send-email-with-attachment-from-winforms-app –

+0

嗨,郵件發送。問題是關閉窗體。謝謝。 – Ikenna

回答

0

這是因爲你正試圖接近的一種形式構造函數。我相信構造函數調用InitializeComponent。

其實你並不需要一個形式,嘗試普通類

class MailHelper 
{ 
    public void SendMail() 
    { 
      MailMessage message = new MailMessage("[email protected]", "[email protected]"); 
      message.To.Add("[email protected]"); 
      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("[email protected]", "password"); 
      client.EnableSsl = true; 

      // client.UseDefaultCredentials = true; 

      client.Send(message); 
    } 
} 

,你可以使用它像new MailHelper().SendMail();

相關問題