forked from lukencode/FluentEmail
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathAzureEmailSender.cs
191 lines (162 loc) · 7.54 KB
/
AzureEmailSender.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Communication.Email;
using Azure.Core;
using FluentEmail.Core;
using FluentEmail.Core.Interfaces;
using FluentEmail.Core.Models;
namespace FluentEmail.Azure.Email;
// Read more about Azure Email Communication Services here:
// https://learn.microsoft.com/en-us/azure/communication-services/quickstarts/email/send-email?pivots=programming-language-csharp
public class AzureEmailSender : ISender
{
private EmailClient _emailClient;
/// <summary>
/// The priority header to use when specifying the importance of an email.
/// Values: 1-High, 3-Normal (default), 5-Low
/// https://sendgrid.com/blog/magic-email-headers/
/// </summary>
const string PriorityHeader = "X-Priority";
/// <summary>
/// Initializes a new instance of <see cref="AzureEmailSender"/>
/// </summary>
/// <param name="connectionString">Connection string acquired from the Azure Communication Services resource.</param>
public AzureEmailSender(string connectionString)
{
_emailClient = new EmailClient(connectionString);
}
/// <summary> Initializes a new instance of <see cref="AzureEmailSender"/>.</summary>
/// <param name="connectionString">Connection string acquired from the Azure Communication Services resource.</param>
/// <param name="options">Client option exposing <see cref="ClientOptions.Diagnostics"/>, <see cref="ClientOptions.Retry"/>, <see cref="ClientOptions.Transport"/>, etc.</param>
public AzureEmailSender(string connectionString, EmailClientOptions options)
{
_emailClient = new EmailClient(connectionString, options);
}
/// <summary> Initializes a new instance of <see cref="AzureEmailSender"/>.</summary>
/// <param name="endpoint">The URI of the Azure Communication Services resource.</param>
/// <param name="keyCredential">The <see cref="AzureKeyCredential"/> used to authenticate requests.</param>
/// <param name="options">Client option exposing <see cref="ClientOptions.Diagnostics"/>, <see cref="ClientOptions.Retry"/>, <see cref="ClientOptions.Transport"/>, etc.</param>
public AzureEmailSender(Uri endpoint, AzureKeyCredential keyCredential, EmailClientOptions options = default)
{
_emailClient = new EmailClient(endpoint, keyCredential, options);
}
/// <summary> Initializes a new instance of <see cref="AzureEmailSender"/>.</summary>
/// <param name="endpoint">The URI of the Azure Communication Services resource.</param>
/// <param name="tokenCredential">The TokenCredential used to authenticate requests, such as DefaultAzureCredential.</param>
/// <param name="options">Client option exposing <see cref="ClientOptions.Diagnostics"/>, <see cref="ClientOptions.Retry"/>, <see cref="ClientOptions.Transport"/>, etc.</param>
public AzureEmailSender(Uri endpoint, TokenCredential tokenCredential, EmailClientOptions options = default)
{
_emailClient = new EmailClient(endpoint, tokenCredential, options);
}
public SendResponse Send(IFluentEmail email, CancellationToken? token = null)
{
return SendAsync(email, token).GetAwaiter().GetResult();
}
public async Task<SendResponse> SendAsync(IFluentEmail email, CancellationToken? token = null)
{
var emailContent = new EmailContent(email.Data.Subject);
if (email.Data.IsHtml)
{
emailContent.Html = email.Data.Body;
}
else
{
emailContent.PlainText = email.Data.Body;
}
var toRecipients = new List<EmailAddress>();
if(email.Data.ToAddresses.Any())
{
email.Data.ToAddresses.ForEach(r => toRecipients.Add(new EmailAddress(r.EmailAddress, r.Name)));
}
var ccRecipients = new List<EmailAddress>();
if(email.Data.CcAddresses.Any())
{
email.Data.CcAddresses.ForEach(r => ccRecipients.Add(new EmailAddress(r.EmailAddress, r.Name)));
}
var bccRecipients = new List<EmailAddress>();
if(email.Data.BccAddresses.Any())
{
email.Data.BccAddresses.ForEach(r => bccRecipients.Add(new EmailAddress(r.EmailAddress, r.Name)));
}
var emailRecipients = new EmailRecipients(toRecipients, ccRecipients, bccRecipients);
// Azure Email Sender doesn't allow us to specify the 'from' display name (instead the sender name is defined in the blade configuration)
// var sender = $"{email.Data.FromAddress.Name} <{email.Data.FromAddress.EmailAddress}>";
var sender = email.Data.FromAddress.EmailAddress;
var emailMessage = new EmailMessage(sender, emailRecipients, emailContent);
if (email.Data.ReplyToAddresses.Any(a => !string.IsNullOrWhiteSpace(a.EmailAddress)))
{
foreach (var emailAddress in email.Data.ReplyToAddresses)
{
emailMessage.ReplyTo.Add(new EmailAddress(emailAddress.EmailAddress, emailAddress.Name));
}
}
if (email.Data.Headers.Any())
{
foreach (var header in email.Data.Headers)
{
emailMessage.Headers.Add(header.Key, header.Value);
}
}
if(email.Data.Attachments.Any())
{
foreach (var attachment in email.Data.Attachments)
{
emailMessage.Attachments.Add(await ConvertAttachment(attachment));
}
}
emailMessage.Headers.Add(PriorityHeader, (email.Data.Priority switch
{
Priority.High => 1,
Priority.Normal => 3,
Priority.Low => 5,
_ => 3
}).ToString());
try
{
EmailSendOperation sendOperation = await _emailClient.SendAsync(WaitUntil.Started, emailMessage, token ?? CancellationToken.None);
var messageId = sendOperation.Id;
if (string.IsNullOrWhiteSpace(messageId))
{
return new SendResponse
{
ErrorMessages = new List<string> { "Failed to send email." }
};
}
// We want to verify that the email was sent.
// The maximum time we will wait for the message status to be sent/delivered is 2 minutes.
var cancellationToken = new CancellationTokenSource(TimeSpan.FromMinutes(2));
var sendStatusResult = sendOperation.WaitForCompletion(cancellationToken.Token).Value;
if (sendStatusResult.Status == EmailSendStatus.Succeeded)
{
return new SendResponse
{
MessageId = messageId
};
}
if (cancellationToken.IsCancellationRequested)
{
return new SendResponse
{
ErrorMessages = new List<string> { "Failed to send email, timed out while getting status." }
};
}
return new SendResponse
{
ErrorMessages = new List<string> { "Failed to send email." }
};
}
catch (Exception ex)
{
return new SendResponse
{
ErrorMessages = new List<string> { ex.Message }
};
}
}
private async Task<EmailAttachment> ConvertAttachment(Attachment attachment) =>
new(attachment.Filename, attachment.ContentType, await BinaryData.FromStreamAsync(attachment.Data));
}