.net send mail on specific time

A classic task!

In.NET, you can use the System.Net.Mail namespace to send emails, and the System.Threading.Timer class to schedule the sending of emails at a specific time. Here's an example:

Step 1: Create a mail message

using System.Net.Mail;

// Create a new mail message
MailMessage mail = new MailMessage();
mail.From = new MailAddress("[email protected]");
mail.To.Add("[email protected]");
mail.Subject = "Test email";
mail.Body = "This is a test email sent at a specific time.";

Step 2: Create a timer

using System.Threading;

// Create a timer that will trigger at the specified time
Timer timer = new Timer(SendMail, null, DateTime.Now.AddHours(2), Timeout.Infinite);

In this example, the timer will trigger 2 hours from now.

Step 3: Send the mail

private void SendMail(object state)
{
    // Send the mail message
    SmtpClient client = new SmtpClient();
    client.Send(mail);
}

This method will be called when the timer triggers. It creates a new SmtpClient instance and uses it to send the mail message.

Putting it all together

using System;
using System.Net.Mail;
using System.Threading;

class Program
{
    static void Main(string[] args)
    {
        // Create a mail message
        MailMessage mail = new MailMessage();
        mail.From = new MailAddress("[email protected]");
        mail.To.Add("[email protected]");
        mail.Subject = "Test email";
        mail.Body = "This is a test email sent at a specific time.";

        // Create a timer that will trigger at the specified time
        Timer timer = new Timer(SendMail, null, DateTime.Now.AddHours(2), Timeout.Infinite);

        // Wait for the timer to trigger
        Console.ReadLine();
    }

    private static void SendMail(object state)
    {
        // Send the mail message
        SmtpClient client = new SmtpClient();
        client.Send(mail);
    }
}

In this example, the program will create a mail message and a timer that will trigger 2 hours from now. When the timer triggers, the SendMail method will be called, which will send the mail message using an SmtpClient instance.

Note that you'll need to replace the placeholders ([email protected] and [email protected]) with your actual email addresses. Additionally, you may need to configure your SMTP server settings in the SmtpClient instance.