我有一个WEB Api项目。项目中的不同位置,它会向用户发送电子邮件。
代码看起来像这个标准代码:
MailMessage mail = new MailMessage("you@yourcompany.com", "user@hotmail.com");
SmtpClient client = new SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "smtp.google.com";
mail.Subject = "this is a test email.";
mail.Body = "this is my test email body";
client.Send(mail);
在我的项目中,创建和使用此方法的正确位置在哪里?在名为“Services”的文件夹中,使用名为EmailService.cs的文件,使用上面的代码,或者保持代码DRY的最佳/正确做法是什么?
答案 0 :(得分:0)
使用静态方法创建utils
,如下所示:
public static void SendEmail(string subject, string body)
{
using (var client = new SmtpClient(utilities.EmailHost, 25))
using (var message = new MailMessage()
{
From = new MailAddress(utilities.FromEmail),
Subject = subject,
Body = body
})
{
foreach (var address in utilities.RecipList.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries))
message.To.Add(address);
client.Send(message);
}
}
调用方法这样的基本内容
SendEmail("this is a test email.","this is my test email body");