Friday, June 26, 2009

C# SMTP Snippet

I recently provided this simple snippet to a colleague and thought I’d share it out. It includes a way to attach a local file or attach one generated on the fly.
using System;
using System.IO;
using System.Net.Mail;
using System.Text;
public static void SendEmail()
bool createFile = true;
string fileName = @"c:\boot.ini";
MailMessage mail = new MailMessage();
mail.IsBodyHtml = true;
mail.From = new MailAddress("");
mail.To.Add(new MailAddress(""));
mail.Subject = "Subject";
mail.Body = "Body";
if (createFile)
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] bytes = encoding.GetBytes("File Content Blah Blah Blah");
MemoryStream ms = new MemoryStream(bytes);
mail.Attachments.Add(new Attachment(ms, "FileTitle" + ".txt", "text/plain"));
mail.Attachments.Add(new Attachment(fileName));
SmtpClient smtpClient = new SmtpClient();
smtpClient.Host = "SMTPSERVERNAME";
catch (Exception ex)


1 comment:

  1. John - thanks. Saved me from having to figure it out by myself!