An improved Email Class for .Net

Nothing too special, just combining a couple classes for a more logical approach to email

Most all of my websites/projects require some email to be sent. The System.Net.Mail class is great, but to me, sending an email is not a logical process. Also, the fact that you will likely only use one smtp server throughout a project seems to make the SmtpClient setup a bit repetetive to me. With my class you can setup and send an email as simply as this:
new Email("", "", "You stink", "here are the reasons why...").Send();

Now you wouldn't have to do it all in one line, but this demonstrates that the smtp is already taken care of in the background, this simply builds on the SmtpClient class. Here is the code:
using System;
using System.Net.Mail;

public class Email : SmtpClient
  public MailMessage Message { get; private set; }

  // keep in mind I don't recommend hard coding these values in, this is just for example

  public Email(string to, string from, string subject, string body) : base("", 587)
    // this next line is only necessary if you want to enable SSL
    this.Credentials = new System.Net.NetworkCredential("", "crap_nugget");
    this.Message = new MailMessage(from, to, subject, body);

  public void Send()
    try { this.Send(Message); }
    catch (Exception ex) { throw ex; }

Notice that I do not recommend hard-coding your username/password and/or smtp server in the class -- but it will work. Also, this example is to use Gmail, but it will work just as well with another SMTP (I use this with a local Exchange server some times).

Just polishing up an already good tool and making it a bit better.

Pingbacks and trackbacks (1)+

Comments are closed