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.
Great post. Maybe you could do one with adding a CalendarEvent as an attachment.
Henry, I’ll take it up in one of the upcoming posts on emailing in .NET.
//Andras
To be exact I want to Attach a meetiing.ics to an email directly from a Memory stream without having to first read or write the file to disk.
I’ll take a look at that but it won’t come this week. Hence if it’s urgent then you should find a solution online.
//Andras
Thanks again. Your articles are very insightful. I read your blog daily with coffee every AM
.
Just to make sure I’m on the right track. Do you mean this CalendarEvent class?
//Andras
Hi Henry,
just add a new Attachment with your stream and ContentType = “text/calendar”.
Stefan, thanks a lot for your input.
//Andras
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;
}
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.
Reblogged this on Dinesh Ram Kali..
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++?
Hello, i don’t know much about c++, so i cannot help you here unfortunately. Andras
Thanks
Sorry to disturb you