通过SmtpClient发送电子邮件会导致system.dll中出现'System.InvalidOperationException

时间:2014-09-06 14:14:49

标签: c# .net web-config smtp console-application

我想在我的控制台应用程序中发送电子邮件。我用过:

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配置。

1 个答案:

答案 0 :(得分:1)

如果您不使用任何配置文件,则必须在代码中配置SMTP客户端。 例如:

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