Sending e-mail by SmtpClient causes 'System.InvalidOperationException in system.dll

六眼飞鱼酱① 提交于 2020-01-07 06:24:54

问题


I wanted to send e-mail in my console application. I used:

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);
                    }

and it causes:

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

author of this code said that one should add:

<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>

to Web.config but this is not ASP .NET MVC application and I don't see any web config.


回答1:


You have to configure your SMTP client in code if you are not using any configuration file. For example:

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


来源:https://stackoverflow.com/questions/25701158/sending-e-mail-by-smtpclient-causes-system-invalidoperationexception-in-system

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!