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;
        }
    }
}

Run and stop a method after certain interval

Run and stop a method after a certain time by using Stopwatch. This can be done by using a stopwatch that is present in System.Diagnostics namespace. The below code is for reference.


using System;
using System.Diagnostics;

class Program
{
    static void Main(string[] args)
    {
        ExecuteMethodWithTimer(60);
    }
    static void ExecuteMethodWithTimer(double maxRunTimeInSecs)
    {
        Stopwatch stopwatch = new Stopwatch();      
        stopwatch.Start();
        while(true)
        {
            if (stopwatch.Elapsed > TimeSpan.FromSeconds(maxRunTimeInSecs))
            {               
                break;
            }
        }
    }
}

Labels

How to take screenshot of a Webpage using C# Selenium

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