Sending Emails through gmail SMTP Server using C# ASP.NET

by Nathan 8. December 2010 09:48

Here is the C# code to send emails through the gmail smtp server. You will need to replace the emailaddress and password to reflect your gmail account.

NOTE: Headers will be replaced by gmail that will make your from address @gmail.com

 

 

 

using System;
using System.Configuration;
using System.Net;
using System.Net.Mail;


public class GmailSMTP
{

    public bool Send(string fromEmail, string senderName, string[] toEmail, string[] cc, string[] bcc, string emailSubject, string emailContent, bool isHtmlContent, out string sendStatusMsg)
    {
        bool inValidEmailAddr = false;
        string outPutParam = "";


        if (fromEmail == "" || fromEmail == null)
        {
            sendStatusMsg = "(From) Email Address cannot be null.";
            return false;
        }

        SmtpClient smtpClient = new SmtpClient();
        MailMessage message = new MailMessage();
        MailAddress fromAddress = new MailAddress(fromEmail, senderName);

        // SMTP Details
        smtpClient.Host = "smtp.gmail.com";
        smtpClient.Port = 587;
        smtpClient.EnableSsl = true;
        smtpClient.UseDefaultCredentials = true;
        NetworkCredential SMTPUserInfo = new NetworkCredential("youraddress@gmail.com", "password");
        smtpClient.Credentials = SMTPUserInfo;
        message.From = fromAddress;

        foreach (string toAddr in toEmail)
        {
            message.To.Add(toAddr);
        }

        if (cc != null)
        {
            foreach (string ccAddr in cc)
            {
                message.CC.Add(ccAddr);
            }
        }

        if (bcc != null)
        {
            foreach (string bccAddr in bcc)
            {
                message.Bcc.Add(bccAddr);
            }
        }

        message.Subject = emailSubject;
        message.IsBodyHtml = isHtmlContent;
        message.Body = emailContent;
        try
        {
            smtpClient.Send(message);
            sendStatusMsg = "Message sent successfully";
            return true;
        }
        catch (Exception ex)
        {
            sendStatusMsg = "Send Email Failed: " + ex.Message;
            return false;
        }
    }

}

 

Tags: ,

ASP.NET

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.6.1.0
Theme by Mads Kristensen