Tuesday, January 18, 2011

How to send Email From your silverlight application.

While browsing through the pages you must have seen the share buttons at the bottom of the page. today we’ll see how do we achieve this from our Silverlight application.

Idea behind this topic is very simple. we need to make use of smpt class to send the mails from either your Hotmail, Gmail, yahoo mail ids or any other mail servers if you know the host address of the mail server.

You Need to have following things to get going.

1. Visual Studio 2010.

2. Expression Blend 4.

3. Silverlight 4 tools.

If you have all this so lets get started.

Step1 :

We need to create new project in visual studio. Name it “EmailApp”.

ProjectNaming

Step 2:

You’ll have two project under your under the solution. First the Silverlight project and other will be the hosting web project.

ProjectEmptyStart

Step 3:

Once you have done up to this point. next we need to add a web service in EmailApp.Web project and name it “EmailService.asmx”, This will act as wrapper class between our Silverlight application and the mailing server.

AddingWebService

Step 4:

Now when you have added this asmx file you need to add the following line of code, which are actually the main code of our application. Remove HelloWorld Method and Add Send Function as follows.

We are using System.Net.Mail.MailMessage object, and SMTP client object to send the mails from the desired mail server. what we need to know is the smtp.Host and the port number of the mail server from which the email will be sent. Send Function takes 6 argument

emailFrom: Email Address from which the email is sent.

emailTo: Email Address to which the email is to be sent.

emailSubject : Subject of the email.

emailBody : Body of the email.

userId : Email Address from which the email is sent.

password: password of the account.

Do not forget to include following namespaces.

using System.Web;
using System.Web.Services;
using System.Web.Mail;
using System.Net.Mail;
using System.Net;

[WebMethod]
public bool Send(string emailFrom, string emailTo, string emailSubject, string emailBody, string userId, string password)
{
try
{
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add(new MailAddress(emailTo));
message.From = new MailAddress(emailFrom);
message.CC.Add(new MailAddress(emailTo));
message.IsBodyHtml = true;
message.Subject = emailSubject;
message.Body = emailBody;
SmtpClient smtp = new SmtpClient();
smtp.EnableSsl = true;
if ((userId != null && password != null) && (userId != string.Empty && password != string.Empty))
{
smtp.Credentials = new NetworkCredential(userId, password);
}
else
{
throw new Exception("Can Not Authenticate user...!!!");
}
if (emailFrom.Contains("yahoo"))
{
smtp.Host = "smtp.mail.yahoo.com";
}
else if (emailFrom.Contains("gmail"))
{
smtp.Host = "smtp.gmail.com";
}
else if (emailFrom.Contains("hotmail"))
{
smtp.Host = "smtp.live.com";
}
else
{
smtp.Host = "smtp.mail.yahoo.com";
}
smtp.Port = 587;
smtp.Send(message);
return true;
}
catch
{
return false;
}
}

Step 5:

Once you have added a service now its time to consume this web service. Right Click on the References in Silverlight project and add service reference. A window will come where you will see a discover button. Click it discover our web service. Once it discovers our service click ok button. It Might through an error that the service reference could not be added, This is because the service could not be found as it is not running. If it appears then right click the EmailService.asmx file in the web project and run it in a browser. Now it should work.

Referencing the service reference

Once you successfully reference the service you will see ServiceRefence1 and ServiceReferences.ClientConfig files added into the Silverlight project.

ServiceReferenced Successfully

Step 6:

Now some styling and controls needs to be added into our MainPage.xaml file. I will give us a nice looking UI

<Grid>
<StackPanel x:Name="AuthenticationStack" HorizontalAlignment="Center" VerticalAlignment="Center" Background="#FFE8EEFA" d:IsHidden="True">
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" d:LayoutOverrides="Width">
<TextBlock TextWrapping="Wrap" Text="Username:" VerticalAlignment="Center" Margin="10"/>
<TextBox x:Name="txtbxUserName" Width="200" VerticalAlignment="Center" Margin="10" />
</StackPanel>
<StackPanel Orientation="Horizontal" d:LayoutOverrides="Width" VerticalAlignment="Center">
<TextBlock TextWrapping="Wrap" Text="Password:" VerticalAlignment="Center" Margin="10"/>
<PasswordBox x:Name="pwdBx" VerticalAlignment="Center" Width="200" Margin="10" />
</StackPanel>
<Button Content="Sign In" Click="btn_Click" x:Name="btnSignIn" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="10" />
</StackPanel>
<StackPanel x:Name="mailStack" Background="#FFE8EEFA" HorizontalAlignment="Center" Width="300" VerticalAlignment="Center" Visibility="Collapsed">
<StackPanel x:Name="fromStack" Orientation="Horizontal" VerticalAlignment="Center" d:LayoutOverrides="Width">
<TextBlock TextWrapping="Wrap" Text="Mail From:" VerticalAlignment="Center" Margin="10"/>
<TextBox x:Name="txtbxFrom" Width="200" VerticalAlignment="Center" Margin="10" />
</StackPanel>
<StackPanel x:Name="toStack" Orientation="Horizontal" d:LayoutOverrides="Width" VerticalAlignment="Center">
<TextBlock TextWrapping="Wrap" Text="Mail To:" VerticalAlignment="Center" Margin="10"/>
<TextBox x:Name="txtbxTo" Width="200" VerticalAlignment="Center" Margin="10" />
</StackPanel>
<StackPanel x:Name="subjectStack" Orientation="Horizontal" VerticalAlignment="Center">
<TextBlock TextWrapping="Wrap" Text="Subject:" VerticalAlignment="Center" Margin="10"/>
<TextBox x:Name="txtbxSub" Width="200" VerticalAlignment="Center" Margin="10" />
</StackPanel>
<StackPanel x:Name="bodyStack" VerticalAlignment="Center">
<TextBlock TextWrapping="Wrap" Text="Subject:" VerticalAlignment="Center" Margin="10"/>
<TextBox x:Name="txtbxBody" Width="280" VerticalAlignment="Center" Margin="10" HorizontalAlignment="Left" Height="120" />
</StackPanel>
<Button Content="Send" Click="btn_Click" x:Name="btnSend" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="10" />
</StackPanel>
<StackPanel x:Name="endStack" Visibility="Collapsed" HorizontalAlignment="Center" VerticalAlignment="Center" Background="#FFE8EEFA">
<StackPanel Orientation="Horizontal">
<TextBlock TextWrapping="Wrap" Text="Thanks for using this mailing service" VerticalAlignment="Center" Margin="10"/>
</StackPanel>
<Button Content="Close" Click="btn_Click" x:Name="btnCloseBrowser" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="10" />
</StackPanel>
</Grid>

UI :

UI

UI2

Step 7:

Last but not the least we need to add some code in code behind of the click event of the Sign In button.

private void btn_Click(object sender, RoutedEventArgs e)
{
if (sender == btnSignIn)
{
busyIndicator.DisplayAfter = TimeSpan.FromMilliseconds(2.0);
busyIndicator.IsBusy = true;
busyIndicator.Opacity = 0.9;

ThreadPool.QueueUserWorkItem((state) =>
{
Thread.Sleep(1 * 500);
Dispatcher.BeginInvoke(() => busyIndicator.IsBusy = false);
});
AuthenticationStack.Visibility = Visibility.Collapsed;
mailStack.Visibility = Visibility.Visible;
txtbxFrom.Text = txtbxUserName.Text;
}
else if (sender == btnSend)
{
BasicHttpBinding bind = new BasicHttpBinding();
EndpointAddress endPoint = new EndpointAddress("http://localhost:39206/MailService.asmx%22);
SendEmailServiceReference.MailServiceSoapClient mailService = new SendEmailServiceReference.MailServiceSoapClient(bind, endPoint);
mailService.SendAsync(txtbxFrom.Text.ToString().Trim(), txtbxTo.Text.ToString().Trim(), txtbxSub.Text.ToString().Trim(), txtbxBody.Text.ToString().Trim(), txtbxUserName.Text, pwdBx.Password);
mailService.SendCompleted += new EventHandler<SendEmailServiceReference.SendCompletedEventArgs>(mailService_SendCompleted);
}
else if (sender == btnCloseBrowser)
{
HtmlPage.Window.Invoke("close");
}
}

As you can see from the above code we can access the send function with 6 argument in our web service. Send function will be accessed asynchronously as all the methods and calls from Silverlight will made asynchronously. Following code we need to write in the Mail web service Send Completed event handler.

void mailService_SendCompleted(object sender, SendEmailServiceReference.SendCompletedEventArgs e)
{
if (e.Result)
{
if (MessageBox.Show("Message Sent Successfully") == MessageBoxResult.OK)
{
mailStack.Visibility = Visibility.Collapsed;
AuthenticationStack.Visibility = Visibility.Collapsed;
endStack.Visibility = Visibility.Visible;
}
}
else
{
MessageBox.Show("Message Not Sent...!!!");
}
}

So that's it.. we are now ready to send emails from our Silverlight application. BUT make sure while running the application you must also browse the EmailService.asmx in to the web browser.

Enjoy Coding and Happy Programming…………….!!!Hot smile

Thursday, June 17, 2010

Silverlight Editor


It is a small user control build in silverlight 4. In this i have used a rich text box control, and its properties like text decoration for "underlining" the selected text, Text weight property for making the selected text "Bold". To make the selected text "italic" i have used text style property.
The font family property is used to apply different silverlight supported fonts to the selected text. And the Font size property helped me to increase or decrease the size of the selected text.
All the operations are applyied on selected text which we can retrieve using Selection.GetPropertyValue() method. and the Dependency properties are applied using the
Selection.ApplyPropertyValue() method..
Hope you got the clear cut idea about this tool..
Please keep visiting this place for more such creations..
Happy Programming....!!!!!!!!!!