Send Email With or Without Attachment using WCF

Send Email With or Without Attachment using WCF is quite simple. We can either attach a document while sending email or send without attachment.

First create services for Send email. Add below code in IMyServices.cs

[ServiceContract]
[XmlSerializerFormat]
  
public interface IMyServices
{
#region EmailService
[OperationContract]
string SendEmailWithOrWithoutAttachement(string[] emailToAddress, string subject,      string body, bool isBodyHtml, string[] ccemailTo, byte[] byteData);      
#endregion
}

In order to send email add below code in the web.config file.

<appSettings>
    <add key ="SMTP_SERVER" value="smtp.gamil.com"/>
    <add key ="SMTP_PORT" value="25"/>
    <add key ="UserName" value="gmailusername"/>
    <add key ="UserPassword" value="gmailpassword"/>
  </appSettings>
 <system.serviceModel>
    <services>
      <service name="NameOfServiceApplication.MyServices">
        <endpoint address=""
                  contract="NameOfServiceApplication.IMyServices"
                  binding="basicHttpBinding"
                  bindingConfiguration="EmailBinding" />
      </service>
    </services>
   
    <bindings>      
      <basicHttpBinding>
        <binding name="EmailBinding"
                closeTimeout="00:01:00"
                openTimeout="00:01:00"
                receiveTimeout="00:01:00"
                sendTimeout="00:01:00"
                allowCookies="false"
                bypassProxyOnLocal="false"
                hostNameComparisonMode="StrongWildcard"
                maxBufferSize="2147483647"
                maxBufferPoolSize="2147483647"
                maxReceivedMessageSize="2147483647"
                messageEncoding="Text"
                textEncoding="utf-8"
                transferMode="Buffered"
                useDefaultWebProxy="true">
          <readerQuotas
                 maxDepth="32"
                 maxStringContentLength="2147483647"
                 maxArrayLength="20971520"
                 maxBytesPerRead="4096"
                 maxNameTableCharCount="16384" />
          <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None"
                realm="" />
            <message clientCredentialType="UserName" algorithmSuite="Default" />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>    
  </system.serviceModel>

Add the gmail user name and password in web.config file in order to send email using smtp.

<system.net>
    <mailSettings>
      <smtp deliveryMethod="Network" from="emailid">
        <network host="smtp.gamil.com" userName="emailid" password="password" port="25" enableSsl="false"/>
      </smtp>
    </mailSettings>    
</system.net>

Add below code in MyServices.svc.cs file

public class MyServices: IMyServices
    {
  #region EmailService

        private static string SMTP_SERVER = ConfigurationManager.AppSettings["SMTP_SERVER"];
        private static int SMTP_PORT = Convert.ToInt32(ConfigurationManager.AppSettings["SMTP_PORT"]);

        public string SendEmailWithOrWithoutAttachement(string[] emailToAddress, string subject, string body, bool isBodyHtml, string[] ccemailTo, byte[] byteData)
        {
            string UserName = ConfigurationManager.AppSettings["UserName"];
            string UserPassword = ConfigurationManager.AppSettings["UserPassword"];
            MemoryStream AttachmentMemoryStream = null;

            if (byteData != null)
           {
                //convert the byte array to Memory stream so that it can be used as attachment
                AttachmentMemoryStream = new MemoryStream(byteData);
           }

           if (emailToAddress == null || emailToAddress.Length == 0)
           {
                return "Email To Address Empty";
           }

            SmtpClient smtpClient = new SmtpClient(SMTP_SERVER, SMTP_PORT);
            smtpClient.Host = ConfigurationManager.AppSettings["SMTP_SERVER"];
            smtpClient.EnableSsl = false;
           smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtpClient.UseDefaultCredentials = true;
           smtpClient.Credentials = new NetworkCredential(UserName, UserPassword);

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

               foreach (string email in emailToAddress)
               {
                   message.To.Add(email);
                }
               if (ccemailTo != null && ccemailTo.Length > 0)
               {
                    foreach (string emailCc in ccemailTo)
                   {
                       //code to check if the email cc is empty or not
                       if (emailCc != "")
                       {
                            message.CC.Add(emailCc);
                        }
                   }
                }
                if (byteData != null)
                {
                    //code to add attachments in email
                    message.Attachments.Add(new Attachment(AttachmentMemoryStream, "TestDocument", "text/plain"));
               }
               try
                {
                    smtpClient.Send(message);
                    return "success";
               }
               catch (FaultException fex)
              {
                   throw fex;
               }
            }
        }       
        #endregion
}

Add a new web application and add a new web form. Add below code in aspx page of the web form.

<div class="entry-content">
        <h2>
            Email</h2>
        <asp:Label runat="server" ID="lblTo">To</asp:Label>
        <asp:TextBox ID="txt_to" runat="server" CssClass="TextBox" AutoComplete="off" PlaceHolder="eg: sam_01@gmail.com"
            Width="215"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RFVto" runat="server" ControlToValidate="txt_to"
            Display="Dynamic" SetFocusOnError="true" CssClass="failureNotification" ErrorMessage="Please enter email Id."
            ToolTip="Please enter email Id" ForeColor="Red" ValidationGroup="sbmitbtn"></asp:RequiredFieldValidator>
        <asp:RegularExpressionValidator ID="REVto" ValidationGroup="sbmitbtn" runat="server"
            Display="Dynamic" SetFocusOnError="true" ToolTip="Email Id invalid." ErrorMessage="Email Id invalid."
            ValidationExpression="((\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*([, ])*)*"
            ForeColor="Red" ControlToValidate="txt_to"></asp:RegularExpressionValidator>
        <br />
        <br />
        <asp:Label runat="server" ID="lblCC">Cc</asp:Label>
        <asp:TextBox ID="txt_cc" runat="server" AutoComplete="off" CssClass="TextBox" PlaceHolder="eg: sam_01@gmail.com"
            Width="215"></asp:TextBox>
        <asp:RegularExpressionValidator ID="REVcc" ValidationGroup="sbmitbtn" Display="Dynamic"
            SetFocusOnError="true" runat="server" ToolTip="Please check email id/id's are wrong."
            ErrorMessage="Please check email id/id's are wrong" ValidationExpression="((\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*([, ])*)*"
            ForeColor="Red" ControlToValidate="txt_cc"></asp:RegularExpressionValidator>
        <br />
        <br />
        <br />
        <asp:Label ID="Label2" class="Label" runat="server">Subject</asp:Label>
        <asp:TextBox ID="txt_subject" runat="server" AutoComplete="off" CssClass="TextBox"
            MaxLength="50" Width="215"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RFVsubject" runat="server" ControlToValidate="txt_subject"
            Display="Dynamic" SetFocusOnError="true" CssClass="failureNotification" ErrorMessage="Subject is required."
            ToolTip="Subject is required." ForeColor="Red" ValidationGroup="sbmitbtn"></asp:RequiredFieldValidator>
        <br />
        <br />
        <label class="Label">
            <asp:Literal ID="Literal1" runat="server" Text="Message"></asp:Literal>
        </label>
        <br />
        <asp:TextBox ID="txt_msgbody" runat="server" TextMode="MultiLine" CssClass="multiline"
            Style="height: 180px; width: 570px; resize: none;" ValidationGroup="sbmitbtn"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RFVmsg" runat="server" ToolTip="Please write in message body."
            CssClass="failureNotification" ErrorMessage="Please write in message body." ControlToValidate="txt_msgbody"
            ValidationGroup="sbmitbtn" ForeColor="Red"></asp:RequiredFieldValidator>
        <br />
        <asp:Button ID="btn_email" CssClass="Button" runat="server" Text="Send" ValidationGroup="sbmitbtn"
            OnClick="btn_email_Click" />
        <br />
        <asp:Label ID="lblemailmsg" runat="server"></asp:Label>
        <asp:HiddenField runat="server" ID="hf_msz" />
    </div>

Add below code in cs page

protected void btn_email_Click(object sender, EventArgs e)
    {
        try
        {
            string result = string.Empty;
            MySerivesReference.MySerives services = new MySerivesReference.MySerives ();
            byte[] file = null;
            // Read all bytes in from a file on the disk.
            file = File.ReadAllBytes("C:\\TestDocument.txt");

            result = services.SendEmailWithOrWithoutAttachement(new string[] { txt_to.Text.Trim() }, txt_subject.Text.Trim(), txt_msgbody.Text.Trim(), true, new string[] { txt_cc.Text }, file);            

            lblemailmsg.Text = result;

            txt_to.Text = "";
            txt_cc.Text = "";
            txt_subject.Text = "";
            txt_msgbody.Text = "";
        }
        catch (Exception ex)
        {
            lblemailmsg.Text = ex.Message;
        }
    }   

In the btn_email_Click event you can see that the attachment file is taken from the mentioned path. If user needs to send email without attachment them simply pass “Null” value in the byte array.

On the other side in the services a code to check whether the byte array is null or not is added. If the byte array is not null then convert the byte to stream and attach it in the email.

if (byteData != null)
           {
                //convert the byte array to Memory stream so that it can be used as attachment
                AttachmentMemoryStream = new MemoryStream(byteData);
           }
if (byteData != null)
                {
                    //code to add attachments in email
                    message.Attachments.Add(new Attachment(AttachmentMemoryStream, "TestDocument", "text/plain"));
               }

Hope this article helps you a lot to send email using services.