Allowing user to send mail (feedback, contact etc) is a very common feature in current web applications. In this series of post we will talk about some basic mail features and how to implement them in c#.
Basics
In order to send mail we need SMTP server configured as mails work over SMTP. You can configure SMTP server yourself or if you are using web hosting services you can get an account setup for you. In order to receive mails we need POP. For this tutorial series we will use gmail SMTP server.
.NET APIs
.Net provides us with lots of classes present in System.Net.Mail to send an email. We will be using MailMessage, MailAddress and SmtpClient classes.
We will create a MailHelper and will use it in Winforms, Asp.Net, Console etc.
Mail Helper
using System.Collections.Generic; using System.Net.Mail; namespace MailConsole { public class MailHelper { public static void SendMail(string subject,string message,Listto) { var mailMessage = new MailMessage() { From = new MailAddress("YOUR-MAILID@gmail.com"), Subject = subject, Body = message }; foreach (var id in to) { mailMessage.To.Add(id); } var smtp = new SmtpClient(); smtp.Host = "smtp.gmail.com"; smtp.Port = 587; smtp.Credentials = new System.Net.NetworkCredential("YOUR-USERNAME", "YOUR-PASSWORD"); smtp.EnableSsl = true; smtp.Send(mailMessage); } } }
Comments
Post a Comment