How to Send Emails through SMTP in C# and ASP.NET
Sometimes you are required to send email to the website administrator when a visitor fills a contact form on the website. You can create this feature in C#
easily and for this you will need the following things.
1. Email access that is the password of the email through which you will send emails (with your C#
code).
2. SMTP
settings for your email address.
Create a new Email
Nearly all web hosting services (shared hosting and dedicated hosting) provide you with the email services through which you can send emails. So go to the hosting account of the website and create a new Email.
Next go to the Email settings and find out the SMTP
Settings which the email has.
See the image below:
Email Sending Code in C#
Now we can proceed with creating the ASP.NET Send Email code. So in your C#
code first provide reference to the following namespace:
using System.Net.Mail;
Then add the following code:
MailMessage mailMessage = new MailMessage();mailMessage.From = new MailAddress("email1@somewebsite.com");mailMessage.To.Add(new MailAddress("email2@somewebsite.com"));mailMessage.Subject = "Your subject";
mailMessage.IsBodyHtml = true;
mailMessage.Body = "Email body";SmtpClient client = new SmtpClient();
client.Credentials = new System.Net.NetworkCredential("email1@somewebsite.com", "password");
client.Host = "smtpout.asia.secureserver.net";client.Send(mailMessage);
Add the above code at some relevant area like button click
or page load to send your email.
Adding the CC and Bcc
The CC
and BCC
can be added to the MailMethod
class like:
mailMessage.CC.Add(new MailAddress("solutions@yogihosting.com"));
mailMessage.Bcc.Add(new MailAddress("coding@yogihosting.com"));
Adding Mail Attachment
To add the Mail attachment use the MailMethod
class like:
mailMessage.Attachments.Add(new Attachment(Server.MapPath("File-Path")));
Conclusion
CMS like WordPress provides plugins Contact Form 7 which creates a contact form in the website and when this contact form is filled the email is automatically sent to the website administrator.
If you want to create this feature by C#
code then the above code works absolutely perfect.
If you like this tutorial then please give me some claps, and do follow me for 1 tutorial on Web Development every week.
I have also published another tutorial on HACKERNOON, you would like to see it too — ASP.NET CORE — Learn CRUD Operations in ADO.NET from Zero to Hero
Thanks & Regard,
YOGI