ASP.NET(ASP)服務可以通過使用內置的System.Net.Mail
命名空間來處理郵件發送。以下是一個簡單的示例,展示了如何使用ASP.NET服務發送電子郵件:
System.Net.Mail
命名空間。在Web.config
文件中添加以下引用:<system.net>
<mailSettings>
<smtp from="your_email@example.com" deliveryMethod="Network" >
<network host="smtp.example.com" port="587" userName="your_email@example.com" password="your_password" />
</smtp>
</mailSettings>
</system.net>
請將your_email@example.com
和your_password
替換為您的SMTP服務器憑據。
SendEmail
的方法,該方法接受收件人電子郵件地址、主題和正文作為參數,并使用System.Net.Mail
命名空間發送電子郵件:using System;
using System.Net;
using System.Net.Mail;
public class EmailService
{
public void SendEmail(string toEmail, string subject, string body)
{
MailMessage mail = new MailMessage();
SmtpClient smtpClient = new SmtpClient();
mail.From = new MailAddress("your_email@example.com");
mail.To.Add(toEmail);
mail.Subject = subject;
mail.Body = body;
smtpClient.Host = "smtp.example.com";
smtpClient.Port = 587;
smtpClient.Credentials = new NetworkCredential("your_email@example.com", "your_password");
smtpClient.EnableSsl = true;
try
{
smtpClient.Send(mail);
Console.WriteLine("Email sent successfully!");
}
catch (Exception ex)
{
Console.WriteLine("Error sending email: " + ex.Message);
}
}
}
SendEmail
方法。例如,在一個ASP.NET Web頁面的代碼后臺中:protected void ButtonSendEmail_Click(object sender, EventArgs e)
{
EmailService emailService = new EmailService();
string toEmail = "recipient@example.com";
string subject = "Test email";
string body = "This is a test email sent from an ASP.NET service.";
emailService.SendEmail(toEmail, subject, body);
}
在這個示例中,當用戶點擊名為ButtonSendEmail
的按鈕時,將調用SendEmail
方法并發送一封測試電子郵件。請確保在Web.config
文件中配置了正確的SMTP服務器設置。