如何在特定时间自动发送电子邮件

时间:2015-04-10 10:14:39

标签: c# sql asp.net

我正在尝试在特定时间自动发送电子邮件,就像使用c#sql在asp.net中提醒一样

我的代码:

try {
    DataTable dt = new DataTable();
    string query = "SELECT Name,Date  FROM Reminder (DAY, Date) = @DAY AND DATEPART(MONTH, Date)= @Month ";
    string connstr = ConfigurationManager.ConnectionStrings["reminderconnection"].ConnectionString;
    SqlConnection con = new SqlConnection(connstr);
    SqlCommand cmd = new SqlCommand(query);
    cmd.Connection = con;
    cmd.Parameters.AddWithValue("@Day", DateTime.Today.Day);
    cmd.Parameters.AddWithValue("@Month", DateTime.Today.Day);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    sda.Fill(dt);

    foreach(DataRow row in dt.Rows) {
        string name = row["Name"].ToString();
        string email = row["Email"].ToString();
        MailMessage msg = new MailMessage();
        msg.Subject = "Meeting";
        msg.Body = string.Format("Meeting for a week", name);
        msg.IsBodyHtml = true;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.EnableSsl = true;
        NetworkCredential credentials = new NetworkCredential();
        credentials.UserName = "xxxxxxxx";
        credentials.Password = "xxxxxxxx";
        smtp.UseDefaultCredentials = true;
        smtp.Credentials = credentials;
        smtp.Port = 587;
        smtp.Send(msg);

    }
} catch (Exception ex) {
    Response.Write("Error message");
}

2 个答案:

答案 0 :(得分:1)

您可以使用Quartz.Net来实现结果。您必须将其作为服务安装在服务器上。

Tutorial here以及一些Hello world程序Here

基本上,你把你的工作安排好,安排工作,并安排工作。

答案 1 :(得分:0)

您可以使用hangfire来安排asp.net中的后台重复进程

检查http://hangfire.io/