How to Send Email Using ASP.Net With C#?

Introduction

In this article, we will see the way to send email in ASP.Net C#. There are several articles on the web for sending an email using ASP.NET and C#. This article explains some important functions and common notable errors.

Follow the below Sample Code.

using System.IO;
using System.Net;
using System.Net.Mail;

string to = "[email protected]";
string from = "[email protected]";
MailMessage message = new MailMessage(from, to);

string mailbody = "Send an email using ASP.NET C#";
message.Subject = "Sending Email Using ASP.NET C#";
message.Body = mailbody;
message.BodyEncoding = Encoding.UTF8;
message.IsBodyHtml = true;

SmtpClient client = new SmtpClient("smtp.gmail.com", 587); // Set Gmail SMTP
System.Net.NetworkCredential basicCredential1 = new System.Net.NetworkCredential("yourEmailId", "Password");
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = basicCredential1;

try
{
    client.Send(message);
}
catch (Exception ex)
{
    throw ex;
}

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 it to True in UseDefaultCredentials, then that specifies to allow authentication based on the credentials of the account used to send emails.

Common Error

  • 5.5.1 Authentication Required 

The SMTP server requires a secure connection, or the client was not authenticated. The server response was: 5.5.1 Authentication Required.

Solution

It’s a common error faced in sending emails. To solve this, follow the below steps.

  • Enter the correct login password.
  • Remove 2-Step Verification.

Conclusion

That's it! With these steps, you will send the email using Asp.Net C#. There are several other ways to do this. But this simple and clean code will help you.


Similar Articles