【问题标题】:Sending e-mail by SmtpClient causes 'System.InvalidOperationException in system.dll通过 SmtpClient 发送电子邮件会导致 system.dll 中出现“System.InvalidOperationException”
【发布时间】:2014-10-31 07:25:14
【问题描述】:

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

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

【问题讨论】:

  • "这不是 ASP .NET MVC 应用程序,我没有看到任何 Web 配置。" - 然后将 app.config 添加到您的项目中,并将配置放在那里。

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


【解决方案1】:

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

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

【讨论】:

  • 我得到了这个:Error 1 'System.Net.NetworkCredential' is a 'type', which is not valid in the given context 你知道我这里缺少什么吗?
  • 我已经编辑了我的帖子。试试这样,让我知道
  • 谢谢我已经解决了,忘了提。我也这样做了。
猜你喜欢
  • 1970-01-01
  • 2021-06-23
  • 2019-12-02
  • 2015-02-26
  • 1970-01-01
  • 1970-01-01
  • 2022-06-13
相关资源
最近更新 更多