分享方式:


電子郵件

流覽範例。 流覽範例

本文說明如何使用 .NET 多平臺應用程式 UI (.NET MAUI) IEmail 介面來開啟預設的電子郵件應用程式。 載入電子郵件應用程式時,可以設定為使用指定的收件者、主旨和本文建立新的電子郵件。

介面的預設實作 IEmail 可透過 Email.Default 屬性取得。 IEmail介面和Email類別都包含在 命名空間中Microsoft.Maui.ApplicationModel.Communication

開始使用

若要存取電子郵件功能,需要下列平臺特定設定。

如果您的項目目標 Android 版本設定為 Android 11(R API 30)或更高版本,您必須使用使用 Android 套件可見性需求的查詢來更新 Android 指令清單

[平臺/Android/AndroidManifest.xml] 檔案中,在 節點中manifest新增下列queries/intent節點:

<queries>
  <intent>
    <action android:name="android.intent.action.SENDTO" />
    <data android:scheme="mailto" />
  </intent>
</queries>

使用電子郵件

電子郵件功能的運作方式是提供電子郵件資訊做為 方法的 ComposeAsync 自變數。 在這裡範例中 EmailMessage ,類型是用來代表電子郵件資訊:

if (Email.Default.IsComposeSupported)
{

    string subject = "Hello friends!";
    string body = "It was great to see you last weekend.";
    string[] recipients = new[] { "john@contoso.com", "jane@contoso.com" };

    var message = new EmailMessage
    {
        Subject = subject,
        Body = body,
        BodyFormat = EmailBodyFormat.PlainText,
        To = new List<string>(recipients)
    };

    await Email.Default.ComposeAsync(message);
}

檔案附件

建立提供給電子郵件客戶端的電子郵件時,您可以新增檔案附件。 系統會自動偵測檔類型 (MIME),因此您不需要指定它。 某些郵件用戶端可能會限制您傳送的檔類型,或可能完全防止附件。

EmailMessage.Attachments使用集合來管理附加至電子郵件的檔案。

下列範例示範如何將圖像檔新增至電子郵件附件。

if (Email.Default.IsComposeSupported)
{

    string subject = "Hello friends!";
    string body = "It was great to see you last weekend. I've attached a photo of our adventures together.";
    string[] recipients = new[] { "john@contoso.com", "jane@contoso.com" };

    var message = new EmailMessage
    {
        Subject = subject,
        Body = body,
        BodyFormat = EmailBodyFormat.PlainText,
        To = new List<string>(recipients)
    };

    string picturePath = Path.Combine(FileSystem.CacheDirectory, "memories.jpg");

    message.Attachments.Add(new EmailAttachment(picturePath));

    await Email.Default.ComposeAsync(message);
}

平台差異

並非所有 Android 的電子郵件客戶程式都支援 EmailBodyFormat.Html,因為無法偵測到此狀況,因此建議您在傳送電子郵件時使用 EmailBodyFormat.PlainText