简体   繁体   中英

how to send a email automatically at particular time

I'm trying to send a email automatically at particular time like a reminder in asp.net with c# sql

my code:

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");
}

You can use Quartz.Net to achieve your result. You have to install it as a service on server.

Tutorial here and some Hello world programs Here

Basically you write your job to schedule, a trigger for the job and schedule it for mailing.

You can use hangfire to schedule background recurring processes in asp.net

check http://hangfire.io/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM