Home » Selenium C# Scripts

Category Archives: Selenium C# Scripts

How to handle if .Displayed and .Enabled in selenium does not work

driver.findElement(By.Id("YourIdHere")).Displayed. There are more chances that, this line of code might return null and throw NoSuchElementFound exception when it doesn't find 
particular element on the webpage. To handle it, you need to create a simple method which return boolean value and enclose above line of code by try and catch.

Send Email from Outlook account

This method is used to send email from your microsoft office account and it takes 3 arguments i.e email subject, email body and an optional attachement.(using c#)

public void SendEMail(string messagesubject, string messagebody, string screenshot = "")
 MailMessage mesg = new MailMessage(); // MailMessage is a class inside System.Net.Mail
 foreach (string receipents in GetRecipients())
 mesg.To.Add(new MailAddress(receipents));
 // if (!String.IsNullOrEmpty(emailReceiver))
 // {
 // mesg.To.Add(new MailAddress(emailReceiver));
 // }
 mesg.From = new MailAddress("<yourMicrosoftUserName>", "Automation Report");
 mesg.Subject = messagesubject;
 mesg.Body = messagebody;
 mesg.IsBodyHtml = false;

if (!String.IsNullOrEmpty(screenshot))
 Attachment attachment;
 attachment = new Attachment(screenshot);

SmtpClient client = new SmtpClient(); // SmtpClient is a class inside System.Net.Mail
 client.TargetName = "STARTTLS/smtp.office365.com";
 client.UseDefaultCredentials = true;
 client.Credentials = new System.Net.NetworkCredential("<yourMicrosoftUserName>", "<yourMicrosofPassword");
 client.Port = 587;
 client.Host = "smtp.office365.com";
 client.DeliveryMethod = SmtpDeliveryMethod.Network;
 client.EnableSsl = true;

 catch (Exception ex)
 Console.WriteLine("Exception caugh while Sending e-mail. Details : {0}", ex.ToString());

// get list of recepients

private List<string> GetRecipients()
 List<string> ListOfRecipients = new List<string>();
 string value1 = File.ReadAllText("C:\\myFile\\myFile.txt");
 var Recipients = value1.Replace(" ", "").Split(';');
 foreach (string Recipient in Recipients)
 if (!String.IsNullOrWhiteSpace(Recipient))
 return ListOfRecipients;

Take screenshot of the webpage using Selenium C#

Following script is used to take screenshot of the webpage and save in your local drive. (using C#)

ITakesScreenshot screen = driver as ITakesScreenshot;  // ITakesScreenshot is  an interface inside OpenQA.Selenium namespace
Screenshot scrnst = screen.GetScreenshot();  // Screenshot is a class inside OpenQA.Selenium namespace
string screenshot = "c:\\screens\\myScreenShot1.png";
scrnst.SaveAsFile(screenshot, ImageFormat.Png);