Sending e-mail by SmtpClient causes 'System.In

2019-09-05 02:52发布

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条回答
家丑人穷心不美
2楼-- · 2019-09-05 03:22

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;
查看更多
登录 后发表回答