One thing that is quite clear is that many of the people that write in are called Don. The corollary is that if you want to see less bad code, change your name. What isn't clear (to me, from the submission) is what Don's company does.

Whatever they do, they send out a lot of template-based email. Even better, it's all environmentally friendly: they have a catch and release program. In case you'd like to start a similar program, here's some exceptional sample code written in C#.

 

  public Exception SendMail(
      string Template,
      Person Sender,
      Person Receiver,
      string Subject )
  {
     try
     {
        if ( Template.EndsWith(".tmp") == false )
           Template += ".tmp";

        string Body = _Templates[Template];

        // %%SomeWord%%
        Regex word = new Regex("\u0025\u0025[a-zA-Z]+\u0025\u0025");

        foreach ( Match match in word.Matches(Body) )
        {
           switch ( match.Value.Replace("%%", "").toLower() )
           {
              case "username":
                 Body = Body.Replace("%%username%%",  Receiver.UserName);
                 break;
              case "password":
                 Body = Body.Replace("%%password%%",  Receiver.Password);
                 break;
              case "FirstName":
                 Body = Body.Replace("%%firstname%%", Receiver.GivenName);
                 break;
              case "LastName":
                 Body = Body.Replace("%%lastname%%",  Receiver.FamilyName);
                 break;
           }
        }

        MailMessage mm = new MailMessage();
        mm.From    = Sender.WorkAddr;
        mm.To      = Receiver.HomeAddr;
        mm.Subject = Subject;
        mm.Body    = Body;

        SmtpMail.SmtpServer = "mx.domain.net";
        SmtpMail.Send(mm);
     }
     catch ( Exception ex ) { return ex; }

     return null;
  }

 

Perhaps I misunderstand the way that exceptions are supposed to work but I've never felt the need to return one, only throw them. While you've got the C# book open, go ahead and look up the semantics of string.Replace( string, string ). As an aside, pay close attention to the case of the switch-cases. And remember: it's not easy being green.

[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!