Wednesday, February 5, 2020

Using SMTP server to send email

Using the SMTP server to send an email. This is a simple Email helper class which is used to send email using your Gmail account. For any other server just provide the correct SMTP details based on your environment. You can modify it based on your reference.

using System;
using System.Net.Mail;

class Program
{
    static void Main(string[] args)
    {
        var isMailSent = SendMail("Recipient EmailIds", "UserName@gmail.com", "CCEmail Ids", "Emmail Subject", "Email body");

    }
    static bool SendMail(string toEmailIds, string fromEmailId, string ccEmailIds, string mailSubject, string mailBody)
    {
        try
        {
            var smtpClient = new SmtpClient()
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                UseDefaultCredentials = true,
                Credentials = new System.Net.NetworkCredential("Your Gmail Username", "Your Gmail Password")
            };
            MailAddress fromAddress = new MailAddress(fromEmailId);
            var message = new MailMessage()
            {
                From = new MailAddress(fromEmailId),
                Subject = mailSubject,
                IsBodyHtml = true,
                Body = mailBody
            };
            message.To.Add(toEmailIds);
            message.CC.Add(ccEmailIds);

            smtpClient.Send(message);
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }
}

No comments:

Post a Comment

Labels

How to take screenshot of a Webpage using C# Selenium

           ChromeOptions options = new ChromeOptions();             options.AddArgument("headless");//Comment if we want to see ...