How to send emails in .NET part 1: basics of MailMessage

We’ll look at techniques around sending emails in .NET in this series of short posts.

If your single aim is to send a plain text email with no attachments then it’s very simple. The System.Net.Mail package includes most objects you’ll need for emailing but the following 2 are probably the most important:

  • MailMessage
  • SmtpClient

You use the MailMessage object to construct the message. Example:

string from = "";
string to = "";
string subject = "This is the subject";
string plainTextBody = "This is a great message.";
MailMessage mailMessage = new MailMessage(from, to, subject, plainTextBody);

The fields, like “from” and “to” are probably easy to understand.

For sending the message you’ll need a valid SMTP server which is needed for the SmtpClient object:

string smtpServer = "";
SmtpClient client = new SmtpClient(smtpServer);

This will send the email in a sequential manner, i.e. Send blocks the code until it returns.

SmtpClient.Send has an overload which enables you to bypass the creation of MailMessage entirely:

client.Send(from, to, subject, plainTextBody);

The MailMessage object internally validates the email address so you don’t need to worry about some magic regex string. E.g. the following will throw a FormatException:

MailMessage mm = new MailMessage("helloFrom", "helloTo");

That’s it for starters. We’ll look at emailing in a lot more depth in the upcoming parts.

Read all posts related to emailing in .NET here.

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

14 Responses to How to send emails in .NET part 1: basics of MailMessage

  1. Henry Fatino says:

    Great post. Maybe you could do one with adding a CalendarEvent as an attachment.

    • Andras Nemes says:

      Henry, I’ll take it up in one of the upcoming posts on emailing in .NET.

    • Andras Nemes says:

      Just to make sure I’m on the right track. Do you mean this CalendarEvent class?

      • Stefan Ossendorf says:

        Hi Henry,

        just add a new Attachment with your stream and ContentType = “text/calendar”.

      • Andras Nemes says:

        Stefan, thanks a lot for your input.

      • henry says:

        Thanks all,
        my solution

        public string SendEventEmailAttachment(Event storeEvent)
        if (storeEvent.StartTime == null) return string.Empty;

        var mailDefinition = new MailDefinition
        BodyFileName = Url.Content(“~/EmailTemplates/EventMeeting.html”),
        IsBodyHtml = true,
        From = “”

        var from = new MailAddress(“”, “Field Service Tools Event”);
        var to = new MailAddress(this.AspNetUser.Email, this.AspNetUser.UserName);

        var mergeFields = new Dictionary
        {“”, storeEvent.Store.Name},
        {“”, storeEvent.Store.Address.Address1},
        {“”, storeEvent.Store.Address.City},
        {“”, storeEvent.Store.Address.State},
        {“”, storeEvent.Store.Address.ZipCode},
        {“”, storeEvent.StartTime.ToString()},
        {“”, storeEvent.EndTime.ToString()},
        {“”, storeEvent.Activity.Name},
        {“”, storeEvent.Store.Address.Latitude.ToString()},
        {“”, storeEvent.Store.Address.Longitude.ToString()},
        {“”, storeEvent.ID.ToString(CultureInfo.InvariantCulture)},
        {“”, storeEvent.Store.ID.ToString(CultureInfo.InvariantCulture)}

        using (var stream = new MemoryStream())
        using (var writer = new StreamWriter(stream))

        using (var mailMessage = mailDefinition.CreateMailMessage(“”, mergeFields, new System.Web.UI.Control()))
        mailMessage.From = from;
        mailMessage.Subject = String.Format(“{0} at {1}”, storeEvent.Activity.Name, storeEvent.Store.Name);
        mailMessage.IsBodyHtml = true;

        stream.Position = 0; // read from the start of what was written

        mailMessage.Attachments.Add(new Attachment(stream, string.Format(“EventCalendar-{0}.ics”, storeEvent.ID), “text/calendar”));

        var smtpMail = SmtpConfiguration.SetupSmtpClient();
        return string.Empty;

      • Stefan Ossendorf says:

        Hi Henry,

        just one suggestion. When you are not using your SmtpClient anywhere else. Please Dispose() it! Since .net 4.0 SmtpClient implements IDisposable because its caching the smtp connection for reuse. So if you don’t need it anymore call Dispose to make sure the smtp gets a QUIT msg from your SmtpClient.

  2. Elie says:

    I have a question
    In order to add this code to a c++ project i am working on, what do i have to include?
    Or does this not work with c++?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: