1

有人有适合 asp.net 4.0 c# 的电子邮件发送类吗?

目前我有类似下面的东西

你会在课堂上提出什么建议?

public static string sendEmail(string srEmailAddress, string srFrom, string srSubject, string srBodyHTML, string srBodyText)
{
    using (MailMessage Email = new MailMessage(new MailAddress("noreply@monstermmorpg.com", srFrom), new MailAddress(srEmailAddress)))
    {
        Email.IsBodyHtml = true;
        Email.SubjectEncoding = Encoding.UTF8;
        Email.BodyEncoding = Encoding.UTF8;
        Email.Subject = srSubject;

        using (AlternateView textPart = AlternateView.CreateAlternateViewFromString(srBodyText, Encoding.UTF8, "text/plain"))
        {
            textPart.TransferEncoding = System.Net.Mime.TransferEncoding.QuotedPrintable;
            Email.AlternateViews.Add(textPart);
        }

        using (AlternateView htmlPart = AlternateView.CreateAlternateViewFromString(srBodyHTML, Encoding.UTF8, "text/html"))
        {
            htmlPart.TransferEncoding = System.Net.Mime.TransferEncoding.QuotedPrintable;
            Email.AlternateViews.Add(htmlPart);
        }

        try
        {
            using (SmtpClient smtpClient = new SmtpClient())
            {
                smtpClient.Host = "127.0.0.1";
                smtpClient.Port = 25;
                smtpClient.Send(Email);
                return "True";
            }
        }
        catch (Exception E)
        {
            return E.Message.ToString();
        }
    }
}

c# 4.0 asp.net 4.0 IIS 7.5

4

1 回答 1

3

SmtpClient是正确的。仅供参考,您可以在构造函数中指定Hostand Port,但除此之外它很好。

using (SmtpClient smtpClient = new SmtpClient("127.0.0.1", 25))
{
    smtpClient.Send(Email);
    return true;
}

不过,我会更改返回类型...要么返回 a boolof trueor false,要么创建返回类型void并在调用代码中捕获异常。

编辑:回答你关于捕获异常的问题......而不是捕获Exception你的sendEmail方法内部(顺便说一句,这应该SendEmail遵循 C# 命名标准),你应该从你调用的地方捕获异常sendEmail

try
{
    sendEmail(/*whatever parameters you need */);
}
catch(Exception e)
{
    //Do whatever you need to do with the exception... Display a notification
    // to the user, etc
}

此外,您应该尽量不要捕获所有异常 - 只捕获您期望的异常 - 在这种情况下很可能是SmtpException.

于 2012-12-26T16:10:01.693 回答