Wednesday, May 29, 2013

Sending Email Using C#

I thought I would change things up a bit today and actually talk about a little bit of C#.  I currently use Visual C# at work for some projects and some of those include sending email.  First, you need to make sure to add the System.Net.Mail namespace to your C# project.  This namespace gives you a list of different classes you can use to send email.  Once the namespace has been added, here is the code I use to create a method to send email.  It allows you to provide the body, subject and an attachment to the method:

public static string SendEmail(String body, String subject, Attachment attachment)
        {
            SmtpClient smtp = new SmtpClient("mail.companyname.com");

            string fromEmail = "my.email@companyname.com";

            MailMessage objEmail = new MailMessage();

            objEmail.IsBodyHtml = true;

            objEmail.To.Add("to.email@companyname.com");

            objEmail.From = new MailAddress(fromEmail, "My Name");

            objEmail.Subject = subject;

            objEmail.Body = body;

            objEmail.Attachments.Add(attachment);

            try
            {
             
                smtp.Send(objEmail);

                return "true";

            }
         
            catch (Exception exc)
         
            {
                return exc.Message;
             }

        }

If you wanted to create a method that sends an email, but doesn't include an attachment, use the following:

public static string SendEmail(String body, String subject)
        {
            SmtpClient smtp = new SmtpClient("mail.companyname.com");

            string fromEmail = "my.email@companyname.com";

            MailMessage objEmail = new MailMessage();

            objEmail.IsBodyHtml = true;

            objEmail.To.Add("to.email@companyname.com");

            objEmail.From = new MailAddress(fromEmail, "My Name");

            objEmail.Subject = subject;

            objEmail.Body = body;

            try
            {
             
                smtp.Send(objEmail);

                return "true";

            }
         
            catch (Exception exc)
         
            {
                return exc.Message;
             }

        }

These methods are pretty basic, since the email addresses are hard-coded.  You will want to create your own method if your "to" email is dynamic or you want to pass the email values into the method.

No comments:

Post a Comment