.net send mail on specific time in windows form
To send an email at a specific time in a Windows Forms application using.NET, you can use the System.Threading.Timer
class to schedule a timer that will trigger a method to send the email at the desired time.
Here's an example of how you can do this:
using System;
using System.Net.Mail;
using System.Threading;
public partial class Form1 : Form
{
private Timer _timer;
public Form1()
{
InitializeComponent();
}
private void SendEmail()
{
// Create a new MailMessage object
MailMessage mail = new MailMessage();
// Set the sender and recipient
mail.From = new MailAddress("[email protected]");
mail.To.Add("[email protected]");
// Set the subject and body
mail.Subject = "Test email";
mail.Body = "This is a test email";
// Create a new SmtpClient object
SmtpClient client = new SmtpClient();
// Set the SMTP server and port
client.Host = "smtp.example.com";
client.Port = 587;
// Send the email
client.Send(mail);
}
private void Form1_Load(object sender, EventArgs e)
{
// Set the timer to trigger at 8:00 AM every day
_timer = new Timer(new TimerCallback(SendEmail), null, DateTime.Now.AddDays(1).AddHours(8), TimeSpan.FromDays(1));
}
}
In this example, the SendEmail
method is called every day at 8:00 AM using the Timer
class. The TimerCallback
delegate is used to specify the method to be called when the timer triggers.
You can adjust the timer settings to send the email at a different time or frequency by modifying the Timer
constructor parameters. For example, to send the email every hour, you can use the following code:
_timer = new Timer(new TimerCallback(SendEmail), null, DateTime.Now.AddHours(1), TimeSpan.FromHours(1));
Make sure to add the necessary using statements and references to the System.Net.Mail
and System.Threading
namespaces to use the MailMessage
and SmtpClient
classes.
Also, you can use System.Timers.Timer
instead of System.Threading.Timer
if you are targeting.NET Framework 4.5 or later.
You can also use Task
and TaskScheduler
to send the email at a specific time, here is an example:
private async void Form1_Load(object sender, EventArgs e)
{
await Task.DelayUntil(DateTime.Now.AddDays(1).AddHours(8));
SendEmail();
}
This will send the email at 8:00 AM every day, but it will not run in the background, it will block the UI thread until the email is sent.
Please note that the above examples are just a demonstration of how to send an email at a specific time, you should adjust the code to fit your specific requirements and also make sure to handle any exceptions that may occur during the email sending process.