In this article I would like to demonstrate how to send emails from the .Net Framework via WCF.
It is a common task in real time projects where we need to send emails from our applications. In .Net it is very easy to implement. I have developed a small piece of code that sends email via Gmail account.
For a real experience I have uploaded the source code.
Step 1: IEmailService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace EmailService
{
[ServiceContract]
public interface IEmailService
{
[OperationContract]
bool SendEmail(string emailTo, string subject, string body, bool isBodyHtml);
}
}
EmailService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Net.Mail;
using System.Net;
namespace EmailService
{
public class EmailService : IEmailService
{
public bool SendEmail(string emailTo, string subject, string body, bool isBodyHtml)
{
if (string.IsNullOrEmpty(emailTo))
{
return false;
}
using (SmtpClient smtpClient = new SmtpClient())
{
using (MailMessage message = new MailMessage())
{
message.Subject = subject == null ? "" : subject;
message.Body = body == null ? "" : body;
message.IsBodyHtml = isBodyHtml;
message.To.Add(new MailAddress(emailTo));
try
{
smtpClient.Send(message);
return true;
}
catch (Exception exception)
{
//Log the exception to DB
throw new FaultException (exception.Message);
}
}
}
}
}
}
EmailService exposes a method named SendEmail that accepts 4 input parameters.
- emailTo (destination email)
- subject (Email Subject)
- body (Email Body)
- isBodyHtml (if it is true then we can pass HTML data in the body {eg: Hi John ,<br/> How are you})
Step 2
So we have created the WCF service library. Let's create a Host. Here I have created a console application to host the service. Add the Service reference to the console application.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using EmailService;
namespace ConsoleEmailHost
{
class Program
{
static void Main(string[] args)
{
using(ServiceHost host=new ServiceHost(typeof(EmailService.EmailService)))
{
Console.WriteLine("Host Started....");
host.Open();
Console.ReadLine();
}
}
}
}
Configure the Application Configuration file.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<services>
<service name="EmailService.EmailService" behaviorConfiguration="mexBehaviour">
<endpoint address="EmailService" binding="wsHttpBinding" contract="EmailService.IEmailService">
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8080/" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="mexBehaviour">
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="True" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="">
<network host="smtp.gmail.com" userName="" password="" port="587" enableSsl="true"/>
</smtp>
</mailSettings>
</system.net>
</configuration>
The highlighted portion is the heart of this application where we configure the Email.
In this example I have used the host smtp.gmail.com (Gmail Server). You need to set the values for from, username and password (from address, user name and the Gmail password).
Now run this console application to start the host.
Step 3: Now the next step is to create the Client. I have created a Windows Forms application that has a Button named Send.
Add the service reference.
Client Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;
namespace EmailClient
{
public partial class Form1 : Form
{
EmailService.EmailServiceClient emailClient;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
emailClient = new EmailService.EmailServiceClient();
try
{
bool send = emailClient.SendEmail("[email protected]", "WCF Mail Test", "Hi Praveen,<br/>This is a test mail from WCF", true);
if (send)
{
MessageBox.Show("Email Sent Successfully..");
}
else
{
MessageBox.Show("Please try again..");
}
}
catch (FaultException exception)
{
MessageBox.Show(exception.Message);
}
finally
{
emailClient.Close();
}
}
}
}
You need to pass a valid email id in the highlighted string.
That's it. You have sent a mail to your recipient via .Net Code.