2014-09-06 93 views
0

我想在我的控制檯應用程序中發送電子郵件。我用:由SmtpClient發送電子郵件導致system.dll中出現System.InvalidOperationException

SmtpClient client = new SmtpClient(); 
        MailMessage msg = new MailMessage(); 
        MailAddress to = new MailAddress("[email protected]"); 
        MailAddress from = new MailAddress("[email protected]"); 
        msg.IsBodyHtml = true; 
        msg.Subject = "Mail Title"; 
        msg.To.Add(to); 
        msg.Body = "Your message"; 
        msg.From = from; 
        try { 
         client.Send(msg);//THIS CAUSES ERROR 
        } catch (InvalidOperationException e) { 
         Console.WriteLine(e); 
        } 

,它會導致:此代碼的

A first chance exception of type 'System.InvalidOperationException' occurred in System.dll 

撰文稱,應該加上:

<system.net> 
    <mailSettings> 
     <smtp deliveryMethod="Network"> 
     <network host="smtp.gmail.com" port="587" userName="your email address" password="your password" defaultCredentials="false" enableSsl="true" /> 
     </smtp> 
    </mailSettings> 
    </system.net> 

到Web.config中,但這不是ASP .NET MVC應用程序,我沒有看到任何Web配置。

+0

「這不是ASP .NET MVC應用程序,我沒有看到任何Web配置。」 - 然後添加一個app.config到你的項目中,並把配置放在那裏。 – Joe 2014-09-06 19:12:31

回答

1

如果不使用任何配置文件,則必須在代碼中配置SMTP客戶端。 例如:

SmtpClient smtp = new SmtpClient(); 
smtp.Host = "smtp.gmail.com"; 
smtp.UseDefaultCredentials = false; 
smtp.Credentials = System.Net.NetworkCredential("youremail", "yourpassword"); 
smtp.EnableSsl = true; 
+0

我得到這個:'錯誤1'System.Net.NetworkCredential'是一個'類型',它在給定的上下文中無效'你知道我在這裏缺少什麼嗎? – 2014-09-06 16:17:51

+0

我已編輯我的帖子。嘗試這樣,讓我知道 – 2014-09-06 17:24:02

+0

謝謝我已經解決它,忘了提及。我也是這樣做的。 – 2014-09-06 19:11:58

相關問題