您可以使用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"替換為附件文件的路徑。然后,您可以運行該代碼來發送帶有附件的郵件。