Sharing our knowledge

Michael Sync

Tip/Trick- Sending Email in Silverlight 2 beta1

May 25th, 2008 by Michael Sync

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

24 Responses

  1. Albert Says:

    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. Albert Says:

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

  3. Michael Sync Says:

    Act, it’s in App_Code.

  4. Ben Hayat Says:

    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. Kenneth Auchenberg Says:

    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. Fallon Massey Says:

    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. Michael Sync Says:

    >>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. Ben Hayat Says:

    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. Wöchentliche Rundablage: ASP.NET MVC, Silverlight 2, C#, Entity Framework, WPF, Javascript | Code-Inside Blog Says:

    [...] Tip/Trick- Sending Email in Silverlight 2 beta1 [...]

  10. Michael Sync Says:

    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. Ben Hayat Says:

    >>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. Post: 131 - Mirrored Blogs Says:

    [...] Email in Silvelight 2Michael Sync has a tutorial showing how to send email with SL:http://michaelsync.net/2008/05/25/tiptrick-sending-email-in-silverlight-2-beta1Expression Blend for DevelopersHere an article not to [...]

  13. Ben Hayat Says:

    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. Michael Sync Says:

    >>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. Ben Hayat Says:

    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. Michael Sync Says:

    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. Ben Hayat Says:

    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. Niyla Says:

    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. Francisco Says:

    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. Justin Says:

    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. Michael Sync Says:

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

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

    [...] some of them several times, before I finally got a sample to work. I used the tutorial from Michael Sync to get it going, and it took me a while to realize that there was an error in the [...]

  23. Jose Says:

    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. rtwPhoenix Says:

    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???????????????

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.