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 = "andras.nemes@company.com";
string to = "john.smith@company.com";
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 = "mail.company.com";
SmtpClient client = new SmtpClient(smtpServer);
client.Send(mailMessage);

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.

Advertisements

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

    • Andras Nemes says:

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

      • 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.
        //Andras

      • 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 = “FieldServiceTools@ABRIZA.net”
        };

        var from = new MailAddress(“FieldServiceTools@ABRIZA.net”, “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(“FieldServiceTools@ABRIZA.net”, mergeFields, new System.Web.UI.Control()))
        {
        mailMessage.To.Clear();
        mailMessage.To.Add(to);
        mailMessage.From = from;
        mailMessage.Subject = String.Format(“{0} at {1}”, storeEvent.Activity.Name, storeEvent.Store.Name);
        mailMessage.IsBodyHtml = true;

        writer.WriteLine(FormatEventCalendarAttachment(storeEvent));
        writer.Flush();
        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();
        smtpMail.Send(mailMessage);
        }
        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:

    Hi
    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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: