Automatically send Birthday email using C#

In this article, I’ll demonstrate how to use C# to automatically send birthday emails every day at a specific time.
A Windows Service will be established in order to automatically send Birthday emails every day at a specific time using C#. This Windows Service will run daily at the designated time.

Concept:

In this article, a Task will be carried out every day at a certain time by the Windows Service. The assignment is to gather all student records with today’s birthdays.
These students will immediately receive a birthday email from the Windows Service.

Database:

I used the following table: Students with the following schema.

Building the Windows Service

In my article, I’ve already covered how to create a Windows Service that would carry out a task every day at a certain time.
Simple Windows Service written in C# that executes once daily at a given time.
For sending emails every day, the same code will be utilized with a few minor modifications.

App.Config Modifications

You must specify ScheduledTime to the time the Windows Service will run the Task and Mode to Daily in the App.Config file.
Additionally, you must include the database connection string in the App.Config Connection Strings section.

<appSettings>
    <add key ="Mode" value ="Daily" />
    <add key ="IntervalMinutes" value ="1" />
    <add key ="ScheduledTime" value ="17:43" />
</appSettings>
<connectionStrings>
    <add name="constr" connectionString="Data Source=.\SQL2008R2;Initial Catalog=StudentsDB;integrated security=true" />
</connectionStrings>

Modifying the SchedularCallback event handler

In order to automatically obtain records of Students who have a Birthday and send them emails, we must alter the SchedularCallback event handler.
The Day and Month of each Student’s Birthdate are compared to the Day and Month of the Current Date to retrieve all Student information.
Then a loop is run, and an email is sent to each Student one by one.
After completing the operation, the Windows service goes into rest mode and resumes the same task in 24 hours at the designated time.

private void SchedularCallback(object e)
{
    try
    {
        DataTable dt = new DataTable();
        string query = "SELECT Name, Email FROM Students WHERE DATEPART(DAY, BirthDate) = @Day AND DATEPART(MONTH, BirthDate) = @Month";
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand(query))
            {
                cmd.Connection = con;
                cmd.Parameters.AddWithValue("@Day", DateTime.Today.Day);
                cmd.Parameters.AddWithValue("@Month", DateTime.Today.Month);
                using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                {
                    sda.Fill(dt);
                }
            }
        }
        foreach(DataRow row in dt.Rows)
        {
            string name = row["Name"].ToString();
            string email = row["Email"].ToString();
            WriteToFile("Trying to send email to: " + name + " " + email);
 
            using (MailMessage mm = new MailMessage("sender@gmail.com", email))
            {
                mm.Subject = "Birthday Greetings";
                mm.Body = string.Format("<b>Happy Birthday </b>{0}<br /><br />Many happy returns of the day.", name);
 
                mm.IsBodyHtml = true;
                SmtpClient smtp = new SmtpClient();
                smtp.Host = "smtp.gmail.com";
                smtp.EnableSsl = true;
                System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();
                credentials.UserName = "sender@gmail.com";
                credentials.Password = "<Password>";
                smtp.UseDefaultCredentials = true;
                smtp.Credentials = credentials;
                smtp.Port = 587;
                smtp.Send(mm);
                WriteToFile("Email sent successfully to: " + name + " " + email);
            }
        }
        this.ScheduleService();
    }
    catch (Exception ex)
    {
        WriteToFile("Simple Service Error on: {0} " + ex.Message + ex.StackTrace);
 
        //Stop the Windows Service.
        using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("SimpleService"))
        {
            serviceController.Stop();
        }
    }
}

 

Submit a Comment

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

Subscribe

Select Categories