Duke Nuke
Duke Nuke

Reputation: 1925

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

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

SmtpClient client = new SmtpClient();
                    MailMessage msg = new MailMessage();
                    MailAddress to = new MailAddress("[email protected]");
                    MailAddress from = new MailAddress("[email protected]");
                    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.

Upvotes: 1

Views: 2435

Answers (1)

Daniel M
Daniel M

Reputation: 340

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;

Upvotes: 1

Related Questions