Hi mahesh213,
The WebServer IIS is continuously running, we can add a timer in the application and the timer can manage all these activities.
For this we have to make use of Global.asax file in which the timer will check Today date and send the email to that employee.
Check this example. Now please take its reference and correct your code.
Global.asax
<%@ Application Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.Net.Mail" %>
<script RunAt="server">
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 1000;
timer.AutoReset = true;
timer.Elapsed += new System.Timers.ElapsedEventHandler(TimerElapsed);
timer.Enabled = true;
}
public void TimerElapsed(object source, System.Timers.ElapsedEventArgs e)
{
// Runs at every dat 12 AM.
if (DateTime.Now.Hour == 0 && DateTime.Now.Minute == 0)
{
// Filter and get the DataTable whose DOB falls on Today's Date.
DataTable dt = new DataTable();
string query = "SELECT Id,Name,DOB,Email FROM Employee WHERE DATEPART(DAY, DOB) = @Day AND DATEPART(MONTH, DOB) = @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);
}
}
}
// Loop througn each Employee and send email.
foreach (DataRow dr in dt.Rows)
{
// Call the send mail method.
using (MailMessage mm = new MailMessage("sender@gmail.com", dr["Email"].ToString()))
{
mm.Subject = "Birthday Greetings";
mm.Body = string.Format("<b>Happy Birthday </b>{0}<br /><br />Many happy returns of the day.", dr["Name"].ToString());
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential credentials = new NetworkCredential(mm.From.Address, "xxxxxx");
smtp.UseDefaultCredentials = true;
smtp.Credentials = credentials;
smtp.Port = 587;
smtp.Send(mm);
}
}
}
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
}
</script>