SmtpClient发送电子邮件导致';System.dll中的System.InvalidOperationEx
本文关键字:System dll 中的 InvalidOperationEx 电子邮件 SmtpClient | 更新日期: 2023-09-27 18:21:05
我想在控制台应用程序中发送电子邮件。我用过:
SmtpClient client = new SmtpClient();
MailMessage msg = new MailMessage();
MailAddress to = new MailAddress("informatyka4445@wp.pl");
MailAddress from = new MailAddress("informatyka4444@wp.pl");
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配置。
如果不使用任何配置文件,则必须用代码配置SMTP客户端。例如:
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.UseDefaultCredentials = false;
smtp.Credentials = System.Net.NetworkCredential("youremail", "yourpassword");
smtp.EnableSsl = true;