温馨提示×

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

c#
小樊
91
2024-08-18 05:06:37
栏目: 编程语言

您可以使用System.Net.Mail命名空间中的SmtpClient类来发送带有附件的邮件。以下是一个示例代码,演示如何添加附件到SMTP邮件:

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

class Program
{
    static void Main()
    {
        // 发件人邮箱和密码
        string from = "your-email@example.com";
        string password = "your-password";

        // 创建邮件对象
        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);

        // 发送邮件
        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"替换为您的发件人邮箱和密码,将"recipient@example.com"替换为收件人邮箱,将"path-to-your-attachment-file"替换为附件文件的路径。然后,您可以运行该代码来发送带有附件的邮件。

0