I have gone through some of the answers in this website for automatic mail sending in particular date.
I am using vs 2010 and I have created a project which is not hosted.
I have created a table for appointments with email id,Start date and start time.
The mail should be sent automatically to the email id of person one hour before an appointment.
How should I do this?
I have tried using window service but did not work for me.
protected override void OnStart(string[] args)
{
string dateonly = DateTime.Now.ToString("yyyy-MM-dd");
string timeonly = DateTime.Now.ToString("HH:mm tt");
string source = "Data Source=localhost;Initial Catalog=PRO;Integrated Security=SSPI;";
SqlConnection con = new SqlConnection(source);
con.Open();
SqlCommand cmd = new SqlCommand("select * from Appointments where CONVERT(varchar(10),StartDate,101)=CONVERT(varchar(10),GETDATE(),101)", con);
cmd.Parameters.AddWithValue("@date", dateonly);
cmd.Parameters.AddWithValue("@time", timeonly);
cmd.ExecuteNonQuery();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds); //Filling table with user data
SmtpClient client = new SmtpClient();
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
client.Host = "smtp.gmail.com";
client.Port = 587; //Google mail port
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("email", "password");
client.UseDefaultCredentials = false;
client.Credentials = credentials;
for each (Data Row Dr in ds.Tables[0].Rows)
{
MailMessage mm = new MailMessage();
mm.To.Add(dr["Email"].ToString());
mm.From = new MailAddress("email");
mm.Subject = "Sending Auto Mail ";
mm.Body = "This email has been send automatically through Windows Service to remind you about your Appointment in next one hour ";
client.Send(mm);
mm.Dispose();
}
}
protected override void OnStop()
{
}