简体   繁体   中英

How to send email with attachments in WinUI app?

My application is a WinUI desktop application using.Net 6.

<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows10.0.19041.0</TargetFramework>
<UseWinUI>true</UseWinUI>

I thought I could use the EmailManager from UWP (which supports email attachments) but I get the following error when I do.

System.Runtime.InteropServices.COMException (0x80070032): The request is not supported. (0x80070032)
   at WinRT.ExceptionHelpers.<ThrowExceptionForHR>g__Throw|20_0(Int32 hr)
   at WinRT.ExceptionHelpers.ThrowExceptionForHR(Int32 hr)
   at ABI.Windows.ApplicationModel.Email.IEmailManagerStaticsMethods.ShowComposeNewEmailAsync(IObjectReference _obj, EmailMessage message)
   at Windows.ApplicationModel.Email.EmailManager.ShowComposeNewEmailAsync(EmailMessage message)
   at WinUIApp.MainWindow.ComposeEmail(String subject, String messageBody)

What is the correct API to use to send emails from a WinUI application?

Code

I made the application using the default WinUI template and simply added the following code in MainWindows.xaml.cs to test.

private void myButton_Click(object sender, RoutedEventArgs e)
{
    myButton.Content = "Clicked";

    ComposeEmail("Bob", "Hello Bob.");
}

private async Task ComposeEmail(string subject, string messageBody)
{
    try
    {
        var emailMessage = new Windows.ApplicationModel.Email.EmailMessage();
        await Windows.ApplicationModel.Email.EmailManager.ShowComposeNewEmailAsync(emailMessage);
    }
    catch (Exception e)
    {
        Debug.WriteLine(e);
    }
}

Note that the previous code works fine in a UWP app. It launches the Mail app. I was expecting it to do the same in my WinUI app, but it doesn't.

The EmailManager API is only supported with UWP apps, because it depends on Windows.UI.Core.CoreWindow Class 's GetForCurrentThread method which always get backs null for non-UWP apps .

You can check this dependency if you disassemble the ShowComposeNewEmailAsync function, as shown in this screenshot here:

在此处输入图像描述

Some of these WinRT classes have been modified to support the IInitializeWindow trick to support classical HWNDs, but it seems it's not the case here. Maybe you can report that to Microsoft so they can improve it.

So you'll have to find other non-WinRT/UWP ways to send email.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM