在ASP.NET中發送帶有附件的電子郵件,你可以使用System.Net.Mail
命名空間中的類。以下是一個簡單的示例,展示了如何使用C#和ASP.NET Core發送帶有附件的電子郵件:
System.Net.Mail
命名空間。MailMessage
類創建郵件消息,并使用Attachment
類添加附件。SmtpClient
類發送郵件。下面是一個示例代碼:
using System;
using System.IO;
using System.Net.Mail;
public class EmailService
{
private readonly string _smtpServer;
private readonly int _smtpPort;
private readonly string _smtpUsername;
private readonly string _smtpPassword;
public EmailService(string smtpServer, int smtpPort, string smtpUsername, string smtpPassword)
{
_smtpServer = smtpServer;
_smtpPort = smtpPort;
_smtpUsername = smtpUsername;
_smtpPassword = smtpPassword;
}
public void SendEmailWithAttachment(string to, string subject, string body, string filePath)
{
// 創建郵件消息
var message = new MailMessage
{
From = new MailAddress(_smtpUsername),
Subject = subject,
Body = body,
IsBodyHtml = true
};
// 添加收件人
message.To.Add(to);
// 添加附件
var attachment = new Attachment(filePath);
message.Attachments.Add(attachment);
// 配置SMTP客戶端
var smtpClient = new SmtpClient(_smtpServer, _smtpPort)
{
Credentials = new System.Net.NetworkCredential(_smtpUsername, _smtpPassword),
EnableSsl = true
};
try
{
// 發送郵件
smtpClient.Send(message);
Console.WriteLine("Email sent successfully.");
}
catch (Exception ex)
{
Console.WriteLine("Error sending email: " + ex.Message);
}
}
}
在這個示例中,SendEmailWithAttachment
方法接受四個參數:收件人的電子郵件地址、郵件主題、郵件正文和附件的文件路徑。它創建了一個MailMessage
對象,設置了發件人、收件人、主題和正文,然后添加了一個附件。最后,它使用SmtpClient
對象發送郵件。
要使用這個EmailService
類,你可以在你的ASP.NET Core控制器或頁面中創建一個實例,并調用SendEmailWithAttachment
方法來發送帶有附件的電子郵件。例如:
public class HomeController : Controller
{
private readonly EmailService _emailService;
public HomeController(EmailService emailService)
{
_emailService = emailService;
}
public IActionResult Index()
{
// 發送帶有附件的電子郵件
_emailService.SendEmailWithAttachment("recipient@example.com", "Test Email with Attachment", "This is the email body.", "path/to/attachment.txt");
return View();
}
}
請確保將示例代碼中的占位符替換為你自己的SMTP服務器和憑據信息,以及實際的收件人地址、郵件主題、郵件正文和附件文件路徑。