Hello Sir,
Below is the code which I'm using to triggere automated Emails from web application.
Thanks
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["CRM_DB"].ConnectionString);
DataTable dt = new DataTable();
string query = "SELECT staffname, email,driving_date FROM documents WHERE DATEPART(DAY, driving_date) = @Day AND DATEPART(MONTH, driving_date) = @Month";
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);
}
for (int i = 0; i < dt.Rows.Count; i++)
{
// Checking condition of Current Date with Database Date.
if (Convert.ToDateTime(dt.Rows[i]["driving_date"]).AddDays(-1).ToShortDateString() == DateTime.Now.ToShortDateString())
{
using (MailMessage mailMessage = new MailMessage())
{
mailMessage.From = new MailAddress("myemail@gmail.com");
mailMessage.Subject = "Test Subject";
mailMessage.Body = "Test Body";
mailMessage.IsBodyHtml = true;
mailMessage.To.Add(new MailAddress(dt.Rows[i]["email"].ToString()));
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = "mymail@gmail.com";
NetworkCred.Password = "password";
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mailMessage);
Response.Redirect("Mail sent");
}
}
else{
Response.Redirect("Mail not sent");
}
}
}
finally
{
con.Close();
con.Dispose();
}
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
System.Timers.Timer timer = new System.Timers.Timer();
// Set the Interval to 7 Days (604800000 milliseconds).
timer.Interval = ((((1 * 24) * 60) * 60) * 1000);
timer.AutoReset = true;
timer.Elapsed += new System.Timers.ElapsedEventHandler(TimerElapsed);
timer.Enabled = true;
}
public void TimerElapsed(object source, System.Timers.ElapsedEventArgs e)
{
// Instanciate the Mail class.
ScheduleMail scheduleMail = new ScheduleMail();
// Call the send mail method.
scheduleMail.SendScheduleMail();
}