C#中如何添加附件到SMTP郵件

c#
小樊
100
2024-08-18 05:06:37
欄目: 編程語言

您可以使用System.Net.Mail命名空間中的SmtpClient類來發(fā)送帶有附件的郵件。以下是一個(gè)示例代碼,演示如何添加附件到SMTP郵件:

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

class Program
{
    static void Main()
    {
        // 發(fā)件人郵箱和密碼
        string from = "your-email@example.com";
        string password = "your-password";

        // 創(chuàng)建郵件對(duì)象
        MailMessage mail = new MailMessage();
        mail.From = new MailAddress(from);
        mail.To.Add("recipient@example.com");
        mail.Subject = "Test Email with Attachment";
        mail.Body = "This is a test email with attachment";

        // 添加附件
        Attachment attachment = new Attachment("path-to-your-attachment-file");
        mail.Attachments.Add(attachment);

        // 發(fā)送郵件
        SmtpClient client = new SmtpClient("smtp.example.com");
        client.Port = 587;
        client.Credentials = new NetworkCredential(from, password);
        client.EnableSsl = true;

        try
        {
            client.Send(mail);
            Console.WriteLine("Email sent successfully.");
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }
}

在上面的代碼中,您需要將"your-email@example.com"和"your-password"替換為您的發(fā)件人郵箱和密碼,將"recipient@example.com"替換為收件人郵箱,將"path-to-your-attachment-file"替換為附件文件的路徑。然后,您可以運(yùn)行該代碼來發(fā)送帶有附件的郵件。

0