My Technical Notes

Thursday, 12 September 2013

Sending an email with C#

Firstly add the using statement for System.Net.Mail namespace:


using System.Net.Mail;

The following code is what you can use to send a test email message:


MailMessage message = new MailMessage();

// *** start of parameters
string from = "xxx@xxx.com";
string to = "yyy@yyy.com";
string subject = "my subject";
string body = "my body";
string attachmentPath = null /* set this to a path if you want */;
// *** end of parameters

message.From = new MailAddress(from);
message.To.Add(new MailAddress(to));
message.Subject = subject;
message.Body = body;
message.IsBodyHtml = false /* set to true if using html */;

if (attachmentPath != null)
{
    message.Attachments.Add(new Attachment(attachmentPath));
}

using (SmtpClient client = new SmtpClient(/* specifying host here or in config */))
{
    client.Send(message);
}

The following is the configuration which is needed (unless you specify the host and/or port in the SmtpClient constructor):


<system.net>
  <mailSettings>
    <smtp>
      <network host="localhost" />
    </smtp>
  </mailSettings>
</system.net>

If you want the emails to end up in a folder, later for inspection, then we can specify an IIS pickup directory:


<system.net>
  <mailSettings>
    <smtp deliveryMethod="SpecifiedPickupDirectory">
      <specifiedPickupDirectory pickupDirectoryLocation="C:\Temp\MyEmailsFolder" />
    </smtp>
  </mailSettings>
</system.net>

No comments: