C# How to send an email

In this blog I'll be showing you how to send an email in C#.

Firstly we'll create variables for the 'from', 'subject' and 'body'.

string strFrom = "username@gmail.com";
string strSubject = "A simple email";
string strBody = @" Please <a href='http://www.merlinjs.com'<a/>";

 

Now create FROM and TO mail address objects.

 // Create a FROM and a TO MailAddress
System.Net.Mail.MailAddress from = new System.Net.Mail.MailAddress(strFrom, "");
System.Net.Mail.MailAddress to = new System.Net.Mail.MailAddress(email, "");


Next create a new mail message using the FROM and TO mail addresses above

// Create a new blank MailMessage
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(from, to);


Next configure the remaining properties on MailMessage.

//Configure the mail message (we are using HTML)
mail.IsBodyHtml = true;
mail.Subject = strSubject;
mail.Body = strBody;


Create a new SmtpClient to Send the email, below we retrieve our SmtpServer value from web.config

//We need an SmtpClient in order to send the email, (here we retrieve the smtp server name from the web.config) replace as required
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(System.Web.Configuration.WebConfigurationManager.AppSettings["SmtpServer"]);


Next be sure to set the credentials(username and password) on the SmtpClient, we also retreive these from the web.config.

//Set the Credentials on the smtpClient again here we retrieve from the web.config so odify as required
smtp.Credentials = new System.Net.NetworkCredential(System.Web.Configuration.WebConfigurationManager.AppSettings["MailU"], System.Web.Configuration.WebConfigurationManager.AppSettings["MailP"]);


Finally send the email to the recipient, below we put this in a try/catch block enabling us to catch and manage any errors.

//Finally SEND the email
try
{
    smtp.Send(mail);
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}


 Comments

you are welcome to leave a comment
Please enter the code above:



No comments