Send and Receive Emails in ASP.NET with C#

Send and Receive Emails in ASP.NET with C#

Youve got along ASP.NET project ahead. Youre trying to wrap your head around all tasks at hand - infrastructure, business logic, admin panel, integrations. On top of that, theres a long list of could havetype of features that the team would like to implement if time and resources allow.

One of them is adding the ability to send email in ASP.NET C# that youve been postponing for a while. After all, its 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 dont 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, weve covered the first steps with the various code samples. Lets start!

MailMessage

Throughout the course of this article, well often be using MailMessage class. Its 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 Microsofts 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, well show how to send a very simple email with the following details:

To: elizabeth@westminster.co.uk

From: piotr@mailtrap.io

Title: Hey whats up?

Body: Hey Elizabeth, lets meet for lunch on Monday, WDYT?

In order to send such an email, well use the aforementioned MailMessage class from .NET API.

  1. // in the beginning of the file  
  2. using System.Net;  
  3. using System.Net.Mail;  
  4.   
  5.   
  6.   
  7. MailAddress to = new MailAddress("elizabeth@westminster.co.uk");  
  8. MailAddress from = new MailAddress("piotr@mailtrap.io");  
  9.   
  10. MailMessage message = new MailMessage(from, to);  
  11. message.Subject = "Good morning, Elizabeth";  
  12. message.Body = "Elizabeth, Long time no talk. Would you be up for lunch in Soho on Monday? I'm paying.;";  
  13.   
  14. SmtpClient client = new SmtpClient("smtp.server.address", 2525)  
  15. {  
  16.     Credentials = new NetworkCredential("smtp_username""smtp_password"),  
  17.     EnableSsl = true  
  18. };  
  19. // code in brackets above needed if authentication required   
  20.   
  21. try  
  22. {    
  23.   client.Send(message);  
  24. }  
  25. catch (SmtpException ex)  
  26. {  
  27.   Console.WriteLine(ex.ToString());  
  28. }  

Once the message was configured, we connected to the SMTP server and sent it this way!

Sending emails with attachments

Now that we know how to send basic emails, lets 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, well use Attachment class from .NET API. Make sure you add the attachment to the current working directory first.

  1. // in the beginning of the file  
  2. using System.Net;  
  3. using System.Net.Mail;  
  4. using System.Net.Mime;  
  5.   
  6.   
  7.   
  8. String filePath = "wedding_invoice.pdf";  
  9. Attachment data = new Attachment(filePath, MediaTypeNames.Application.Octet);  
  10.   
  11. MailAddress to = new MailAddress("elizabeth@westminster.co.uk");  
  12. MailAddress from = new MailAddress("piotr@mailtrap.io");  
  13.   
  14. MailMessage message = new MailMessage(from, to);  
  15. message.Subject = "Regarding our meeting";  
  16. message.Body = "Elizabeth, as requested, sending you the invoice for Harry and Meghan's wedding. Any questions? Let me know.;";  
  17. message.Attachments.Add(data);  
  18.   
  19. SmtpClient client = new SmtpClient("smtp.server.address", 2525)  
  20. {  
  21.     Credentials = new NetworkCredential("smtp_username""smtp_password"),  
  22.     EnableSsl = true  
  23. };  
  24. // code in brackets above needed if authentication required   
  25.   
  26. try  
  27. {    
  28.   client.Send(message);  
  29. }  
  30. catch (SmtpException ex)  
  31. {  
  32.   Console.WriteLine(ex.ToString());  
  33. }   

 

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

Weve just covered sending emails with attachments. But what if youre sending images but want them displayed inline rather than being attached to an email. Certainly, it will be easier to attract the Queens attention this way. With a bit of modification of our previous code, this can be easily achieved.

When trying to send an email with images in C#, youre not going to use a typical <img src="" alt="" /> construction. It would add an image attachment to the email and thats the last thing we need right now. Instead, well 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 its missing, an email will be sent without any attachment and, really, arent we receiving these oops, forgot about the attachment!” emails too often already?

  1. // in the beginning of the file  
  2. using System.Net;  
  3. using System.Net.Mail;  
  4. using System.Net.Mime;  
  5.   
  6. String messageBody = "Elizabeth, sending you a quick sneak peak of the pictures" +  
  7.   "we took at the last royal wedding. " +  
  8.   "Let me know your thoughts.";  
  9. MailAddress to = new MailAddress("elizabeth@westminster.co.uk");  
  10. MailAddress from = new MailAddress("piotr@mailtrap.io");  
  11. MailMessage message = new MailMessage(from, to);  
  12. message.Subject = "Pics from the royal wedding";  
  13. message.Body = messageBody;  
  14.   
  15. String imagePath = "bestpictureever.png";  
  16. LinkedResource LinkedImage = new LinkedResource(@imagePath);  
  17. LinkedImage.ContentId = "Wedding";  
  18.   
  19. AlternateView htmlView = AlternateView.CreateAlternateViewFromString(  
  20.   $"{messageBody} <br> <img src=cid:Wedding>"null"text/html"  
  21. );  
  22. htmlView.LinkedResources.Add(LinkedImage);  
  23. message.AlternateViews.Add(htmlView);  
  24.                   
  25. try  
  26. {    
  27.   client.Send(message);  
  28. }  
  29. catch (SmtpException ex)  
  30. {  
  31.   Console.WriteLine(ex.ToString());  
  32. }    

Sending to multiple recipients

No rocket science here either. Let's go back to the original email weve sent to our noble recipient.

To: elizabeth@westminster.co.uk

From: piotr@mailtrap.io

Title: Hey whats up?

Body: Hey Elizabeth, lets meet for lunch on Monday, WDYT?

Lets say we want to have a bit bigger lunch party than originally planned, were going to talk about the Royal Wedding after all. Lets keep Prince Harry and his wife Meghan in the loop. New recipients are simply added to the code, separated by a comma. As in the example below. 

  1. // in the beginning of the file  
  2. using System.Net;  
  3. using System.Net.Mail;  
  4.   
  5.   
  6. MailAddress to = new MailAddress("elizabeth@westminster.co.uk, harry@westminster.co.uk");  
  7. MailAddress from = new MailAddress("piotr@mailtrap.io");  
  8.   
  9. MailMessage message = new MailMessage(from, to);  
  10. message.Subject = "Good morning";  
  11. message.Body = "Elizabeth, Harry, There are a few unpaid invoices for the Royal Wedding. Let's talk this over on Monday.;";  
  12.   
  13. SmtpClient client = new SmtpClient("smtp.server.address", 2525)  
  14. {  
  15.     Credentials = new NetworkCredential("smtp_username""smtp_password"),  
  16.     EnableSsl = true  
  17. };  
  18. // code in brackets above needed if authentication required   
  19.   
  20. try  
  21. {    
  22.   client.Send(message);  
  23. }  
  24. catch (SmtpException ex)  
  25. {  
  26.   Console.WriteLine(ex.ToString());  
  27. }  

 

Things get a tiny bit more tricky when you want to add people in bcc and cc, well need a few additional lines:
  1. // in the beginning of the file  
  2. using System.Net;  
  3. using System.Net.Mail;  
  4.   
  5.   
  6.   
  7. MailAddress to = new MailAddress("elizabeth@westminster.co.uk, harry@westminster.co.uk");  
  8. MailAddress from = new MailAddress("piotr@mailtrap.io");  
  9.   
  10. MailMessage message = new MailMessage(from, to);  
  11. message.Subject = "Good morning";  
  12. message.Body = "Elizabeth, Harry, There are a few unpaid invoices for the Royal Wedding. Let's talk this over on Monday.;";  
  13. message.CC.Add(new MailAddress("meghan@westminster.co.uk"));   
  14. message.Bcc.Add(new MailAddress("charles@westminster.co.uk"));  
  15.   
  16. SmtpClient client = new SmtpClient("smtp.server.address", 2525)  
  17. {  
  18.     Credentials = new NetworkCredential("smtp_username""smtp_password"),  
  19.     EnableSsl = true  
  20. };  
  21. // code in brackets above needed if authentication required   
  22.   
  23. try  
  24. {    
  25.   client.Send(message);  
  26. }  
  27. catch (SmtpException ex)  
  28. {  
  29.   Console.WriteLine(ex.ToString());  
  30. }  
 Voila!

Do I need to have an SMTP server?

Lets consider a situation when you dont have (or dont want to have) an SMTP server configured but still want to send an email in C#.

The first option is to do a DNS MX lookup of the email address that youre trying to send an email to. This allows you to figure out what the SMTP server is and connect to it. So, youre still going to use an SMTP server, just not yours!

We dont, however, recommend such an approach for several reasons:

  • Your emails might be treated as spam, especially if you send them from a Dynamic IP
  • Each recipients mail server will need to be resolved manually.
  • Compared to other methods, querying DNS manually consumes more CPU and networking, making the performance worse

In order to implement it, youll need to install a 3rd party plugin. DnsPlugin.NET is our choice here. See the sample code:

  1. // in the top of the file  
  2. // requires installation of https://www.nuget.org/packages/DnsClient  
  3. using System.Net;  
  4. using System.Net.Mail;  
  5. using DnsClient;  
  6.   
  7.   
  8.   
  9. MailAddress to = new MailAddress("elizabeth@westminster.co.uk");  
  10. MailAddress from = new MailAddress("piotr@mailtrap.com");  
  11.   
  12. MailMessage message = new MailMessage(from, to);  
  13. message.Subject = "See you Monday?";  
  14. message.Body = "Elizabeth, I didn't hear back from you. Let me know if we're still scheduled for Monday.";  
  15.   
  16. LookupClient lookup = new LookupClient();  
  17. IDnsQueryResponse response = lookup.Query("westminster.co.uk", QueryType.MX);  
  18.   
  19. foreach(DnsClient.Protocol.MxRecord record in response.Answers) {  
  20.     Console.WriteLine(ObjectDumper.Dump(record.Exchange));  
  21.   
  22.     SmtpClient client = new SmtpClient(record.Exchange, 25);  
  23.   
  24.     try  
  25.     {  
  26.         client.Send(message);  
  27.         // if we reached this point, our email was sent and we can break the loop  
  28.         break;  
  29.     }  
  30.     catch(SmtpException ex)  
  31.     {  
  32.         Console.WriteLine(ex.ToString());  
  33.     }  
  34. }   

Receiving emails in C#

Finally, you might be wondering if theres a way to receive the emails directly with the C# code. After all, the Queen might get back to us any minute now. Of course, you could easily track new emails with simple email clients, such as Gmail or Thunderbird, without a single line of code and with minimal effort. But lets assume you need to see at least the topics of incoming emails with your code, for example, to build some integrations around that.

Receiving emails is not a part of core C# stack so you will need to utilize some 3rd party libraries for that purpose. OpenPop.NET open-source library seems to be getting the job done in this case. You can use the following code to fetch the topics of incoming mail:

var client = new POPClient();

client.Connect("pop.gmail.com", 995, true);

client.Authenticate("piotr@mailtrap.io", "My_password_here");

var count = client.GetMessageCount();

Message message = client.GetMessage(count);

Console.WriteLine(message.Headers.Subject);

For the details on using OpenPop library for this or any other purposes, please refer to their documentation.

Summary

As you can see, sending emails in C# is fairly easy, its mostly about playing with basic HTML and just a few classes. Try it out when you launch your first project but consider some more robust solutions if you plan to scale.

The article on Send and Receive Emails in ASP.NET C# was originally published at Mailtrap’s blog.