I am trying to send an email automatically using timer. the given below code is I have used for send email. But it is not responding. While using the same code under button click event, its working perfectly. Help me to find a proper solution. Thank you.
Code:
namespace AlertMail
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
MailMessage loginInfo = new MailMessage();
string em = "toAddress@gmail.com";
loginInfo.To.Add(em.ToString());
loginInfo.From = new MailAddress("fromAddress@gmail.com");
loginInfo.Subject = "Alert Information";
loginInfo.Body = "Hai";
loginInfo.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential("fromAddress@gmail.com", "Password");
smtp.Send(loginInfo);
label6.Text = "Alert is send to your email..!!";
}
}
}
In many web application we need to send schedule(automatic) emails and we schedule them. like:
For this, we normally used windows services or windows application.
As we know the web server IIS is continuously running, we can add a timer in the application and the timer can manage all these activities
//Inside Global.ascx
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
System.Timers.Timer myTimer = new System.Timers.Timer();
// Set the Interval to 5 seconds (5000 milliseconds).
myTimer.Interval = 5000;
myTimer.AutoReset = true;
myTimer.Elapsed += new ElapsedEventHandler(myTimer_Elapsed);
myTimer.Enabled = true;
}
public void myTimer_Elapsed(object source, System.Timers.ElapsedEventArgs e)
{
// use your mailer code
clsScheduleMail objScheduleMail = new clsScheduleMail();
objScheduleMail.SendScheduleMail();
}
// inside your class
public void SendScheduleMail()
{
// Write your send mail code here.
}
Usually when I need to run something on a schedule on a Windows server, I use a Scheduled Task. You can write your e-mail piece as a Console application, save it to a location on the server, and then have a scheduled task run the application on a given time interval. I'm not sure what version of Windows you are running, but these instructions apply to Windows 2008, Windows 8, and Windows 2012:
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.