代码之家  ›  专栏  ›  技术社区  ›  Dave Mateer

发送电子邮件-健康检查

  •  1
  • Dave Mateer  · 技术社区  · 15 年前

    请检查电子邮件实现的健全性:-)有什么明显的遗漏吗?

    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 回复  |  直到 15 年前
        1
  •  3
  •   Matt B    15 年前

    乍一看,捕获一个一般的异常对象并抛出一个新的异常对象,将有一个吞食由 SendEmail .

    剩下的看起来不错。

        2
  •  0
  •   Adibe7    15 年前

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

    catch (Exception ex)
                {
                    throw;
                }
    

    因为否则,您将丢失与抛出的原始摘要一起提供的所有数据