M3: 发送邮件附件(2)
阅读原文时间:2024年06月26日阅读:1

本小节介绍如何通过邮件将生成的贺卡发送给朋友。使用到了EmailMessageAPI, 需要引入的命名空间为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添加为邮件附件。

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章