Home > .NET > Sending email through C#.net

Sending email through C#.net

Module: CEmailManager
Calling function:

public static bool SendDummyEmail()
{
   return SendEmail(CGlobalParams.AdminEmail, "dummy", "Hi");
}

Worker function:
private static bool SendEmail(string p_strTo, string p_strSubject, string p_strBody)
{
   try
   {
      MailMessage objMessage = new MailMessage();

      string[] lstRecipient = p_strTo.Split(',');
      foreach (string strTo in lstRecipient)
      {
          objMessage.To.Add(strTo);
      }

      objMessage.From = new MailAddress(CGlobalParams.SMTPUser, CGlobalParams.EmailSenderDisplay);
      objMessage.Subject = p_strSubject;
      objMessage.Body = p_strBody;

      SmtpClient objClient = new SmtpClient(CGlobalParams.SMTPServer, CGlobalParams.SMTPPort);
      objClient.UseDefaultCredentials = false;
      objClient.Credentials = new System.Net.NetworkCredential(CGlobalParams.SMTPUser, CGlobalParams.SMTPPassword);
      objClient.DeliveryMethod = SmtpDeliveryMethod.Network;

      if (CGlobalParams.SMTPRequireSSL)
      {
          objClient.EnableSsl = true;
      }

      objClient.Send(objMessage);

      return true;
   }
   catch
   {
     return false;
   }
}

Where

CGlobalParams: A class responsible for reading values for global parameters

Global parameters used here:

SMTPPassword    : somevalue
SMTPPort   : 587
SMTPRequireSSL    : true
SMTPServer    : smtp.gmail.com
SMTPUser    : jyotsnas@philogy.com

With currently set global parameters, the code sends email with gmail/ google apps over SSL. Setting the SMTPRequireSSL to false, will make the code send email with SMTP server which requires authentication but not SSL.

Advertisement
Categories: .NET
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.