Click here to Skip to main content
15,897,519 members
Articles / Programming Languages / C#

WCF Service to Send Emails With Attachments

Rate me:
Please Sign up or sign in to vote.
4.63/5 (19 votes)
11 Nov 2013CPOL4 min read 84.3K   20   61  
Setting, configuring, and calling a WCF service to send emails with multiple file attachments.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Xml.Linq;

namespace EmailService
{

    public class Mail : IMail
    {
        private static string SMTP_SERVER = "smtp.gmail.com";
        private static int SMTP_PORT = 587;

        
        public string SendEmail(MailAddress gmailFrom, string gmailUserPassword, MailAddress[] emailTo, MailAddress[] ccTo, string subject, string body, bool isBodyHtml, MailPriority priority, FileAttachment[] attachments)
        {
            XElement resultXml = new XElement("SendEmailResult");
            XElement codeXml = new XElement("Code");
            resultXml.Add(codeXml);
            XElement messageXml = new XElement("Message");
            resultXml.Add(messageXml);
            XElement isSuccessfulXml = new XElement("IsSuccessful");
            resultXml.Add(isSuccessfulXml);


            if (gmailFrom == null)
            {
                codeXml.Value = "10";
                messageXml.Value = "Email From is not valid";
                isSuccessfulXml.Value = false.ToString();
                return resultXml.ToString();
            }
            if (String.IsNullOrEmpty(gmailUserPassword))
            {
                codeXml.Value = "15";
                messageXml.Value = "Password is required";
                isSuccessfulXml.Value = false.ToString();
                return resultXml.ToString();
            }
            if (emailTo == null || emailTo.Length == 0)
            {
                codeXml.Value = "20";
                messageXml.Value = "Email-To not provided";
                isSuccessfulXml.Value = false.ToString();
                return resultXml.ToString();
            }


            SmtpClient smtpClient = new SmtpClient(SMTP_SERVER, SMTP_PORT);
            smtpClient.EnableSsl = true;
            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = new NetworkCredential(gmailFrom.Address, gmailUserPassword);

            using (MailMessage message = new MailMessage())
            {
                message.From = gmailFrom;
                message.Subject = subject == null ? "" : subject;
                message.IsBodyHtml = isBodyHtml;
                message.Body = body == null ? "" : body;
                message.Priority = priority;

                foreach (MailAddress email in emailTo)
                {
                    message.To.Add(email);
                }

                if (ccTo != null && ccTo.Length > 0)
                {
                    foreach (MailAddress emailCc in ccTo)
                    {
                        message.CC.Add(emailCc);
                    }
                }

                //List to store pointers to memoty streams. Not really needed -- for paranoid programmers' mental comfort
                List<MemoryStream> memStreamList = new List<MemoryStream>();

                if (attachments != null && attachments.Length > 0)
                {
                    foreach (FileAttachment fileAttachment in attachments)
                    {
                        fileAttachment.FileName = Tools.CleanUpFileName(fileAttachment.FileName);

                        if (fileAttachment.FileContentBase64 != null && fileAttachment.FileContentBase64.Trim().Length > 0)
                        {
                            try
                            {
                                MemoryStream memAttachm = new MemoryStream(Convert.FromBase64String(fileAttachment.FileContentBase64));
                                memStreamList.Add(memAttachm); //Add stream to the list to dispose of properly after email is send. 
                                Attachment attach = new Attachment(memAttachm, fileAttachment.FileName);
                                message.Attachments.Add(attach);
                            }
                            catch (Exception ex) //Just in case
                            {
                                Console.WriteLine(ex.Message);
                                //TODO: add error message to output xml 
                            }
                        }
                    }
                }

                try
                {
                    smtpClient.Send(message);
                    codeXml.Value = "0";
                    messageXml.Value = "OK";
                    isSuccessfulXml.Value = true.ToString();
                }
                catch (Exception ex)
                {
                    smtpClient.Send(message);
                    codeXml.Value = "70";
                    messageXml.Value = ex.Message;
                    isSuccessfulXml.Value = false.ToString();
                }
                finally
                {
                    //Dispose of any open memory streams. Really, not needed for managed memory stream... for paranoid programmers only
                    for (int i = 0; i < memStreamList.Count; i++)
                    {
                        if (memStreamList[i] != null)
                        {
                            memStreamList[i].Dispose();
                        }
                    }
                }
            }

            return resultXml.ToString();
        }

        //Overloaded methods are not allowed in WCF, hence, a different name
        public string SendSimpleEmail(MailAddress gmailFrom, string gmailUserPassword, MailAddress[] emailTo, string subject, string body)
        {
            MailAddress[] ccTo = null;
            bool isBodyHtml = false;
            MailPriority priority = MailPriority.Normal;
            FileAttachment[] attachments = null;

            string resultXml = this.SendEmail(gmailFrom, gmailUserPassword, emailTo, ccTo, subject, body, isBodyHtml, priority, attachments);
            return resultXml;
        }


        //Used for debugging WCF service
        public string GetDate() 
        {
            return DateTime.Now.ToString();
        }



        //Old code
        //public int SendEmail(string gmailUserAddress, string gmailUserPassword, string[] emailTo, string[] ccTo, string subject, string body, bool isBodyHtml, FileAttachment[] attachments)
        //{
        //    int result = -100;
        //    if (gmailUserAddress == null || gmailUserAddress.Trim().Length == 0)
        //    {
        //        return 10;
        //    }
        //    if (gmailUserPassword == null || gmailUserPassword.Trim().Length == 0)
        //    {
        //        return 20;
        //    }
        //    if (emailTo == null || emailTo.Length == 0)
        //    {
        //        return 30;
        //    }

        //    string tempFilePath = "";
        //    List<string> tempFiles = new List<string>();

        //    SmtpClient smtpClient = new SmtpClient(SMTP_SERVER, SMTP_PORT);
        //    smtpClient.EnableSsl = true;
        //    smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
        //    smtpClient.UseDefaultCredentials = false;
        //    smtpClient.Credentials = new NetworkCredential(gmailUserAddress, gmailUserPassword);

        //    using (MailMessage message = new MailMessage())
        //    //Message object must be disposed before deleting temp attachment files
        //    {
        //        message.From = new MailAddress(gmailUserAddress);
        //        message.Subject = subject == null ? "" : subject;
        //        message.Body = body == null ? "" : body;
        //        message.IsBodyHtml = isBodyHtml;

        //        foreach (string email in emailTo)
        //        {
        //            //TODO: Check email is valid
        //            message.To.Add(email);
        //        }

        //        if (ccTo != null && ccTo.Length > 0)
        //        {
        //            foreach (string emailCc in ccTo)
        //            {
        //                //TODO: Check CC email is valid
        //                message.CC.Add(emailCc);
        //            }
        //        }

        //        if (attachments != null && attachments.Length > 0)
        //        {
        //            foreach (FileAttachment fileAttachment in attachments)
        //            {
        //                byte[] bytes = System.Convert.FromBase64String(fileAttachment.FileContentBase64);
        //                MemoryStream memAttachment = new MemoryStream(bytes);
        //                Attachment attachment = new Attachment(memAttachment, fileAttachment.Info.Name);
        //                message.Attachments.Add(attachment);
        //            }
        //        }

        //        try
        //        {
        //            smtpClient.Send(message);
        //            result = 0;
        //        }
        //        catch
        //        {
        //            result = 60;
        //        }
        //    }

        //    return result;
        //}

    }

}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions