Send an Email via SMTP with C#

For whatever reason the web is filled with outdated examples of sending email with C#. This an example using .NET 2.0

First, be sure to import the Mail libs at the top of your class:

using System.Net.Mail;

Then in your code where the email will be sent:

MailMessage msg = new MailMessage();
msg.From = new MailAddress("from@address.com");
msg.To.Add(new MailAddress("to@address.com"));
msg.Subject = "message subject";
msg.Body = "message body";

SmtpClient smtp = new SmtpClient("your.smtp.host");
smtp.Send(msg);

That should do it. Feel free to post comments.

4 Responses to “Send an Email via SMTP with C#”

  1. Nhilesh Baua November 29, 2007 at 2:08 am #

    I am using almost same code in a winform application, however I am facing a very weird problem.

    I am trying to send the mails to around 200 mail ids at once but unless I close the application the mails are not sent actually. As soon as i close the application norton antivirus scans the mails which are stored in “Queue” folder one by one.

    I want the mails should be sent and cleared as soon as the send button is clicked.

    Also one BIG problem is this class does not provide with the exact exception occoured if the mail is not sent due to some reason.

    Any Ideas?

    Regards
    Nhilesh Baua

  2. Jason December 1, 2007 at 2:42 am #

    Hey Nhilesh, it sounds like the problem is not with your application, rather with Norton – or possibly your smtp host. The mail should go out as soon as you call the send() method.

    One thing you might also try, send the email asynchronously and you can attach an event listener when the SendCompleted event is fired. There is some sample code to do that on this page – http://msdn2.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx

  3. yousef April 5, 2009 at 6:43 pm #

    what should i fill the smtpClient method ?
    “your.smtp.host” ! !
    i dont understand

    can any one help me plz . .

    • Jason April 7, 2009 at 2:03 pm #

      hi yousef, you can try “localhost” as a guess but if that doesn’t work your host company or network admin would need to give you the correct host name. if you are the network admin then you would need to look into installing an SMTP server.

Leave a Reply

Please leave these two fields as-is: