我正在浏览我的应用程序,试图清理一些发送电子邮件的代码。我开始创建我自己的 emailer 包装类,但后来我想一定有一个标准的 emailer 类在某个地方。我做了一些搜索,但找不到任何东西。

另外,任何地方都有这样的代码库吗?

编辑 :对不起,让我澄清一下。

我不想在我需要发送电子邮件的任何时候在我的代码中包含这个:

System.Web.Mail.MailMessage message=new System.Web.Mail.MailMessage();
message.From="from e-mail";
message.To="to e-mail";
message.Subject="Message Subject";
message.Body="Message Body";
System.Web.Mail.SmtpMail.SmtpServer="SMTP Server Address";
System.Web.Mail.SmtpMail.Send(message);

我创建了一个名为 Emailer 的类,其中包含以下功能:
SendEmail(string to, string from, string body)
SendEmail(string to, string from, string body, bool isHtml)

所以我可以在我的代码中添加一行来发送电子邮件:
Emailer.SendEmail("name@site.com", "name2@site.com", "My e-mail", false);

我的意思是,它并不太复杂,但我认为有一个标准的、公认的解决方案。

最佳答案

像这样的东西?

using System;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using MailMessage=System.Net.Mail.MailMessage;

class CTEmailSender
{
    string MailSmtpHost { get; set; }
    int MailSmtpPort { get; set; }
    string MailSmtpUsername { get; set; }
    string MailSmtpPassword { get; set; }
    string MailFrom { get; set; }

    public bool SendEmail(string to, string subject, string body)
    {
        MailMessage mail = new MailMessage(MailFrom, to, subject, body);
        var alternameView = AlternateView.CreateAlternateViewFromString(body, new ContentType("text/html"));
        mail.AlternateViews.Add(alternameView);

        var smtpClient = new SmtpClient(MailSmtpHost, MailSmtpPort);
        smtpClient.Credentials = new NetworkCredential(MailSmtpUsername, MailSmtpPassword);
        try
        {
            smtpClient.Send(mail);
        }
        catch (Exception e)
        {
            //Log error here
            return false;
        }

        return true;
    }
}

关于c# - 标准电子邮件类?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4976076/

10-17 02:39