Wednesday, 4 December 2013

How to Send Email with WCF Service in Asp.NET

How to Send Email with WCF Service in Asp.NET

Hi Friends,
            In this post I will tell you Step by Step Process how to send email using WCF Service. I will first explain how to create WCF service then I will try to implement email functionality using WCF Service. Here i am using Gmail to send email., that why user must have gmail account for sending email.


Step:1 Create a new ASP.Net Web Application.
Step:2 Now right click on solution and add new Project.






Step:3 Now form installed templates select WCF then Select wcf service application and name it Email. 






Now you should have two projects in your solution.






Step:4 Now from Email project open IService1.cs add the below namespace

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Net.Mail;


Now Delete the below code:-



and this




Now paste the below code:-

[ServiceContract]
    public interface IService1
    {

        [OperationContract]
        string Email(SendEmail objemail);

    }


    // Use a data contract as illustrated in the sample below to add composite types to service operations.
    
    [DataContract]
    public class SendEmail
    {
        string from, to, cc, bcc, subject, body, filename,path;

        //Stream attachment;

        [DataMember]
        public string From
        {
            get { return from; }
            set { from = value; }
        }

        [DataMember]
        public string To
        {
            get { return to; }
            set { to = value; }
        }

        [DataMember]
        public string Cc
        {
            get { return cc; }
            set { cc = value; }
        }

        [DataMember]
        public string Bcc
        {
            get { return bcc; }
            set { bcc = value; }
        }

        [DataMember]
        public string Subject
        {
            get { return subject; }
            set { subject = value; }
        }

        [DataMember]
        public string Body
        {
            get { return body; }
            set { body = value; }
        }
    }

Now your Page should look like this:-





Step:5 Now open Service1.svc.cs and add below namespace

using System.Net.Mail;
using System.Net;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


Now Delete the below code :-




Now paste the below code:- 

public string Email(SendEmail objemail)
        {
            string fromEmail = "Your Gmail Id";
            MailMessage mail = new MailMessage();
            mail.From = new MailAddress(fromEmail, "Your Name");
            mail.Subject = objemail.Subject;
            mail.Body = objemail.Body;

           
            mail.To.Add(objemail.To);
            if (objemail.Cc.ToString() != null && objemail.Cc.ToString() != "")
            {
                mail.CC.Add(objemail.Cc);
            }
            if (objemail.Bcc.ToString() != null && objemail.Bcc.ToString() != "")
            {
                mail.Bcc.Add(objemail.Bcc);
            }

            SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
            smtpClient.UseDefaultCredentials = false;
            smtpClient.EnableSsl = Convert.ToBoolean(true);
            smtpClient.Credentials = new NetworkCredential("Your Gmail Id", "Your Password");
            try
            {
                smtpClient.Send(mail);
                return "Email Send";
            }
            catch
            {
                return "Failed To Send Email";
            }

        }



Note:- Please don't forget to enter your gmail id and password . 

Now Your Page should look like this:-





Step:6 Now Press F6 To build your project.

Then Right Click on Service1.svc and view in browser:-




Now from browser copy the url.




Step:7 Now add service reference in your web application project. In my case my project name is WCFExample. Right Click Reference and Click on Add Service Reference.




Now a popup box will appear. In Address paste the copied url then press Go.
Now in Namespace write EmailService then press OK.


  


Step:8 Now create a new web form using master page and name it Email.aspx

Now Paste below code in main content of Email.aspx page:-

     <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 />
        <asp:Label runat="server" ID="lblBcc">Bcc</asp:Label>
        <asp:TextBox ID="txt_bcc" runat="server" AutoComplete="off" CssClass="TextBox" PlaceHolder="eg: sam_01@gmail.com"
            Width="215"></asp:TextBox>
        <asp:RegularExpressionValidator ID="REVBcc" 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_bcc"></asp:RegularExpressionValidator>
        <br />
        <br />
        <asp:Label ID="Label2" class="Label" runat="server">Subject</asp:Label>
        <br />
        <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>

Now your page should be like:-


Step:9 Now open Email.aspx.cs and add below namespace

using System.IO;
using System.Net.Mail;
using System.Net;
using WCFExample.EmailService; // In my case reference is added in my web appplication project WCFExample

Now Paste the below code above Page_Load:-

EmailService.Service1Client objemail = new EmailService.Service1Client();

Now add below code below Page_Load:-

protected void btn_email_Click(object sender, EventArgs e)
        {
            SendEmail seobj = new SendEmail();

            seobj.To = txt_to.Text.Trim();
            seobj.Cc = txt_cc.Text.Trim();
            seobj.Bcc = txt_bcc.Text.Trim();
            seobj.Subject = txt_subject.Text.Trim();
            seobj.Body = txt_msgbody.Text.Trim();
            
            string result = objemail.Email(seobj);
            lblemailmsg.Text = result;



        }

Now press F6 to build project. Then Press F5 to run the project.

Finally Your page will be like this:-



Enter email-id,subject,message and Press Send Button to send email.
When Email is send you will get message "Email Send" below Send Button.


Please leave your feedback and comments below..!









No comments:

Post a Comment