Home » Selenium C# Scripts » Send Email from Outlook account

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 = "")
 
 {
 try
 {
 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);
 mesg.Attachments.Add(attachment);
 }

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;

client.Send(mesg);
 }
 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>();
 try
 {
 
 string value1 = File.ReadAllText("C:\\myFile\\myFile.txt");
 
 var Recipients = value1.Replace(" ", "").Split(';');
 foreach (string Recipient in Recipients)
 {
 
 if (!String.IsNullOrWhiteSpace(Recipient))
 {
 ListOfRecipients.Add(Recipient);
 
 }
 }
 }
 catch{}
 return ListOfRecipients;
 }

10 Comments

  1. Not much info is available on internet on Test Studio. Your work is meritorious and it helped me a lot in my project.
    Keep posting cool stuff like this. 🙂

Leave a comment

Your email address will not be published. Required fields are marked *