溫馨提示×

c# office如何自動化郵件發送

c#
小樊
125
2024-07-26 18:35:17
欄目: 編程語言

在C#中自動化發送郵件可以使用System.Net.Mail命名空間中的SmtpClient類來實現。以下是一個簡單的示例代碼:

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

class Program
{
    static void Main()
    {
        // 設置發件人和收件人信息
        string from = "your-email@example.com";
        string to = "recipient@example.com";
        string subject = "Test Email";
        string body = "This is a test email.";

        // 創建郵件對象
        MailMessage mail = new MailMessage(from, to, subject, body);

        // 創建SMTP客戶端
        SmtpClient client = new SmtpClient("smtp.yourmailserver.com");

        // 設置發件人郵箱的用戶名和密碼
        client.Credentials = new NetworkCredential("your-email@example.com", "your-password");

        // 發送郵件
        try
        {
            client.Send(mail);
            Console.WriteLine("Email sent successfully!");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Failed to send email: " + ex.Message);
        }
    }
}

在上面的代碼中,你需要替換示例中的發件人郵箱地址、SMTP服務器地址、發件人郵箱用戶名和密碼。然后運行程序即可自動發送郵件。請確保你的郵箱設置允許使用SMTP客戶端進行發件。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女