Tip/Trick- Sending Email in Silverlight 2 beta1 36

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.

Screenshot

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


[WebMethod]
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;
smtp.Send(msg);
return true;
}
catch (Exception ex) {
///Log.Write(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.


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

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,
endpoint);

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;
}
}

36 thoughts on “Tip/Trick- Sending Email in Silverlight 2 beta1

  1. Reply Albert May 25,2008 8:39 am

    Very util this example, but I can’t find the MailService.asmx.cs file on the example code for download, and get an error when I try add a Service reference to my own project. I think the answer is on this file that remains on the example code.

  2. Reply Albert May 25,2008 8:44 am

    Never mind my comment… I never have worked with Web Services. Now I can see the file on App_code directory

  3. Reply Michael Sync May 25,2008 8:45 am

    Act, it’s in App_Code.

  4. Reply Ben Hayat May 25,2008 11:36 am

    Michael, I just got off the phone with God and He told me to tell you, that anyone who helps others, has a special place in My home…

    ..Ben

  5. Reply Kenneth Auchenberg May 25,2008 1:50 pm

    Hmmm… Creating a webservice without any authentication. Is that a good dear?

    Without authentication I would be possible for everyone to use the webservice to send mails… Spam spam bot?

  6. Reply Fallon Massey May 25,2008 6:12 pm

    Kenneth Auchenberg, he did say he didn’t include a lot of the things required in a real world app, it’s just a demo.

    However, it’s not really about sending email from SL2, it’s more of a webservice demo than anything else. You can’t send emails from SL.

  7. Reply Michael Sync May 25,2008 11:14 pm

    >>Michael, I just got off the phone with God and He told me to tell you, that anyone who helps others, has a special place in My home…

    :)

    >>Hmmm… Creating a webservice without any authentication. Is that a good dear?

    Fallon already answered you. :)

    >>However, it’s not really about sending email from SL2, it’s more of a webservice demo than anything else. You can’t send emails from SL.

    It’s ture that we can’t send mails from Silverlight. We answered like that in SL forum too. then, newbie asked for alternative way so we told them that you can use web serivce for that. but newbie doesn’t know how to do that. So, this is the reason why I create this post. :) it’s nothing so special but I hope it might be helpful for that guy.. that’s all… :)

  8. Reply Ben Hayat May 26,2008 7:28 am

    Michael, I’m sure you always put blogs out mainly for sake of education. What you started, is great and can lead to an important solution. Perhaps you or someone you know, who is good at security, can take this post a notch further and shows how security should be handled on SL or server side for the purpose of sending emails or performing other actions. Should the SL client perform security check and pass the result to middle tier as an Authenticated action? or should the middle tier perform the check or both?

    I think this will make a great blog topic to find out how security should be handled to pass password or Credit Card info from SL Client to Middle tier server!

    Thanks!
    ..Ben

  9. Pingback: Wöchentliche Rundablage: ASP.NET MVC, Silverlight 2, C#, Entity Framework, WPF, Javascript | Code-Inside Blog

  10. Reply Michael Sync May 28,2008 7:36 pm

    Hey Ben,

    Great Idea. I’ve been thinking about that too.. I asked a questions related to SSL and Silverlight in SL forum but MS guys said that All requests/responses to/from a web service deployed to an SSL secured location are encrypted automatically at the transport layer. So, if we are passing the sensitive data (e.g. credit card or password) from Silverlight to webservice, we don’t need to do anything special. Just configu webservice in SSL and call it from webservice.. that’s all. seems like it’s extremely easy :)

    What do you think?

  11. Reply Ben Hayat May 28,2008 8:25 pm

    >>What do you think?<<

    Funny you wrote this post. I was just reading that post you put on the forum and read what Allan said and I came here to tell you this, but you’re one step ahead of me :-)

    Now does that mean for even email we should use SSL? That can get expensive for simple sites?

    Man where is beta 2…???

  12. Pingback: Post: 131 - Mirrored Blogs

  13. Reply Ben Hayat May 31,2008 8:26 pm

    Hey Mike, just curious, why did you choose ASP Web service rather than WCF? Are there things that are better to be done in ASMX v.s. WCF or was that your personal choice?

    I ask this because I’m trying to see if I should only use WCF for SL application services?

    Thanks!

    p.s. Did you hear anything from Imran?

  14. Reply Michael Sync Jun 1,2008 2:30 am

    >>why did you choose ASP Web service rather than WCF?

    Mainly, cuz of two reasons..

    Reason 1) It’s true that WCF has a lot of cool things but I don’t need them. ASMX Web service works well for me.

    The following is a very nice note about WCF from Pete O’Hanlon..

    Basically, WCF is a service layer that allows you to build applications that can communicate using a variety of communication mechanisms. With it, you can communicate using Peer to Peer, Named Pipes, Web Services and so on.

    You can’t compare them because WCF is a framework for building interoperable applications. If you like, you can think of it as a SOA enabler. What does this mean?

    Well, WCF conforms to something known as ABC, where A is the address of the service that you want to communicate with, B stands for the binding and C stands for the contract. This is important because it is possible to change the binding without necessarily changing the code. The contract is much more powerful because it forces the separation of the contract from the implementation. This means that the contract is defined in an interface, and there is a concrete implementation which is bound to by the consumer using the same idea of the contract. The datamodel is abstracted out.

    Reason 2) I’m more familiar with ASMX Web Service than WCF since I’ve been using ASMX for 4 years. I played a lit bit with WCF but I don’t have any WCF experience in real projects..

    >>I ask this because I’m trying to see if I should only use WCF for SL application services?

    For me, I more prefer to use Astoria :) I’m waiting beta2 ..

    >>p.s. Did you hear anything from Imran?

    No. man.. It’s strange that you are missing Cass a lot.. Why not Yasser or Justin or me? hehe :P

  15. Reply Ben Hayat Jun 1,2008 7:28 am

    First thing first; :-)

    [quote]No. man.. It’s strange that you are missing Cass a lot.. Why not Yasser or Justin or me? hehe [/quote]

    I do miss Yasser and Justin (don’t you mean Jason?), but with Yasser, he is working on a large project and he slowly walked away. Jason was very active in SL 1.0 and 1.1, but as soon as 2 showed up, no more. But Imran just vanished from the forum, form other forums, his own blog, no email, nothing. And with Michael, I’m hoping we can get ride of him soon… :-)

    >>For me, I more prefer to use Astoria :) I’m waiting beta2 ..<<
    I’m going to TechEd next week and I hope to to find out.

    And thanks for info on the service

  16. Reply Michael Sync Jun 3,2008 11:07 am

    Hey Ben,

    >>Man where is beta 2…???

    I heard that Silverlight 2 beta 1 will be available this week :)
    http://michaelsync.net/2008/06/03/news-silverlight-2-beta2-will-be-coming-this-week

    Are you at TechEd now? You might already know about that… please share your TechEd exp with me, man :) how is it over there?

  17. Reply Ben Hayat Jun 3,2008 12:16 pm

    Mike, I’m not attending the full TechEd. I’ll be going for the “Partner Expo” where I can spend some time meeting the vendors and their new products for SL. Once I’m back and I see hot, I’ll let you know.

  18. Reply Niyla Jul 9,2008 9:50 am

    Hi,

    The above code was working fine but yesterday I started getting “the remote server returned an unexpected response : (404)not found”.

    Any ideas?

    Niyla.

    Ps. Also, any chance of doing a web service demo with authentication.

  19. Reply Francisco Apr 21,2009 10:27 am

    I used ASMX service to send emails in silverlight, in the dev environment it works good, but when I publish the web site a got an error “error on page”, somebody knows what happens?.

  20. Reply Justin May 1,2009 9:19 am

    Thanks for this demo, only thing is you should abstract out that endpoint address, as you don’t want a local url hard-coded into c#. Deployments wouldn’t be too fun…

  21. Reply Michael Sync May 3,2009 8:31 am

    yes.. Endpoint should come from ClientConfig so if we like to change the endpoint, we can extract, change and zip it again.

  22. Pingback: Silverlight to send email - Never Argue With Stupid People

  23. Reply Jose Jul 31,2009 1:13 pm

    Hi guys,

    I came across this post while searching for help on how to send E-mail from Silverlight. I followed the instructions; however, when I run the application from Expression Blend I get an error “The type or namespace ‘ServiceProxy’ does not exist in the namespace……”

    The problem seems to be on this line.

    void mailSrv_SendMailCompleted(object sender, SL2Mail.ServiceProxy.SendMailCompletedEventArgs e)

    I would really appreciate your help on solving this.

    Thanks in adnvance.

  24. Reply rtwPhoenix Aug 21,2009 4:27 pm

    Great but I can not get this to work with SL3

    When I create a web service it gives me a page where I put code in it. MailService.asmx.cs however it shows in properties as MailService.asmx I typed in all the code went fine.

    Rebuilt the solution.

    Went to SL3 section and tried to add the Service Reference

    Pressed Discover found the asmx.

    Changed name to ServiceProxy

    Then I tryied to add the reference but it could not find it!

    I check the port and it worked with anohter page so I know it is pointing to the correct place.

    However when I typed in the MailServices.asmx I get this error:
    Line 1:

    Found an article about endpoint have no clue here I am very new at asmx and c# CAN YOU HELP PLEASE???????????????

  25. Reply Dave Nov 5,2009 9:06 pm

    I had problems with the SL3 implementation of this also. I took me a while to figure out that you must have the EndpointAddress exactly match what appears when your run the service in the browser.

    Look at the ServiceReferences.ClientConfig after you add the Service Reference on the client. The client code behind endpointaddress must match this.

    In all of the SL2 examples I have seen the web project name has been in the endpointaddress between the host nmae and the service name. I don’t know if this is a mistake in the examples or a change in the way SL3 adds Service References.

    After many frustrating break points I saw the error. Other than that, the SL2 example worked perfectly with SL3.

    Note: just copy the code to SL3. The SL2 project does not convert correclty because of differences in Referenced dll files.

  26. Reply Martin Apr 29,2010 4:08 pm

    Hi, thanks Dave for this solution, works fine for SL3 envir. Good think to know for someone who will make this for first time in SL3 is that the EndpointAddress we receive from Discover function during Add Service Reference operation.

  27. Reply Dan W Jun 12,2010 4:24 am

    hi there,

    can this be used to send the mail from a exchange email account?

  28. Reply Michael Sync Jun 12,2010 10:24 am

    Yes. Dan. You can use it with Exchange Server as well..

  29. Reply Total Jun 14,2010 8:59 am

    Very strange…. recreate projet to SilverLight 4 – and get the “Unhandled Error in Silverlight Application” error… how solve poblem???

  30. Reply Jeff Sep 9,2010 12:31 pm

    This project on Silverlight 4 and netframework 4 doesn’t work various error on build

    :(

    Is there a new version???

  31. Reply surendar Nov 25,2010 3:59 am

    Hey nice article man..

  32. Reply kevin Apr 28,2011 4:52 am

    We don’t want to split the atom michael, some of us haven’t graduated as “geeks” yet, we just want to send some pictures by silverlight.
    Is it really that compicated?

    Kevin

  33. Reply Kamal Jul 30,2011 2:49 am

    Hi,
    I follow up your example in my application. When I try to submit the email, I get the following error message
    “Remote server returned an error: not found”.
    It throws it when it gets to this method:
    public bool EndSendEmail(System.IAsyncResult result) {
    object[] _args = new object[0];
    bool _result = ((bool)(base.EndInvoke(“SendEmail”, _args, result)));
    return _result;
    }
    Do you know what is pretending the email to be sent?
    Thanks,
    Kamal

  34. Reply Michael Sync Sep 15,2011 6:48 pm

    Hi Kamal,

    Please make sure you can access the WCF service. “Not found” means there is some errors in WCF (not in Silverlight)

  35. Reply ino Oct 5,2011 10:21 am

    i tried your solution by referencing this project from an SL4 project.

    I get errors about BasicHttpBinding and EndpointAddress….seems they could not be found.

  36. Reply amit Mar 27,2012 12:54 am

    Hi sir,
    Nice article..

    But i am getting zero error, still after running it is showing sending failed…
    the id password i have shown under web.config is correct..
    what should i do now??

Leave a Reply