ASP 项目中哪里有电子邮件服务?

Where to have email service in ASP project?

我有一个 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 的文件,使用上面的代码,或者 best/correct 的做法是什么,以保持代码干燥?

使用如下静态方法创建 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");