Send Email Using ASP.Net With C#

Introduction 

There are many more articles on Google for sending an email using ASP.NET and C#. This article explains some important functions and notable errors.

Code

  1. using System.IO;  
  2. using System.Net;  
  3. using System.Net.Mail;  
  4.   
  5.   
  6. string to = "[email protected]"//To address    
  7. string from = "[email protected]"//From address    
  8. MailMessage message = new MailMessage(from, to);  
  9.   
  10. string mailbody = "In this article you will learn how to send a email using Asp.Net & C#";  
  11. message.Subject = "Sending Email Using Asp.Net & C#";  
  12. message.Body = mailbody;  
  13. message.BodyEncoding = Encoding.UTF8;  
  14. message.IsBodyHtml = true;  
  15. SmtpClient client = new SmtpClient("smtp.gmail.com", 587); //Gmail smtp    
  16. System.Net.NetworkCredential basicCredential1 = new  
  17. System.Net.NetworkCredential("yourmail id""Password");  
  18. client.EnableSsl = true;  
  19. client.UseDefaultCredentials = false;  
  20. client.Credentials = basicCredential1;  
  21. try   
  22. {  
  23.     client.Send(message);  
  24. }   
  25.   
  26. catch (Exception ex)   
  27. {  
  28.     throw ex;  
  29. }  
We must add the following namespace:
  1. using System.Net;    
  2. using System.Net.Mail;   
Simple Mail Transfer Protocol (SMTP) 

Simple Mail Transfer Protocol (SMTP) is a TCP/IP protocol used in sending and receiving e-mail. Most e-mail systems that send mail over the Internet use SMTP to send messages from one server to another. The messages can then be retrieved with an e-mail client using either POP or IMAP.

The following is a list of SMTP Server and Port Numbers:

Sl.No Mail Server SMTP Server( Host ) Port Number
1 Gmail smtp.gmail.com 587
2 Outlook smtp.live.com 587
3 Yahoo Mail smtp.mail.yahoo.com 465
4 Yahoo Mail Plus plus.smtp.mail.yahoo.com 465
5 Hotmail smtp.live.com 465
6 Office365.com smtp.office365.com 587
7 zoho Mail smtp.zoho.com 465

Important SMTP Class Properties:

  • Host: Server URL for SMTP (check the preceding table).

  • EnableSsl: Check your host accepts SSL Connections (True or False).

  • Port: Port Number of the SMTP server (check the preceding table).

  • Credentials: Valid login credentials for the SMTP server (the email address and password).

  • UseDefaultCredentials: When we set to True in UseDefaultCredentials then that specifies to allow authentication based on the credentials of the account used to send emails.

Common Error

The following error will occur commonly for everyone. How to solve this? Check my previous blog contents.

Tech Blog Reference

Summary

We learned how to send emails using ASP.NET and C#. I hope this article is useful for all .NET beginners.

Up Next
    Ebook Download
    View all
    Learn
    View all