sending mails with SmtpClient

15,032

Solution 1

Always consult the documentation. The SmptClient has three constructors.

SmtpClient()
SmtpClient(String)
SmtpClient(String, Int32)

If you choose the last one, then your code would look like the following, for gmail:

SmtpClient client = new SmtpClient("smtp.gmail.com", 587);

You could also use the first constructor and set properties instead.

SmtpClient smtp = new SmtpClient();
smtp.Port = 587; 
smtp.EnableSsl = true;
smtp.Credentials = new NetworkCredential("<email_from>",  "password");
smtp.Host = "smtp.gmail.com";   

Solution 2

You can specify the SMTP host and port in code as others have suggested.

But if you're always using the same host and port, it's probably easier and more flexible to use the default SmtpClient constructor, and specify the host and port in the <smtp> element of your application configuration file:

using(var smtpClient = new SmtpClient())
{
    ...
}


<system.net>
    <mailSettings>
        <smtp deliveryMethod="network" from="[email protected]">
            <network 
                 host="localhost"
                 port="25"
                 defaultCredentials="true"
            />
        </smtp>
    </mailSettings>
<system.net>

One advantage of this is that you can use a different configuration in your development/test environment, such as the one below, which will avoid sending unwanted mails to your system's mail recipients without any code changes.

<smtp deliveryMethod="SpecifiedPickupDirectory" from="[email protected]">
  <network host="localhost"/>
  <specifiedPickupDirectory pickupDirectoryLocation="C:\temp\mail\"/>
</smtp>

Solution 3

This is your host and optional port.

For example:

SmtpClient client = new SmtpClient("mail.domain.com", 123);

For more information, you should read the MSDN documentation for this class:

http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx

Share:
15,032
Kira
Author by

Kira

Updated on June 06, 2022

Comments

  • Kira
    Kira almost 2 years

    This is my first time to write a program that sends mails. I don't know what to put in the SMTP client constructor :

    SmtpClient client = new SmtpClient(????);
    

    Can anybody help?