This repository has been archived by the owner on May 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 506
/
Email.ios.cs
81 lines (70 loc) · 2.95 KB
/
Email.ios.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
using System;
using System.IO;
using System.Threading.Tasks;
using Foundation;
using MessageUI;
using UIKit;
namespace Xamarin.Essentials
{
public static partial class Email
{
internal static bool IsComposeSupported =>
MFMailComposeViewController.CanSendMail ||
MainThread.InvokeOnMainThread(() => UIApplication.SharedApplication.CanOpenUrl(NSUrl.FromString("mailto:")));
static Task PlatformComposeAsync(EmailMessage message)
{
if (MFMailComposeViewController.CanSendMail)
return ComposeWithMailCompose(message);
else
return ComposeWithUrl(message);
}
static Task ComposeWithMailCompose(EmailMessage message)
{
// do this first so we can throw as early as possible
var parentController = Platform.GetCurrentViewController();
// create the controller
var controller = new MFMailComposeViewController();
if (!string.IsNullOrEmpty(message?.Body))
controller.SetMessageBody(message.Body, message.BodyFormat == EmailBodyFormat.Html);
if (!string.IsNullOrEmpty(message?.Subject))
controller.SetSubject(message.Subject);
if (message?.To?.Count > 0)
controller.SetToRecipients(message.To.ToArray());
if (message?.Cc?.Count > 0)
controller.SetCcRecipients(message.Cc.ToArray());
if (message?.Bcc?.Count > 0)
controller.SetBccRecipients(message.Bcc.ToArray());
if (message?.Attachments?.Count > 0)
{
foreach (var attachment in message.Attachments)
{
var data = NSData.FromFile(attachment.FullPath);
if (data == null)
throw new FileNotFoundException($"Attachment {attachment.FileName} not found.", attachment.FullPath);
controller.AddAttachmentData(data, attachment.ContentType, attachment.FileName);
}
}
var tcs = new TaskCompletionSource<bool>();
controller.Finished += (sender, e) =>
{
controller.DismissViewController(true, null);
tcs.TrySetResult(e.Result == MFMailComposeResult.Sent);
};
if (controller.PresentationController != null)
{
controller.PresentationController.Delegate = new Platform.UIPresentationControllerDelegate
{
DismissHandler = () => tcs.TrySetResult(false)
};
}
parentController.PresentViewController(controller, true, null);
return tcs.Task;
}
static async Task ComposeWithUrl(EmailMessage message)
{
var url = GetMailToUri(message);
var nsurl = NSUrl.FromString(url);
await Launcher.PlatformOpenAsync(nsurl);
}
}
}