使用SmtpClient需要在Web.config文件中配置一下邮件服务器,这里使用Google的服务器,大家可以使用自己的Gmail帐号,如下代码所示:
XML
<system.net>在浏览器中测试Web Service,确保它可以正确的发送邮件。编写一个简单
<mailSettings>
<smtp>
<network host="smtp.gmail.com" port="587" userName="terrylee@gmail.com" password="password"/>
</smtp>
</mailSettings>
</system.net>
用户界面,如下代码所示:
XAML
<Grid x:Name="LayoutRoot" Background="#333333">在Silverlight项目中添加Web Service引用,并编写代码来调用Web Service,相信大家都已经熟悉了该如何调用,如下代码所示:
<TextBox x:Name="txtToEmailAddress"></TextBox>
<TextBox x:Name="txtSubject"></TextBox>
<TextBox x:Name="txtBody"></TextBox>
<Button x:Name="btnSend" Content="发 送"
Click="OnSendClick"></Button>
</Grid>
C#
void OnSendClick(object sender, RoutedEventArgs e)注意在OnSendCompleted中我使用了HtmlPage对象来弹出一个浏览器对话框,这部分内容我们将在与浏览器集成一章详细讲解。
{
// 发送邮件地址
String fromAddress = "terrylee@gmail.com";
EmailServiceSoapClient client = new EmailServiceSoapClient();
client.SendCompleted += new EventHandler<SendCompletedEventArgs>(OnSendCompleted);
client.SendAsync(fromAddress,
this.txtToEmailAddress.Text,
this.txtSubject.Text,
this.txtBody.Text);
}
void OnSendCompleted(object sender, SendCompletedEventArgs e)
{
if (e.Result)
{
HtmlPage.Window.Alert("发送邮件成功!");
}
else
{
HtmlPage.Window.Alert("发送邮件成功!");
}
}
运行后输入相关信息,并发送邮件,如下图所示:

至此我们就完成一个在Silverlight中发送电子邮件的示例,大家如果有兴趣,还可以为其加上更加丰富的功能,如添加抄送人、密送人以及附件等。