Wednesday, July 20, 2011

send email using smtp

This is how we implemented sending email using smtp:

First, we created a public class in the custom classes project, then we declared the constructor like this:

public EmailSender(string host, int port, string username, string password)
{
_smtpClient = new SmtpClient(host, port);
_smtpClient.EnableSsl = false;
_credentials = new System.Net.NetworkCredential(username, password);
_smtpClient.Credentials = _credentials;
}

After that, we created a function that will create the email message:

public void SendEmail()
{
MailMessage mailMsg = new MailMessage();
mailMsg.From = new MailAddress("abc@email.com", "Sender FullName");
mailMsg.To.Add(new MailAddress("xyz@email.com", "Recipient FullName"));
mailMsg.Subject = "Sample Email";

var message = new StringBuilder();
message.AppendLine("<span style='font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 11px;'>");
message.AppendLine("Dear Recipient FullName",<br/><br/>");
message.AppendLine("This is a test email.<br/>");
message.AppendLine("Thank you,<br/>");
message.AppendLine("Sender FullName");
message.AppendLine("</span>");
mailMsg.Body = message.ToString();
mailMsg.IsBodyHtml = true;
_smtpClient.Send(mailMsg);
}

And now, we are ready to call that function in the Custom Business Layer using this:

EmailSender emailSender = new EmailSender("smtp.gmail.com", 465, "yourgooglemailname@gmail.com", "yourpassword");
emailSender.SendEmail();

Yey! You can now send an email using your program...

No comments: