Tip/Trick- Sending Email in Silverlight 2 beta1

Someone was asking how to send Email in Silverlight 2 beta1 in Silverlight forum. So, I created this sample for him. I’m sharing the code with you all. I hope you will find it useful.

Note that I didn’t add any validation or etc in this sample.


Sourecode Download : SL2Mail.zip (597KB)

1. Create new project named SL2Mail in VS 2008

2. Add a new Web to the solution for hosting the control

3. Right-click on ASP.NET project and select new item

4. Select Web service and name it “MailService”

5. Open MailService.cs and write the following code

public bool  SendMail(string fromAddress,string toAddress,string subject, string body) {
try {
MailMessage msg = new MailMessage();
msg.From = new MailAddress(fromAddress);
msg.To.Add(new MailAddress(toAddress));
msg.Subject = subject;
msg.Body = body;
msg.IsBodyHtml = false;

SmtpClient smtp = new SmtpClient();
smtp.EnableSsl = true;
return true;
catch (Exception ex) {
return false;

6. Confgure SMTP server, port, user name and password in web.config

Note: I’m using one of my gmail account in this sample. [Please don't change my password in Gmail.] You will need to change your mail server configuration.

<network host="smtp.gmail.com" port="587" userName="will.mrk1@gmail.com" password="password123"/>

7. Add Service Reference in Silverlight project

8. Name the proxy file as “ServiceProxy”

9. Call the web service from Silverlight as below

void sendButton_Click(object sender, RoutedEventArgs e) {
BasicHttpBinding bind = new BasicHttpBinding();
EndpointAddress endpoint = new EndpointAddress("http://localhost:50976/SL2Mail_Web/MailService.asmx");

ServiceProxy.MailServiceSoapClient mailSrv = new SL2Mail.ServiceProxy.MailServiceSoapClient(bind,

mailSrv.SendMailAsync(fromEmailAddressTextblock.Text, toEmailAddressTextbox.Text, subjectTextbox.Text, bodyTextbox.Text);
mailSrv.SendMailCompleted +=new EventHandler<SL2Mail.ServiceProxy.SendMailCompletedEventArgs>(mailSrv_SendMailCompleted);


void mailSrv_SendMailCompleted(object sender, SL2Mail.ServiceProxy.SendMailCompletedEventArgs e) {
if (e.Result) {
resultTextBlock.Foreground = new SolidColorBrush(Colors.Blue );
resultTextBlock.Text = "Your email has been sent successfully!";
resultTextBlock.Visibility = Visibility.Visible;
else {
resultTextBlock.Text = "Sending failed. Please try again.";
resultTextBlock.Foreground = new SolidColorBrush(Colors.Red);
resultTextBlock.Visibility = Visibility.Visible;