本小节介绍如何通过邮件将生成的贺卡发送给朋友。使用到了EmailMessage
API, 需要引入的命名空间为Windows.ApplicationModel.Email
。
请确保完成了以前的章节。
在MainPage.xaml.cs
页面,在SendMail_Click
方法中,新定义EmailMessage
的对象,将前一节中生成的Wishes.jpg文件作为邮件附件发送给其他人。 添加如下代码:
EmailMessage emailMessage = new EmailMessage();
emailMessage.Body = "Thanksgiving Card from your friend, this is generated by Card App.";
var stream1 = Windows.Storage.Streams.RandomAccessStreamReference.CreateFromFile(file);
var attachment = new Windows.ApplicationModel.Email.EmailAttachment(file.Name, stream1);
emailMessage.Attachments.Add(attachment);
await EmailManager.ShowComposeNewEmailAsync(emailMessage);
修改后, SendMail_Click
方法的完整代码如下:
private async void SendMail_Click(object sender, RoutedEventArgs e)
{
RenderTargetBitmap renderTrgBitmap = new RenderTargetBitmap();
await renderTrgBitmap.RenderAsync(gridMsg);
var pixelBuffer = await renderTrgBitmap.GetPixelsAsync();
var file = await KnownFolders.PicturesLibrary.CreateFileAsync("Wishes.jpg", CreationCollisionOption.ReplaceExisting);
using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
encoder.SetPixelData(BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Straight,
(uint)renderTrgBitmap.PixelWidth,
(uint)renderTrgBitmap.PixelHeight,
96d, 96d,
pixelBuffer.ToArray());
await encoder.FlushAsync();
}
EmailMessage emailMessage = new EmailMessage();
emailMessage.Body = "Thanksgiving Card from your friend, this is generated by Card App.";
var stream1 = Windows.Storage.Streams.RandomAccessStreamReference.CreateFromFile(file);
var attachment = new Windows.ApplicationModel.Email.EmailAttachment(file.Name, stream1);
emailMessage.Attachments.Add(attachment);
await EmailManager.ShowComposeNewEmailAsync(emailMessage);
}
运行程序,单击Get a Wishes按钮,再单击Send to Friend按钮。App将打开邮件程序,新建一个邮件,并将Wishes.jpg添加为邮件附件。