How to send emails in .NET part 1: basics of MailMessage
August 19, 2014 14 Comments
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.