Send Emails in ASP.NET C#
You’ve got a long ASP.NET project ahead. You’re trying to wrap your head around all tasks at hand – infrastructure, business logic, admin panel, integrations. On top of that, there’s a long list of ‘could have’ type of features that the team would like to implement if time and resources allow.
One of them is adding the ability to send an email in ASP.NET C# that you’ve been postponing for a while. After all, it’s such an obvious feature that might as well be left for the very end, when almost everything is up and running. Before your project goes live, you will need to validate your email workflows anyway and probably you don’t want to stay extra hours just before the launch to do so.
While sending emails with C# is not rocket science, we strongly recommend thinking about it sooner rather than later. To make it easier to start, we’ve covered the first steps with the various code samples. Let’s start!
MailMessage
Throughout the course of this article, we’ll often be using MailMessage class. It’s a part of System.Net.Mail namespace and is used to create email messages that are then sent to an SMTP server. The delivery is then taken care of by the SmtpClient class.
For the complete set of parameters of this class, please refer to Microsoft’s documentation.
Sending emails in C# with SMTP
This one is fairly easy and quick to set up as SMTP (Simple Mail Transfer Protocol) is the most common communication standard used in email transmission. In the example below, we’ll show how to send a very simple email with the following details:
To: elizabeth@westminster.co.uk
From: piotr@mailtrap.io
Title: Good morning, Elizabeth
Body: Elizabeth, Long time no talk. Would you be up for lunch in Soho on Monday? I’m paying.
In order to send such an email, we’ll use the aforementioned MailMessage class from .NET API.
// in the beginning of the file
using System.Net;
using System.Net.Mail;
MailAddress to = new MailAddress("elizabeth@westminster.co.uk");
MailAddress from = new MailAddress("piotr@mailtrap.io");
MailMessage message = new MailMessage(from, to);
message.Subject = "Good morning, Elizabeth";
message.Body = "Elizabeth, Long time no talk. Would you be up for lunch in Soho on Monday? I'm paying.;";
SmtpClient client = new SmtpClient("smtp.server.address", 2525)
{
Credentials = new NetworkCredential("smtp_username", "smtp_password"),
EnableSsl = true
};
// code in brackets above needed if authentication required
try
{
client.Send(message);
}
catch (SmtpException ex)
{
Console.WriteLine(ex.ToString());
}
Once the message was configured, we connected to the SMTP server and sent it this way! Mailtrap Email Delivery also allows you to send emails via SMTP. Just verify your domain, copy the provided SMTP settings to your app or service, and start sending to your recipients.
Sending emails with attachments
Now that we know how to send basic emails, let’s consider a very common scenario and add an attachment to our message to the Queen of England. This could be an invoice for the last royal wedding or a set of pictures we took on that fabulous weekend.
On top of MailMessage class, we’ll use Attachment class from .NET API. Make sure you add the attachment to the current working directory first.
// in the beginning of the file
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
String filePath = "wedding_invoice.pdf";
Attachment data = new Attachment(filePath, MediaTypeNames.Application.Octet);
MailAddress to = new MailAddress("elizabeth@westminster.co.uk");
MailAddress from = new MailAddress("piotr@mailtrap.io");
MailMessage message = new MailMessage(from, to);
message.Subject = "Regarding our meeting";
message.Body = "Elizabeth, as requested, sending you the invoice for Harry and Meghan's wedding. Any questions? Let me know.;";
message.Attachments.Add(data);
SmtpClient client = new SmtpClient("smtp.server.address", 2525)
{
Credentials = new NetworkCredential("smtp_username", "smtp_password"),
EnableSsl = true
};
// code in brackets above needed if authentication required
try
{
client.Send(message);
}
catch (SmtpException ex)
{
Console.WriteLine(ex.ToString());
}
If you need to send multiple invoices (lucky you!) or other files, simply use a loop and add the other files to the email.
Adding images inline
We’ve just covered sending emails with attachments. But what if you’re sending images but want them displayed inline rather than being attached to an email. Certainly, it will be easier to attract the Queen’s attention this way. With a bit of modification of our previous code, this can be easily achieved.
We’ll use LinkedResource object to directly embed an image in the HTML version of our message to the Queen. We will then follow our regular approach with MailMessage class. As always, remember to upload the file first to your current working directory. If it’s missing, an email will be sent without any attachment and, really, aren’t we receiving these “oops, forgot about the attachment!” emails too often already?
// in the beginning of the file
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
String messageBody = "Elizabeth, sending you a quick sneak peak of the pictures" +
"we took at the last royal wedding. " +
"Let me know your thoughts.";
MailAddress to = new MailAddress("elizabeth@westminster.co.uk");
MailAddress from = new MailAddress("piotr@mailtrap.io");
MailMessage message = new MailMessage(from, to);
message.Subject = "Pics from the royal wedding";
message.Body = messageBody;
String imagePath = "bestpictureever.png";
LinkedResource LinkedImage = new LinkedResource(@imagePath);
LinkedImage.ContentId = "Wedding";
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(
$"{messageBody} <br> <img src=cid:Wedding>", null, "text/html"
);
htmlView.LinkedResources.Add(LinkedImage);
message.AlternateViews.Add(htmlView);
try
{
client.Send(message);
}
catch (SmtpException ex)
{
Console.WriteLine(ex.ToString());
}
Sending to multiple recipients
Let’s say we want to use the opportunity and remind the Queen and her grandson about unpaid invoices.
No rocket science here either. New recipients are simply added to the code, separated by a comma. As in the example below:
// in the beginning of the file
using System.Net;
using System.Net.Mail;
MailAddress to = new MailAddress("elizabeth@westminster.co.uk, harry@westminster.co.uk");
MailAddress from = new MailAddress("piotr@mailtrap.io");
MailMessage message = new MailMessage(from, to);
message.Subject = "Good morning";
message.Body = "Elizabeth, Harry, There are a few unpaid invoices for the Royal Wedding. Let's talk this over on Monday.;";
SmtpClient client = new SmtpClient("smtp.server.address", 2525)
{
Credentials = new NetworkCredential("smtp_username", "smtp_password"),
EnableSsl = true
};
// code in brackets above needed if authentication required
try
{
client.Send(message);
}
catch (SmtpException ex)
{
Console.WriteLine(ex.ToString());
}
Things get a tiny bit more tricky when you want to add people in bcc and cc, we’ll need a few additional lines:
// in the beginning of the file
using System.Net;
using System.Net.Mail;
MailAddress to = new MailAddress("elizabeth@westminster.co.uk, harry@westminster.co.uk");
MailAddress from = new MailAddress("piotr@mailtrap.io");
MailMessage message = new MailMessage(from, to);
message.Subject = "Good morning";
message.Body = "Elizabeth, Harry, There are a few unpaid invoices for the Royal Wedding. Let's talk this over on Monday.;";
message.CC.Add(new MailAddress("meghan@westminster.co.uk"));
message.Bcc.Add(new MailAddress("charles@westminster.co.uk"));
SmtpClient client = new SmtpClient("smtp.server.address", 2525)
{
Credentials = new NetworkCredential("smtp_username", "smtp_password"),
EnableSsl = true
};
// code in brackets above needed if authentication required
try
{
client.Send(message);
}
catch (SmtpException ex)
{
Console.WriteLine(ex.ToString());
}
Voila!
I hope you enjoyed our guide on how to send emails to multiple recipients with ASP.NET. Head to Mailtrap's original article to learn about using API to send emails and receiving emails in C#.