Click here to Skip to main content
15,861,125 members
Articles / Programming Languages / C#
Tip/Trick

Send Email using WCF Service

Rate me:
Please Sign up or sign in to vote.
4.61/5 (11 votes)
27 Oct 2014CPOL2 min read 56.6K   1.5K   31   11
How to send email using a WCF Service.

Introduction

In this article I will tell you how to send email using a WCF Service. We can send email directly from the client; however, in some cases you can't send external emails directly. In that case we need a WCF service for sending an email from the client. In this article, I will first explain how to create a WCF service then try to implement email functionality using the WCF Service. In this article I am using GMail to send email. So the user must have a GMail account for sending emails.  

Background

I have already written so many articles on WCF:  

Using the code

1. Create WCF Service Class Library

Create a new Project WCF Class Library Project and Name it EmailServices

Image 1

Step 1: Create service contract as IEmailService and add OperationContract SendEmail for sending email. This method uses GMail user address, password, and email to, cc, and subject as parameters:

C#
[ServiceContract]
public interface IEmailService  { 
    [OperationContract]
    string SendEmail(string gmailUserAddress, string gmailUserPassword, 
    string[] emailTo,string[] ccTo, string subject, string body, bool isBodyHtml);           
}

Step 2: Add the EmailService class and implement IEmailService.

C#
public class EmailService : IEmailService
{
    private static string SMTPSERVER = "smtp.gmail.com";
    private static int PORTNO = 587;

    public string SendEmail(string gmailUserName, string gmailUserPassword,  
       string[] emailToAddress, string[] ccemailTo, string subject, string body, bool isBodyHtml)
    {            
        if (gmailUserName == null || gmailUserName.Trim().Length == 0)
        {
            return "User Name Empty";
        }
        if (gmailUserPassword == null || gmailUserPassword.Trim().Length == 0)
        {
            return "Email Password Empty";
        }
        if (emailToAddress == null || emailToAddress.Length == 0)
        {
            return "Email To Address Empty";
        }

        List<string> tempFiles = new List<string>();

        SmtpClient smtpClient = new SmtpClient(SMTPSERVER, PORTNO);
        smtpClient.EnableSsl = true;
        smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtpClient.UseDefaultCredentials = false;
        smtpClient.Credentials = new NetworkCredential(gmailUserName, gmailUserPassword);
        using (MailMessage message = new MailMessage())
        {
            message.From = new MailAddress(gmailUserName);
            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)
                {                       
                    message.CC.Add(emailCc);
                }
            }
            try
            {
                smtpClient.Send(message);                 
                return "Email Send SuccessFully";
            }
            catch
            {                  
                return "Email Send failed";
            }
        }
    }
}

Step 3: Build your Class Library.

2. Add WCF Service Application Project

Image 2

Step 1: Add reference of Class Library Project to that WCFServiceHost project.

Step 2: Delete IService1.Cs and the code-behind file.

Step 3: Right click on that SaleService.svc and select view Markup:

Image 3

Step 4: Change the Service Name from that markup:

ASP.NET
<%@ ServiceHost Language="C#" Debug="true" 
  Service="EmailServices.EmailService" CodeBehind="EmailService.svc.cs" %>

Step 5: And build the solution and WCFServiceHost set as startup project and EmailService.svc set as startup page and run the service.

Image 4

3. Testing Email Service

  1. Use WCFSTORM for testing WCF Service . You can download WCFSTORM from http://www.wcfstorm.com/wcf/home.aspx.
  2. Open WCFStrom and add the following endpoint http://localhost:53818/EmailService.svc?wsdl.

Image 5

By using this, you have successfully send email using WCF Service.

Image 6

Please see the attached source code.

Happy programming!!

If you have any queries, Reply Me

License

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


Written By
Technical Lead
India India
Sujit Bhujbal is Senior Software Engineer having over 12 + years of Experience in .NET core , C#, Angular , SQL Server and has worked on various platforms. He worked during various phases of SDLC such as Requirements and Analysis, Design and Construction, development, maintenance, Testing, UAT.

He is Microsoft Certified Technology Specialist (MCTS) in Asp.net /WCF Applications. He worked at various levels and currently working as a Senior Software Engineer.

His core areas of skill are Web application development using WPF,WCF , C#.Net, ASP.Net 3.5, WCF, SQL Server 2008, CSS, Java script Web design using HTML, AJAX and Crystal Reports

He is proficient in developing applications using SilverLight irrespective of the language, with sound knowledge of Microsoft Expression Blend and exposure to other Microsoft Expression studio tools.


Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4

------------------------------------------------------------------------
Blog: Visit Sujit Bhujbal

CodeProject:- Sujit Bhujbal codeproject

DotNetHeaven:- DotNetHeaven

CsharpCorner:-CsharpCorner

Linkedin :-Linkedin

Stack-Exchange: <a href="http://stackexchange.com/users/469811/sujit-bhu

Comments and Discussions

 
GeneralMy vote of 1 Pin
Faisalabadians28-Oct-14 3:04
Faisalabadians28-Oct-14 3:04 
GeneralRe: My vote of 1 Pin
Vijay Gill28-Oct-14 7:47
professionalVijay Gill28-Oct-14 7:47 
NewsUnable to download source code Pin
Abhishek Pant30-Sep-14 22:40
professionalAbhishek Pant30-Sep-14 22:40 
GeneralRe: Unable to download source code Pin
Sujeet Bhujbal27-Oct-14 20:19
Sujeet Bhujbal27-Oct-14 20:19 
Questiondownload unavailable Pin
Member 1110376623-Sep-14 4:29
Member 1110376623-Sep-14 4:29 
AnswerRe: download unavailable Pin
Sujeet Bhujbal27-Oct-14 20:10
Sujeet Bhujbal27-Oct-14 20:10 
QuestionUnable to Download File attached Pin
heemanshubhalla15-Feb-14 2:38
heemanshubhalla15-Feb-14 2:38 
AnswerRe: Unable to Download File attached Pin
Sujeet Bhujbal27-Oct-14 20:10
Sujeet Bhujbal27-Oct-14 20:10 
QuestionPlease give suitable instructions Pin
heemanshubhalla15-Feb-14 2:33
heemanshubhalla15-Feb-14 2:33 
Questionwhere is SaleService.svc Pin
heemanshubhalla15-Feb-14 2:24
heemanshubhalla15-Feb-14 2:24 
AnswerRe: where is SaleService.svc Pin
Shashank Vaidya20-Apr-14 15:26
Shashank Vaidya20-Apr-14 15:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.