我正在创建一个Windows服务,以特定的时间间隔发送邮件。我想启用一个计时器来处理mail_send()
。
private void timer1(object sender, EventArgs e) {
// I need a code here to work with email_send()
timer1.Elapsed += new ElapsedEventHandler(email_send);
}
public void email_send(object sender, System.Timers.ElapsedEventArgs e) {
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("email from");
mail.To.Add("emailto");
mail.Subject = DateTime.Now +"logfile";
mail.Body = "mail with log file attachment";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("F:\\logfile\\logfile.txt");
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("emailfrom", "password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
答案 0 :(得分:0)
你应该通过调用方法Start()来运行你的计时器,以“启用”它。
private void timer1(object sender, EventArgs e)
{
timer1.Elapsed += new ElapsedEventHandler(email_send);
timer1.Start();
}
答案 1 :(得分:0)
首先初始化计时器
public static void Main()
{
InitializeTimer();
timerr.Start();
}
您可以使用开始和停止来启动timmer和Stop timmer
private void InitializeTimer()
{
Timer timerr = new Timer();
timerr.Interval = 5000;
timerr.Tick += Timerr_Tick;
}
然后写下tick事件。
private void Timerr_Tick(object sender, EventArgs e)
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("email from");
mail.To.Add("emailto");
mail.Subject = DateTime.Now +"logfile";
mail.Body = "mail with log file attachment";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("F:\\logfile\\logfile.txt");
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("emailfrom", "password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}