Jan 26 2009

A C# class to send email via gmail

Category: Kurtis @ 06:29

The easiest and cheapest way to get a good email solution up and running for your small business is to sign up for Google Apps. This basically gives your employees an email address at your domain through gmail. So, you get lots of storage, great spam protection, and it's free.

Most small businesses on the web will need to be able to send automated mails through their Google Apps account (I know I do). Below is a class I created in C# that does just that.

public class Email
{
    public string Subject { get; set; }
    public string Body { get; set; }
    public string To { get; set; }
    public string From { get; set; }

    public Email()
    {
        
    }

    public Email(string from, string to, string subject, string body)
    {
        From = from;
        To = to;
        Subject = subject;
        Body = body;
    }

    public bool Send()
    {
        MailMessage m = new MailMessage();
        m.To.Add(new MailAddress(To));
        m.From = new MailAddress(From);
        m.Subject = Subject;

        m.Body = Body;

        m.IsBodyHtml = true;

        try
        {
            SmtpClient client = new SmtpClient();
            client.EnableSsl = true;
            client.UseDefaultCredentials = false;
            client.Credentials = new NetworkCredential("user@domain.com", "password");
            client.Port = 587;//or use 465            
            client.Host = "smtp.gmail.com";
            object userState = m;
            client.Send(m);
        }
        catch (Exception)
        {
            return false;
        }

        return true;
    }
}

 It is used like:

Email m = new Email();
m.To = "to@example.com";
m.From = "from@example.com";
m.Subject = "This is the subject of the email";

m.Body = "This is the email body.";

if (!m.Send())
    throw new Exception("Email could not be sent!");

Tags: , ,