Megosztás a következőn keresztül:


Xamarin.Essentials: Email

The Email class enables an application to open the default email application with a specified information including subject, body, and recipients (TO, CC, BCC).

To access the Email functionality the following platform specific setup is required.

If your project's Target Android version is set to Android 11 (R API 30) you must update your Android Manifest with queries that are used with the new package visibility requirements.

Open the AndroidManifest.xml file under the Properties folder and add the following inside of the manifest node:

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

Get started

To start using this API, read the getting started guide for Xamarin.Essentials to ensure the library is properly installed and set up in your projects.

Tip

To use the Email API on iOS you must run it on a physical device, else an exception will be thrown.

Using Email

Add a reference to Xamarin.Essentials in your class:

using Xamarin.Essentials;

The Email functionality works by calling the ComposeAsync method with an EmailMessage that contains information about the email:

public class EmailTest
{
    public async Task SendEmail(string subject, string body, List<string> recipients)
    {
        try
        {
            var message = new EmailMessage
            {
                Subject = subject,
                Body = body,
                To = recipients,
                //Cc = ccRecipients,
                //Bcc = bccRecipients
            };
            await Email.ComposeAsync(message);
        }
        catch (FeatureNotSupportedException fbsEx)
        {
            // Email is not supported on this device
        }
        catch (Exception ex)
        {
            // Some other exception occurred
        }
    }
}

File Attachments

This feature enables an app to email files in email clients on the device. Xamarin.Essentials will automatically detect the file type (MIME) and request the file to be added as an attachment. Every email client is different and may only support specific file extensions, or none at all.

Here is a sample of writing text to disk and adding it as an email attachment:

var message = new EmailMessage
{
    Subject = "Hello",
    Body = "World",
};

var fn = "Attachment.txt";
var file = Path.Combine(FileSystem.CacheDirectory, fn);
File.WriteAllText(file, "Hello World");

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

await Email.ComposeAsync(message);

Platform Differences

Not all email clients for Android support Html, since there is no way to detect this we recommend using PlainText when sending emails.

API

Find more Xamarin videos on Channel 9 and YouTube.