C#发送电子邮件 - 完整性检查

时间:2010-08-16 07:16:19

标签: c# email

对电子邮件实施的完整性检查请:-)我错过了哪些明显的错误?

string supplierOfThisMaterialEmailAddress = "davexxx@gmail.com"; // TODO


string htmlBodyIncludingReplacements = "<html><head><title>E-mail</title></head><body><div>.  There has been a request on the hello.co.nz website for: " + txtMaterialDescription.Text +
            "<br />Full Name: <b>" + fullName + "</b><br />" +
            etc..";

        string textOnlyBodyIncludingReplacements = "E-mail.  There has been a request on the freematerials.co.nz website for: " + txtMaterialDescription.Text +
            "Full Name: " + fullName +
            "etc..";

        string subject = "Someone has contacted you";

        CustomMailer mailer = new CustomMailer();
        string result = mailer.SendEmail(subject, htmlBodyIncludingReplacements, supplierOfThisMaterialEmailAddress, textOnlyBodyIncludingReplacements);
        if (result != null)
            lblMessage.Text = result;
        else
            lblMessage.Text = "Thank you - email has been sent";

上课:

public class CustomMailer
    {
        public string SendEmail(string subject, string htmlBodyIncludingReplacements, string emailTo, string textOnlyBodyIncludingReplacements)
        {
            try
            {
                MailAddress sender = new MailAddress("dave@hello.co.nz", "Dave Mateer");
                emailTo = "dave@hello.co.nz"; // testing
                MailAddress recipient = new MailAddress(emailTo, null);

                MailMessage message = new MailMessage(sender, recipient);
                message.Subject = subject;

                AlternateView textView = AlternateView.CreateAlternateViewFromString(textOnlyBodyIncludingReplacements, null, "text/plain");
                AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlBodyIncludingReplacements, null, MediaTypeNames.Text.Html);
                message.AlternateViews.Add(textView);
                message.AlternateViews.Add(htmlView);

                SmtpClient client = new SmtpClient();
                client.Send(message);
            }

            catch (Exception ex)
            {
                throw new Exception();
            }
            return null;
        }
    }

2 个答案:

答案 0 :(得分:3)

乍一看,捕获一般的异常对象并抛出一个新对象将会产生因SendEmail引发的任何异常而产生的影响。

其余的看起来还不错。

答案 1 :(得分:0)

你应该改变 catch (Exception ex) { throw new Exception(); } 致:

catch (Exception ex)
            {
                throw;
            }

因为否则会丢失所引发的原始例外所带来的所有数据