Sending automated Mail from ASP.NET Windows Services

The following is a step by step tutorial on how to create a simple windows service that sends an automated email to all users in your database.

  1. Create a windows service application and name AutomatedMail
  2. right click project >> add reference >> System.Web
  3. rename the auto created class from service1.cs to AutoMail.cs
  4. open AutoMail.cs Designer and in Properties window change ServiceName and the Name to “AutoMailService” and make sure AutoLog property is true.
  5. Right Click AutoMail.cs >> View Code >> Add following references:
    • using System.Net.Mail;
    • using System.Data;
    • using System.Data.SqlClient;
    • using System.Web.UI.WebControls;

  6. Declare a new timer in the public method named “timeOnInit” and a new DataSet named “newDataSet”.
    • public partial class AutoMailService : ServiceBase{ DateTime timeOnInit= DateTime.Now;DataSet ds= new DataSet();…..}
  7. In the AutoMailService add after the InitializeComponent as shown below in blue:
    • public AutoMailService()
      {

      InitializeComponent();
      this.ServiceName = “AutoMailService”;
      this.CanStop = true;
      this.CanPauseAndContinue = true;
      this.AutoLog = true;

      }

  8. In the OnStart() method add the following and change the parts in blue to make it work:
    • try
      {

      DateTime eventDate = Convert.ToDateTime(“31/12/2012 23:00:00”); //Date of the actual event
      string reminderDate = “30/12/2012 09:00”; //Date we want to send the event reminder, in this case 1 day prior to event first thing in the morning
      DateTime dateNow = DateTime.Now;
      while (dateNow != eventDate)
      {

      if (eventDate.ToString().Contains(reminderDate) )
      {

      DataSet ds = new DataSet();
      string connstr = “Data Source=111.111.111.111;Initial Catalog=dbname;User Id=username;Password=password;”; //your database connection string
      SqlConnection conn = new SqlConnection(connstr);
      conn.Open();
      string sql = “SELECT * FROM Users“;
      SqlDataAdapter da = new SqlDataAdapter(sql, conn);
      da.Fill(ds, “Users“); //Filling table with user data
      SmtpClient client = new SmtpClient(); // setting email smtp client to send email from
      client.DeliveryMethod =SmtpDeliveryMethod.Network;
      client.EnableSsl = true;
      client.Host = “smtp.gmail.com“; //google mail smtp host
      client.Port = 587; //Google mail port
      System.Net.NetworkCredential credentials =new System.Net.NetworkCredential(“example@gmail.com“, “password“); //your email and password
      client.UseDefaultCredentials = false;
      client.Credentials = credentials;
      foreach (DataRow dr in ds.Tables[0].Rows)
      {

      MailMessage mm = new MailMessage(dr[“Email“], dr[“Name“]); //fields in the database
      mm.Subject = “Sending Auto Mail From Windows Service”; //Email Subject to send out
      mm.Body = “This email has been send automatically through Windows Service to remind you about our event tonight at 23:00 “; //Email Content to send out
      mm.IsBodyHtml =true;
      client.Send(mm);
      mm.Dispose(); // to dispose of each email

      // end of foreach (DataRow dr in ds.Tables[0].Rows)

      //End of if (eventDate.ToString().Contains(reminderDate)

      System.Threading.Thread.Sleep(50000); // puts thread to sleep for 50seconds in order to send only one email
      dateNow = DateTime.Now; //Resets time
      } //End of while (dateNow != eventDate)

      }
      catch
      {
      }

Setting the Installers:

  1. Open AutoMail.cs Design >> Right Click >> Add Installers
  2. Click on serviceProcessInstaller1 (Do not Double-click)
    • In the Properties window set Account to LocalSystem from the drop down list
  3. Click on serviceInstaller1 (Do not Double-click)
    • Change DisplayName as the ServiceName (AutoMailService)
    • set Start Type to automatic
  4. Build the application

Intalling the exe:

  1. Click Start on the task bar >> find Visual Studio .Net command prompt >> Right Click >> Run as Administrator
  2. type the command:
    • Join the physical path of the exe file, add the command “InstallUtil” and add the path name of the exe
    • example: installUtil “C:\physical_path_of_exe\bin\debug\AutoMailService.exe”
  3. Close the command prompt
  4. Right Click My Computer >> Manage >> Services and Applications >>Services >> Select the newly added AutoMailService

2 thoughts on “Sending automated Mail from ASP.NET Windows Services

  1. Hello ,

    I follow your procedure for send automatic send mail but i got an error on this line please replay me for this error :

    MailMessage mm = new MailMessage(dr[“email”],dr[“name”]);

    The best overloaded method match for ‘System.Net.Mail.MailMessage.MailMessage(string, string)’ has some invalid arguments.

Leave a reply to ketan Cancel reply