Search code examples
c#email

Sending E-mail using C#


I need to send email via my C# app.

I come from a VB 6 background and had a lot of bad experiences with the MAPI control. First of all, MAPI did not support HTML emails and second, all the emails were sent to my default mail outbox. So I still needed to click on send receive.

If I needed to send bulk html bodied emails (100 - 200), what would be the best way to do this in C#?


Solution

  • You could use the System.Net.Mail.MailMessage class of the .NET framework.

    You can find the MSDN documentation here.

    Here is a simple example (code snippet):

    using System.Net;
    using System.Net.Mail;
    using System.Net.Mime;
    
    ...
    try
    {
    
       SmtpClient mySmtpClient = new SmtpClient("my.smtp.exampleserver.net");
    
        // set smtp-client with basicAuthentication
        mySmtpClient.UseDefaultCredentials = false;
       System.Net.NetworkCredential basicAuthenticationInfo = new
          System.Net.NetworkCredential("username", "password");
       mySmtpClient.Credentials = basicAuthenticationInfo;
    
       // add from,to mailaddresses
       MailAddress from = new MailAddress("[email protected]", "TestFromName");
       MailAddress to = new MailAddress("[email protected]", "TestToName");
       MailMessage myMail = new System.Net.Mail.MailMessage(from, to);
    
       // add ReplyTo
       MailAddress replyTo = new MailAddress("[email protected]");
       myMail.ReplyToList.Add(replyTo);
    
       // set subject and encoding
       myMail.Subject = "Test message";
       myMail.SubjectEncoding = System.Text.Encoding.UTF8;
    
       // set body-message and encoding
       myMail.Body = "<b>Test Mail</b><br>using <b>HTML</b>.";
       myMail.BodyEncoding = System.Text.Encoding.UTF8;
       // text or html
       myMail.IsBodyHtml = true;
    
       mySmtpClient.Send(myMail);
    }
    
    catch (SmtpException ex)
    {
      throw new ApplicationException
        ("SmtpException has occured: " + ex.Message);
    }
    catch (Exception ex)
    {
       throw ex;
    }