温馨提示×

C#中如何实现SMTP邮件的自动回复功能

c#
小樊
85
2024-08-18 05:14:41
栏目: 编程语言

在C#中实现SMTP邮件的自动回复功能,可以通过使用SmtpClient类和MailMessage类来发送自动回复邮件。以下是一个简单的示例代码:

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

class Program
{
    static void Main()
    {
        string host = "smtp.example.com"; // SMTP服务器地址
        int port = 587; // SMTP服务器端口
        string userName = "your_email@example.com"; // 发件人邮箱
        string password = "your_password"; // 发件人邮箱密码
        string from = "your_email@example.com"; // 发件人邮箱
        string to = "recipient@example.com"; // 收件人邮箱
        string subject = "自动回复"; // 邮件主题
        string body = "这是自动回复邮件"; // 邮件内容

        // 创建MailMessage对象
        MailMessage mail = new MailMessage(from, to, subject, body);

        // 创建SmtpClient对象
        SmtpClient client = new SmtpClient(host, port)
        {
            Credentials = new NetworkCredential(userName, password),
            EnableSsl = true
        };

        try
        {
            // 发送邮件
            client.Send(mail);
            Console.WriteLine("自动回复邮件发送成功!");
        }
        catch (Exception ex)
        {
            Console.WriteLine("发送邮件失败:" + ex.Message);
        }
    }
}

以上代码演示了如何使用C#发送一封简单的自动回复邮件,可以根据实际需求添加更多功能,如设置邮件的附件、抄送、密送等。请注意,发送邮件需要提供正确的SMTP服务器地址、端口、发件人邮箱、密码等信息。

0