logo

A Simple Email Class in C#

You can't get far in any web language without needing to send emails from your scripts. If you're like me then you create and send emails from scripts all the time.

That's why I find it easier to always have an "email class" in whatever language I'm working in. In the past I've shared a LotusScript email class and a Java email class.

Both of these classes were aimed at Domino, which has its own in-built SMTP server, so all you had to do was call document.Send() and let Domino do the rest. Life is easy with Domino!

With ASP.NET you don't have an in-built SMTP server. You have to rely on an SMTP server elsewhere to send your emails. This could be Microsoft's SMTP service running on the same server or it could be a third-party server running elsewhere. Either way you need to connect a port to it and know the username/password of a user allowed to route email through it.

It took me a while to get my head round the extra complication in sending mails from ASP.NET apps, but as soon as I did I then set about writing a class for C#.

Using the class looks is as simple as this:

Email mail = new Email();

mail.to = "foo@bar.com";

mail.subject = "Your Ticket Has Been Received";

mail.body = "<p>We have received your ticket.</p>" +
        "<p>Your reference number is " + someString + ".</p>" +
        "<p>We'll be in touch shortly...</p>";

mail.send();

Pretty much exactly the same as the Java version. Makes sending email a breeze.

The C# code that allows us to send emails this way looks like this:

using System;
using System.Net.Mail;
using System.Configuration;

namespace ACME.Messaging
{
    public class Email
    {
        private MailMessage m;

        public Email()
        {
            m = new MailMessage();

            m.Sender = m.From = new MailAddress(
                        ConfigurationManager.AppSettings"SendMailMessagesFromAddress".ToString()
                );
                
            m.IsBodyHtml = true;
        }

        public bool isHTML
        {
            set
            {
                m.IsBodyHtml = value;
            }
        }

        public string to
        {
            set
            {
                m.To.Add(value);
            }
        }

        public string from
        {
            set
            {
                m.Sender = m.From = new MailAddress(value);
            }
        }
        public string subject
        {
            set
            {
                m.Subject = value;
            }
        }

        public string body
        {
            get
            {
                return body;
            }
            set
            {
                m.Body = value;

            }
        }

        public void send()
        {
            try
            {
                SmtpClient sc = new SmtpClient();
                sc.Host = ConfigurationManager.AppSettings"SendMailSTMPHostAddress".ToString();
                sc.DeliveryMethod = SmtpDeliveryMethod.Network;
                sc.UseDefaultCredentials = false;
                sc.Port = 25;
                sc.Credentials = new System.Net.NetworkCredential(
                        ConfigurationManager.AppSettings"SendMailSMTPUserName".ToString(), 
                        ConfigurationManager.AppSettings"SendMailSMTPUserPassword".ToString()
                );

                sc.Send(m);
            }
            catch (Exception e)
            {
                //Log error somehow
            }
        }

    }
}

It's fairly basic and only caters for plain text or HTML emails (not both) as is. It functions just fine for now though.

There are lots of reference to configuration settings in the code. I keep these values in the Web.config file, which looks a bit like this:

<configuration>
    <appSettings>
        <add key="SendMailMessagesFromAddress" 
                value="Jake &lt;jake@foo.com&gt;"/>
        <add key="SendMailSTMPHostAddress" value="smtp.googlemail.com"/>
        <add key="SendMailSMTPUserName" value="jake"/>
        <add key="SendMailSMTPUserPassword" value="foofoolarue"/>
    </appSettings>
</configuration>

As you can see you can use a Google Mail account to send email. Or you could put "localhost" in the SMTP host address setting and set up a local SMPT server on the same box if you like.  YMMV.

Comments

    • avatar
    • Paul
    • Tue 28 Sep 2010 04:35 AM

    Hi Jake, for error logging take a look at elmah - brief how to here http://tiny.cc/zqiu3 Just started using it for projects and impressed so far.

  1. These kind of utility classes are always useful.

    Maybe you are in need of an ABAP version some day?

    (This is just one method of the class but maybe you can imagine what it does...)

    method send_mail.

    data:

    lr_sender type ref to cl_cam_address_bcs,

    lv_address type ad_smtpadr,

    lv_type type so_obj_tp,

    lv_sender type uname,

    lr_ex_send_req type ref to cx_send_req_bcs,

    lr_ex_address type ref to cx_address_bcs,

    lr_ex_doc type ref to cx_document_bcs,

    lv_result type os_boolean.

    lv_type = im_type.

    lv_sender = im_sender.

    if lv_type is initial.

    lv_type = 'HTM'. "HTML-Mail

    endif.

    if lv_sender is initial.

    lv_sender = sy-uname.

    endif.

    try .

    * Maildokument erzeugen

    document = cl_document_bcs=>create_document(

    i_type = im_type

    i_text = body

    i_subject = subject ).

    * Dokument an Senderequest hängen

    call method send_request->set_document( document ).

    * Sender Objekt erzeugen und Sender hinzufügen

    sender_object = cl_sapuser_bcs=>create( lv_sender ).

    call method send_request->set_sender

    exporting

    i_sender = sender_object.

    lv_address = im_recipient.

    * Empfänger hinzufügen

    recipient = cl_cam_address_bcs=>create_internet_address( lv_address ).

    call method send_request->add_recipient

    exporting

    i_recipient = recipient

    i_express = ' '

    i_copy = ' '

    i_blind_copy = ' '.

    send_request->set_send_immediately( 'X' ).

    * Einstellungen für die Statusrückmeldung

    send_request->set_status_attributes( 'E' ).

    * Dokument senden

    lv_result = send_request->send( ).

    catch cx_send_req_bcs into lr_ex_send_req.

    clear log_msg.

    log_msg-msgv1 = lr_ex_send_req->get_text( ).

    log->bal_msg_add( is_msg = log_msg ).

    catch cx_address_bcs into lr_ex_address.

    clear log_msg.

    log_msg-msgv1 = lr_ex_address->get_text( ).

    log->bal_msg_add( is_msg = log_msg ).

    catch cx_document_bcs into lr_ex_doc.

    clear log_msg.

    log_msg-msgv1 = lr_ex_doc->get_text( ).

    log->bal_msg_add( is_msg = log_msg ).

    endtry.

    clear log_msg.

    message i000 with lv_result into log_msg-msgv1.

    log->bal_msg_add( is_msg = log_msg ).

    commit work.

    endmethod.

    • avatar
    • Ian
    • Tue 28 Sep 2010 07:15 AM

    If you wanted to use this with your new gmail then you'll probably be needing a bunch more settings, port number for starters.

      • avatar
      • Jake Howlett
      • Tue 28 Sep 2010 07:18 AM

      Oops. I should point out that I quickly changed the app settings to point to something other than were mine do point and chose gmail as an example without thinking about whether it would work.

      Thanks for the heads up!

  2. But it can get so much better. You can actually just upload an HTML file instead of writing HTML in body field. You can do a replacement on it, meaning that your HTML file contains something like <@@TITLE@@> and you can replace that with significant value.

    Also, if you have everything in HTML files, you don't need to change code once the project is up and running. Just replace contents of your HTML file and totaly different mail will be sent.

    Tbh, I wish that Lotus would posess such an easy way to do this.

      • avatar
      • Jake Howlett
      • Wed 29 Sep 2010 02:29 AM

      Interesting. I just did a bit of looking and found this article which discusses not only your idea but also alternate text/html views as well as embedding images. All so simple compared to Domino.

      http://www.search-this.com/2009/02/05/aspnet-sending-email-both-in-html-and-plain-text/

      Show the rest of this thread

    • avatar
    • Jason Boardman
    • Fri 1 Oct 2010 08:17 AM

    At our firm we've written an email web service. The service allows you to create xsl templates, and send emails using those templates. We've then created a wcf project to hook into the web service and provide friendly hooks into it all. Its more complicated initially but once everything is in place the project can be ported from one solution to another very easily.

  3. There are a few errors in code.

    ConfigurationManager.AppSettings"SendMailSMTPUserName".ToString()

    must be written as

    ConfigurationManager.AppSettings["SendMailSMTPUserName"]

Your Comments

Name:
E-mail:
(optional)
Website:
(optional)
Comment:


About This Page

Written by Jake Howlett on Tue 28 Sep 2010

Share This Page

# ( ) '

Comments

The most recent comments added:

Skip to the comments or add your own.

You can subscribe to an individual RSS feed of comments on this entry.

Let's Get Social


About This Website

CodeStore is all about web development. Concentrating on Lotus Domino, ASP.NET, Flex, SharePoint and all things internet.

Your host is Jake Howlett who runs his own web development company called Rockall Design and is always on the lookout for new and interesting work to do.

You can find me on Twitter and on Linked In.

Read more about this site »

More Content