In this tip I will be showing you how to send an email via Silverlight. Obviously sending email directly from the Silverlight client is not possible.
However, as with most things, you can leverage a Silverlight-enabled WCF server to do the dirty work for you. In this steps below I will be showing you the code needed to send the email through the SmtpClient object as well as some minor configurations you need to do to your server to get it working.
Step #1. Create a new Silverlight application.
Step #2. In your web site, add a Silverlight-enabled WCF web service (calling it something like MyService.svc)
Step #3. Add the following method to your MyService.svc.cs file:
[OperationContract]
public bool SendMail(string emailTo, string emailFrom, string msgSubject, string msgBody)
{
bool success = false;
try
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress(emailFrom);
msg.To.Add(new MailAddress(emailTo));
msg.Subject = msgSubject;
msg.Body = msgBody;
msg.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "111.111.111.111"; // Replace with your servers IP address
smtp.Port = 25;
smtp.EnableSsl = false;
smtp.Send(msg);
success = true;
}
catch
{
success = false;
}
return success;
}
Step #4: Build the web site
Step #5: In your Silverlight application, right click on Service Reference and choose Add Service Reference…
Step #6: Click the Discover button, choose your service under “Services” and click the OK button.
Step #7. At this point, in your Silverlight code, you can create a ServiceReference client and call the method directly like this:
ServiceReferenceTest.MyServiceClient client = new ServiceReferenceTest.MyServiceClient ();
client.SendMailAsynce(emailTo, emailFrom, msgSubject, msgBody);
Note that if you were to execute this code without first installing the SMTP Sever via IIS you would get a “Send Failed” exception.
Step #8: In your server open up the Server Manager (ServerManager.msc) and choose Add Features.
Step #9: Select SMTP Server and click Next until the install is complete.
At this point if you were to run the code you would get the following exception:
Mailbox unavailable. The server response was: 5.7.1 Unable to relay for…
Step #10: Open up IIS 6 Manager (not IIS Manager)
Step #11: Right click on SMTP Virtual Server and choose Properties.
Step #12: Under the Access tab, choose Authentication and verify Anonymous access is checked.
Step #13: Under the Access tab, click the “Relay” button and add the IP of your server making certain the “Only the list below” button is checked.
At this point you should be good to go!
Thanks,
–Mike