Welcome again to Dotnetfunda. In this article I am going to demostrate on how to send an email in Silverlight. I have previously wrote an article on how you can do that in asp.net, but now in Silverlight the approach is different and a newbie or even an experienced person can get lost. I am known by writing easly interpreted articles and I will keep on doing that , by even providing you with screenshots. Thanks again to Sheo who take my article as word document and post them on my behalf. I am a programmer who does not like to spent to much time on a word processing program like ms word.
How to send an email in Silverlight
Introduction
Welcome again to Dotnetfunda. In this article I am going to demostrate on how to send an email in Silverlight. I have previously wrote an article on how you can do that in asp.net, but now in Silverlight the approach is different and a newbie or even an experienced person can get lost. I am known by writing easly interpreted articles and I will keep on doing that , by even providing you with screenshots. Thanks again to Sheo who take my article as word document and post them on my behalf. I am a programmer who does not like to spent to much time on a word processing program like ms word.
Background
In this Article we are going explain how you can send an email from your silverlight appplication , with gmail or other email accounts that you know the smtp and port.
Using the code
We are going to user C# as our language and we will have some xaml to build our UI.
What do I need to Follow this article Examples
You need Visual Studio 2010 or Visual Studio 2008 SP1 and if 2008 version make sure that you have installed the Silverlight Tools. We are going to use WCF to send an email and you need a Gmail account or any account that you know the smtp name and port name. Below is a list of checklist to make sure that you have everything before you start following the examples.
Start
Now if all in the table is installed in your computer , you can now follow my examples.
Open Visual Studio and Create a New project as depicted below

Select new project and a dialogbox will appear, give te name of your application a meaningfull name and choose , “Silverlight Application” and click ok

Another dialog box will appear ,as depicted below

This basically means that , Visual studio is going to add a web application that you can use for testing and probably deploy it. As you know the Silverlight application you are designing will be embeded in a browser. So you will use the oject tag to embed , but if you select this option , Visual studio will do it for you , what you need to do is to deploy the .xap file with the page. Click ok to continue. After that you will see that your Solution Explorer have some Files and a web application has been added and there are two files that are more important , the first one is .aspx file and the other is a .html file. So it depends on you on what you want to use. As depicted below

Your “MainPage.xaml” is when we will design our UI(User Interface) and what ever we do in the project “ContactUs” it will reflect the .xap file in the “Clientbin” in your web application. That means if you make a change and compile your application , you don’t need to change anything to your web application. When you deploy your application you will only need the Folder ClientBin , that Silverlight.js and one of the pages and that is all. Now let us get out hands dirty. Let us design an email page. I will show you my xaml and the look and you can copy my xaml and paste it on your side. Your xaml should look like this
<UserControl x:Class="ContactUs.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="600" d:DesignWidth="800">
<Grid x:Name="LayoutRoot" Margin="10">
<StackPanel x:Name="StaffPanel3" Width="293" Canvas.Left="529" Canvas.Top="99" Margin="134,0,135,0">
<TextBlock x:Name="name" HorizontalAlignment="Left" Text="Name:" TextWrapping="Wrap" Foreground="Black" Margin="0"/>
<TextBox TextWrapping="Wrap" />
<TextBlock x:Name="txtemail" HorizontalAlignment="Left" Text="Email:" TextWrapping="Wrap" Foreground="Black" Margin="0"/>
<TextBox TextWrapping="Wrap"/>
<TextBlock x:Name="txtComment" HorizontalAlignment="Left" Text="Comments:" TextWrapping="Wrap" Foreground="Black" Margin="0"/>
<TextBox TextWrapping="Wrap" Height="95"/>
<Button Height="33" x:Name="btnSumit" Foreground="Black" Content="Submit" Margin="0,3,213,0" HorizontalAlignment="Right" Width="80" Click="btnSumit_Click" ToolTipService.ToolTip="Send us your Message"/>
</StackPanel>
<Button x:Name="btnCancel" Content="Close" Click="btnCancel_Click" Height="31" Margin="221,0,264,20" Grid.Column="0" VerticalAlignment="Bottom" d:LayoutOverrides="GridBox" ToolTipService.ToolTip="Close" />
</Grid>
</UserControl>
And your Design will look like this

Now we have the Designs ready. Let us create a WCF Service. I will not go deeper in WCF because it is out of the scope of this article. There are two option , its either you create a WCF service from the Current Application or you create the service in a different namespace. Let us create a service in a same name space.
Create a WCF Service
Right click on your Solution Explorer and click on new Project as depicted below

A dialog box will appear and as depicted below and choose a WCF Service Application

give your service a name and click ok , in your solution explorer you will have a service added as depicted below

Now delete the Iservice1 and Service1.svc as I do below

That means you will only be left with a web config and other files except the one you just deleted. Now right click the root of your service and add new item and you will see the Following diolog box,

Give your service a name and click the add button and you will have two files in your solution explorer as depicted below

Right click on your service again and add new Item and this time select an Interface as depicted below

Give your interface a name , as you can see I have prefixed my interface with an “I” for interface for good naming convensions. Click add and you will have an interface in your solution explorer.
Do the same the step again but now add a class.
Now all the Files needed to write a service are there. So to make sure that you are in the same page with me, please compare your solution explorer with what I have below

There is one more thing to do here. As you can see my svc file has a collapse sign that means we have a code behind for. Actually we don’t need it collapse it and delete it as depicted below

And you will notice there is another Interface there please Delete it as I do above and add an xml file as depicted below and give it the same name as the one I give here , I will explain later why do you need that file

The name of the xml file is clientaccesspolicy.xml.
when done your Solution Explorer should look like this

Let us start add an email functionality for our service. Before let us start with the xml file we just added. Add the Following code into the Client Acccess policy File
<?xml version="1.0" encoding="utf-8"?>
<access-policy>
<cross-domain-access>
<!-- Silverlight 3 or higher requires the http-request-headers attribute. -->
<policy>
<allow-from http-request-headers="*">
<domain uri="http://*" />
<domain uri="https://*" />
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
Open the Email service Class file and add the Following code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;
using System.Configuration;
using System.IO;
using System.Text;
namespace MailServices
{
public class email : Iemail
{
public int SendEmail(String ClientName, String ClientEmail, String ClientPhone, String WebmasterEmail, int BestWayToContactus, String Comment, String Subject)
{
int Sent = 0;
String FromE = ConfigurationManager.AppSettings.Get("FromE");
String To_1 = ClientEmail;
String Gmail_Password = ConfigurationManager.AppSettings.Get("Gmail_Password");
String Networked_Username = ConfigurationManager.AppSettings.Get("Networked_Username");
int Gmailport = Convert.ToInt32(ConfigurationManager.AppSettings.Get("Gmailport"));
String Server_Host = Convert.ToString(ConfigurationManager.AppSettings.Get("GmailHost"));
try
{
MailMessage mm = new MailMessage();
SmtpClient smtp = new SmtpClient();
mm.From = new MailAddress(FromE);
//add the Emails to a To Collection
mm.To.Add(new MailAddress(WebmasterEmail));
mm.Subject = "WebSite Form";
mm.Body = BuildBody(ClientName, ClientEmail, BestWayToContactus, ClientPhone, Comment);
mm.IsBodyHtml = true;
smtp.Host = Server_Host;
smtp.EnableSsl = true;
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = Networked_Username;
NetworkCred.Password = Gmail_Password;
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = Gmailport;
smtp.Send(mm);
Sent = 1; //Email sent
}
catch (System.Net.Mail.SmtpException)
{
throw;
}
return Sent;
}
private String BuildBody(String ClientName, String StartDate, String EndDate)
{
StringBuilder Str = new StringBuilder();
Str.Append("Dear RBC Projects" + "<br><br>");
Str.Append(ClientName + " Applied for leave from" + "<br><br>");
Str.Append(StartDate + " " + "To the " + EndDate + "<br><br>");
Str.Append("Kind Regards" + "<br><br><br>");
Str.Append("Human Resource System(VLS)" + "<br>");
return Str.ToString();
}
private String BuildBody(String ClientName, String ClientEmail, int BestWayToContactus, String ClientPhone)
{
StringBuilder Str = new StringBuilder();
Str.Append("Dear Madam/Sir" + "<br><br>";
Str.Append("A Client Sent you a message via the Website" + "<br><br>");
Str.Append("Name: " + ClientName + "<br><br>");
Str.Append("Email:" + ClientEmail + "<br><br>");
Str.Append("TEl:" + ClientPhone + "<br><br>");
if (BestWayToContactus == 1)
{
Str.Append("Best way to to Contact the Client:" + "Phone" + "<br><br>");
}
else
{
Str.Append("Best way to to Contact the Client: " + "Email" + "<br><br>");
}
Str.Append("Kind Regards" + "<br><br><br>");
Str.Append("WebMaster" + "<br>");
return Str.ToString();
}
private String BuildBody(String ClientName, String ClientEmail, int BestWayToContactus, String ClientPhone, String Comment)
{
StringBuilder Str = new StringBuilder();
Str.Append("Dear Madam/Sir" + "<br><br>");
Str.Append(ClientName + " Below are the details" + "<br><br>");
Str.Append("Email:" + ClientEmail + "<br><br>");
Str.Append("TEl:" + ClientPhone + "<br><br>");
if (BestWayToContactus == 1)
{
Str.Append("Best way to to Contact the Client:" + "Phone" + "<br><br>");
}
else
{
Str.Append("Best way to to Contact the Client: " + "Email" + "<br><br>");
}
Str.Append("Comment:" + Comment + "<br><br>");
Str.Append("Kind Regards" + "<br><br><br>");
Str.Append("WebMaster" + "<br>");
return Str.ToString();
}
}
}
Save it and open emailService.svc file and add the following markup
<%@ServiceHost Service="MailServices.email" %>
<%@Assembly Name="Mailer" %>
“MailServices” is the namespace and the “email” is the class that we created that inherits the interface. The second line is the assembly name, it is the name of service.
The next file is the Interface , add this simple code
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;
using System.ServiceModel;
using System.Configuration;
namespace MailServices
{
[ServiceContract]
public interface Iemail
{
[OperationContract]
int SendEmail(String ClientName, String ClientEmail, String ClientPhone, String WebmasterEmail, int BestWayToContactus, String Comment, String Subject);
}
}
And the last part is the web config. The web Config is just simple , you can replace what you have there with the following web config markup
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere" />
<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
<section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
</sectionGroup>
</sectionGroup>
</sectionGroup>
</configSections>
<appSettings>
<add key="EmailTO1" value="myemail@dotnetfunda.com" />
<add key="Gmail_Password" value="oopsmypassowrd" />
<add key="Networked_Username" value="myemail@gmail.com" />
<add key="Gmailport" value="587" />
<add key="FromE" value=" myemail@gmail.com " />
<add key="GmailHost" value="smtp.gmail.com" />
<add key="aspnet:IgnoreFormActionAttribute" value="true" />
</appSettings>
<connectionStrings/>
<system.web>
<compilation debug="true">
<assemblies>
<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
<pages>
<controls>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</controls>
</pages>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpModules>
</system.web>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" warningLevel="4"
type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<providerOption name="CompilerVersion" value="v3.5"/>
<providerOption name="WarnAsError" value="false"/>
</compiler>
</compilers>
</system.codedom>
<!--
The system.webServer section is required for running ASP.NET AJAX under Internet
Information Services 7.0. It is not necessary for previous version of IIS.
-->
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<remove name="ScriptModule" />
<add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</modules>
<handlers>
<remove name="WebServiceHandlerFactory-Integrated"/>
<remove name="ScriptHandlerFactory" />
<remove name="ScriptHandlerFactoryAppServices" />
<remove name="ScriptResource" />
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode"
type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode"
type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</handlers>
</system.webServer>
<runtime>
<assemblyBinding appliesTo="v2.0.05727" xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.serviceModel>
<services>
<service name="MailServices.email"
behaviorConfiguration="emailServiceMetaData">
<endpoint address=""
binding="basicHttpBinding"
contract="MailServices.Iemail" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="emailServiceMetaData">
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
As you can see in my class there are functions there, I just copied some email functionality that I used to have it had function overloadinfg with some html building that raterly happened. Now when you have all this build your service and right click on your “svc” file and select “View in Browser” and you should see the following

Now to make sure that our service is working , in your solution explorer right click the service and set it as a startup project and press f5 to run the service and a dialog box will appear

Please note that in VS 2010 it appears automatically , but in Visual studio 2008 is different. After the loading is done it will look as depicted below

As you can see there is your send email function , now to invoke it double click on the function and you will have something like this

As you can see I haved filled the parameters in the Value section and if I click invoke , I get the following message

Just click and when the email is sent you will see a message on the taks bar of the dialog box saying “Service Incocation completed” and that means the email will be sent succsessfully.

Now to make sure that the email is sent we need to check the email in our e-mail. Without going to my email gtalk gave me an alert that I have an email


Now that our service can send an email , in the next part II of this article I will show you how you send an email in your silverlight application you created earlier.
Conclusion
In the Next Article we will call this service and consume the service in Silverlight. I made the article 2 because of the size and the images and again the concept. First we needed to create a WCF Service which is normally an article of its own, but I tried to combine all those in one place.
Thank you for visiting DotnetFunda.
Vuyiswa Maseko