c#

C#中如何实现SMTP邮件的定时发送

小樊
89
2024-08-18 05:10:38
栏目: 编程语言

在C#中实现SMTP邮件的定时发送,可以使用System.Net.Mail命名空间中的SmtpClient类和MailMessage类。以下是一个示例代码,演示如何实现在指定时间发送邮件:

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

class Program
{
    static void Main()
    {
        // 设置SMTP服务器和端口
        SmtpClient client = new SmtpClient("smtp.example.com", 587)
        {
            Credentials = new NetworkCredential("your_email@example.com", "your_password"),
            EnableSsl = true
        };

        // 创建邮件消息
        MailMessage message = new MailMessage("your_email@example.com", "recipient@example.com", "Subject", "Body");

        // 设置发送时间
        DateTime sendTime = new DateTime(2022, 1, 1, 12, 0, 0);

        // 计算延迟时间
        TimeSpan delay = sendTime - DateTime.Now;

        // 创建定时器
        Timer timer = new Timer((state) =>
        {
            // 发送邮件
            client.Send(message);
            Console.WriteLine("Email sent at: " + DateTime.Now);
        }, null, (int)delay.TotalMilliseconds, Timeout.Infinite);

        // 等待邮件发送完成
        Console.ReadLine();
    }
}

在此示例中,我们首先创建了一个SmtpClient实例,指定SMTP服务器地址、端口和凭据。然后创建一个MailMessage实例,设置发件人、收件人、主题和正文。接下来设置发送时间,并根据当前时间和发送时间计算出延迟时间。最后创建一个定时器,在指定的延迟时间后发送邮件。

请注意,上述示例中的发送时间是固定的,你可以根据需要修改发送时间。另外,确保在发送邮件之前替换示例中的SMTP服务器地址、发件人邮箱、收件人邮箱和发件人邮箱的密码。

0
看了该问题的人还看了