-
Notifications
You must be signed in to change notification settings - Fork 442
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add MailPace Sender #379
Open
maartenba
wants to merge
1
commit into
lukencode:master
Choose a base branch
from
maartenba:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Add MailPace Sender #379
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -22,6 +22,7 @@ Maintained by Luke Lowrey - follow me on twitter **[@lukencode](https://twitter | |
|
||
* [FluentEmail.Mailgun](src/Senders/FluentEmail.Mailgun) - Send emails via MailGun's REST API. | ||
* [FluentEmail.SendGrid](src/Senders/FluentEmail.SendGrid) - Send email via the SendGrid API. | ||
* [FluentEmail.MailPace](src/Senders/FluentEmail.MailPace) - Send emails via the [MailPace](https://www.mailpace.com/) REST API. | ||
* [FluentEmail.Mailtrap](src/Senders/FluentEmail.Mailtrap) - Send emails to Mailtrap. Uses [FluentEmail.Smtp](src/Senders/FluentEmail.Smtp) for delivery. | ||
* [FluentEmail.MailKit](src/Senders/FluentEmail.MailKit) - Send emails using the [MailKit](https://github.com/jstedfast/MailKit) email library. | ||
|
||
|
@@ -159,5 +160,4 @@ var email = new Email("[email protected]") | |
.UsingTemplateFromEmbedded("Example.Project.Namespace.template-name.cshtml", | ||
new { Name = "Bob" }, | ||
TypeFromYourEmbeddedAssembly.GetType().GetTypeInfo().Assembly); | ||
``` | ||
|
||
``` |
19 changes: 19 additions & 0 deletions
19
src/Senders/FluentEmail.MailPace/FluentEmail.MailPace.csproj
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
<Description>Send emails via MailPace using their REST API</Description> | ||
<AssemblyTitle>Fluent Email - MailPace</AssemblyTitle> | ||
<Authors>Luke Lowrey;Ben Cull;Github Contributors</Authors> | ||
<PackageTags>$(PackageTags);smtp</PackageTags> | ||
<TargetFramework>netstandard2.0</TargetFramework> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="Newtonsoft.Json" Version="13.0.2" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<ProjectReference Include="..\..\FluentEmail.Core\FluentEmail.Core.csproj" /> | ||
</ItemGroup> | ||
|
||
</Project> |
18 changes: 18 additions & 0 deletions
18
src/Senders/FluentEmail.MailPace/FluentEmailMailPaceBuilderExtensions.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
using FluentEmail.Core.Interfaces; | ||
using FluentEmail.MailPace; | ||
using Microsoft.Extensions.DependencyInjection.Extensions; | ||
|
||
// ReSharper disable once CheckNamespace | ||
namespace Microsoft.Extensions.DependencyInjection | ||
{ | ||
public static class FluentEmailMailPaceBuilderExtensions | ||
{ | ||
public static FluentEmailServicesBuilder AddMailPaceSender( | ||
this FluentEmailServicesBuilder builder, | ||
string serverToken) | ||
{ | ||
builder.Services.TryAdd(ServiceDescriptor.Scoped<ISender>(_ => new MailPaceSender(serverToken))); | ||
return builder; | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
using Newtonsoft.Json; | ||
|
||
namespace FluentEmail.MailPace; | ||
|
||
public class MailPaceAttachment | ||
{ | ||
[JsonProperty("name")] public string Name { get; set; } | ||
[JsonProperty("content")] public string Content { get; set; } | ||
[JsonProperty("content_type")] public string ContentType { get; set; } | ||
[JsonProperty("cid", NullValueHandling = NullValueHandling.Ignore)] public string Cid { get; set; } | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
using System.Collections.Generic; | ||
using Newtonsoft.Json; | ||
|
||
namespace FluentEmail.MailPace; | ||
|
||
public class MailPaceResponse | ||
{ | ||
[JsonProperty("id", NullValueHandling = NullValueHandling.Ignore)] public string Id { get; set; } | ||
[JsonProperty("status", NullValueHandling = NullValueHandling.Ignore)] public string Status { get; set; } | ||
[JsonProperty("error")] public string Error { get; set; } | ||
[JsonProperty("errors")] public Dictionary<string, List<string>> Errors { get; set; } = new(); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
using System.Collections.Generic; | ||
using Newtonsoft.Json; | ||
|
||
namespace FluentEmail.MailPace; | ||
|
||
public class MailPaceSendRequest | ||
{ | ||
[JsonProperty("from")] public string From { get; set; } | ||
[JsonProperty("to")] public string To { get; set; } | ||
[JsonProperty("cc", NullValueHandling = NullValueHandling.Ignore)] public string Cc { get; set; } | ||
[JsonProperty("bcc", NullValueHandling = NullValueHandling.Ignore)] public string Bcc { get; set; } | ||
[JsonProperty("subject")] public string Subject { get; set; } | ||
[JsonProperty("htmlbody", NullValueHandling = NullValueHandling.Ignore)] public string HtmlBody { get; set; } | ||
[JsonProperty("textbody", NullValueHandling = NullValueHandling.Ignore)] public string TextBody { get; set; } | ||
[JsonProperty("replyto", NullValueHandling = NullValueHandling.Ignore)] public string ReplyTo { get; set; } | ||
[JsonProperty("attachments")] public List<MailPaceAttachment> Attachments { get; set; } = new(0); | ||
[JsonProperty("tags")] public List<string> Tags { get; set; } = new(0); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,143 @@ | ||
using System; | ||
using System.IO; | ||
using System.Linq; | ||
using System.Net.Http; | ||
using System.Net.Http.Headers; | ||
using System.Text; | ||
using System.Threading; | ||
using System.Threading.Tasks; | ||
using FluentEmail.Core; | ||
using FluentEmail.Core.Interfaces; | ||
using FluentEmail.Core.Models; | ||
using Newtonsoft.Json; | ||
|
||
namespace FluentEmail.MailPace; | ||
|
||
public class MailPaceSender : ISender, IDisposable | ||
{ | ||
private readonly HttpClient _httpClient; | ||
|
||
public MailPaceSender(string serverToken) | ||
{ | ||
_httpClient = new HttpClient(); | ||
_httpClient.DefaultRequestHeaders.Add("MailPace-Server-Token", serverToken); | ||
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); | ||
} | ||
|
||
public SendResponse Send(IFluentEmail email, CancellationToken? token = null) => | ||
SendAsync(email, token).GetAwaiter().GetResult(); | ||
|
||
public async Task<SendResponse> SendAsync(IFluentEmail email, CancellationToken? token = null) | ||
{ | ||
var sendRequest = BuildSendRequestFor(email); | ||
|
||
var content = new StringContent(JsonConvert.SerializeObject(sendRequest), Encoding.UTF8, "application/json"); | ||
|
||
var response = await _httpClient.PostAsync("https://app.mailpace.com/api/v1/send", content) | ||
.ConfigureAwait(false); | ||
|
||
var mailPaceResponse = await TryOrNull(async () => JsonConvert.DeserializeObject<MailPaceResponse>( | ||
await response.Content.ReadAsStringAsync())) ?? new MailPaceResponse(); | ||
|
||
if (response.IsSuccessStatusCode) | ||
{ | ||
return new SendResponse { MessageId = mailPaceResponse.Id }; | ||
} | ||
else | ||
{ | ||
var result = new SendResponse(); | ||
|
||
if (!string.IsNullOrEmpty(mailPaceResponse.Error)) | ||
{ | ||
result.ErrorMessages.Add(mailPaceResponse.Error); | ||
} | ||
|
||
if (mailPaceResponse.Errors != null && mailPaceResponse.Errors.Count != 0) | ||
{ | ||
result.ErrorMessages.AddRange(mailPaceResponse.Errors | ||
.Select(it => $"{it.Key}: {string.Join("; ", it.Value)}")); | ||
} | ||
|
||
if (!result.ErrorMessages.Any()) | ||
{ | ||
result.ErrorMessages.Add(response.ReasonPhrase ?? "An unknown error has occurred."); | ||
} | ||
|
||
return result; | ||
} | ||
} | ||
|
||
private static MailPaceSendRequest BuildSendRequestFor(IFluentEmail email) | ||
{ | ||
var sendRequest = new MailPaceSendRequest | ||
{ | ||
From = $"{email.Data.FromAddress.Name} <{email.Data.FromAddress.EmailAddress}>", | ||
To = string.Join(",", email.Data.ToAddresses.Select(it => !string.IsNullOrEmpty(it.Name) ? $"{it.Name} <{it.EmailAddress}>" : it.EmailAddress)), | ||
Subject = email.Data.Subject | ||
}; | ||
|
||
if (email.Data.CcAddresses.Any()) | ||
{ | ||
sendRequest.Cc = string.Join(",", email.Data.CcAddresses.Select(it => !string.IsNullOrEmpty(it.Name) ? $"{it.Name} <{it.EmailAddress}>" : it.EmailAddress)); | ||
} | ||
|
||
if (email.Data.BccAddresses.Any()) | ||
{ | ||
sendRequest.Bcc = string.Join(",", email.Data.BccAddresses.Select(it => !string.IsNullOrEmpty(it.Name) ? $"{it.Name} <{it.EmailAddress}>" : it.EmailAddress)); | ||
} | ||
|
||
if (email.Data.ReplyToAddresses.Any()) | ||
{ | ||
sendRequest.ReplyTo = string.Join(",", email.Data.ReplyToAddresses.Select(it => !string.IsNullOrEmpty(it.Name) ? $"{it.Name} <{it.EmailAddress}>" : it.EmailAddress)); | ||
} | ||
|
||
if (email.Data.IsHtml) | ||
{ | ||
sendRequest.HtmlBody = email.Data.Body; | ||
if (!string.IsNullOrEmpty(email.Data.PlaintextAlternativeBody)) | ||
{ | ||
sendRequest.TextBody = email.Data.PlaintextAlternativeBody; | ||
} | ||
} | ||
else | ||
{ | ||
sendRequest.TextBody = email.Data.Body; | ||
} | ||
|
||
if (email.Data.Tags.Any()) | ||
{ | ||
sendRequest.Tags.AddRange(email.Data.Tags); | ||
} | ||
|
||
if (email.Data.Attachments.Any()) | ||
{ | ||
sendRequest.Attachments.AddRange( | ||
email.Data.Attachments.Select(it => new MailPaceAttachment | ||
{ | ||
Name = it.Filename, | ||
Content = it.Data.ConvertToBase64(), | ||
ContentType = it.ContentType ?? Path.GetExtension(it.Filename), // jpeg, jpg, png, gif, txt, pdf, docx, xlsx, pptx, csv, att, ics, ical, html, zip | ||
Cid = it.IsInline ? it.ContentId : null | ||
})); | ||
} | ||
|
||
return sendRequest; | ||
} | ||
|
||
private async Task<T> TryOrNull<T>(Func<Task<T>> method) | ||
{ | ||
try | ||
{ | ||
return await method(); | ||
} | ||
catch | ||
{ | ||
return default; | ||
} | ||
} | ||
|
||
public void Dispose() | ||
{ | ||
_httpClient.Dispose(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
using System; | ||
using System.IO; | ||
|
||
namespace FluentEmail.MailPace; | ||
|
||
public static class StreamExtensions | ||
{ | ||
public static string ConvertToBase64(this Stream stream) | ||
{ | ||
if (stream is MemoryStream memoryStream) | ||
{ | ||
return Convert.ToBase64String(memoryStream.ToArray()); | ||
} | ||
|
||
var bytes = new Byte[(int)stream.Length]; | ||
|
||
stream.Seek(0, SeekOrigin.Begin); | ||
// ReSharper disable once MustUseReturnValue | ||
stream.Read(bytes, 0, (int)stream.Length); | ||
|
||
return Convert.ToBase64String(bytes); | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What was the reason to not bind this in Singleton scope? If there are a large number of concurrent requests couldn't you get resource exhaustion due to all the HttpClients that are created in MailPaceSender's constructor?
Microsoft indicates either HttpClient should be created in singleton scope or use IHttpClientFactory. https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/http/httpclient-guidelines
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You are right! Singleton makes more sense here.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The one caveat with singleton on this class is not being able to set the PooledConnectionLifetime on the internal HttpClient itself. Binding in Singleton scope would help with resource exhaustion but there could be a potential issue with long lived connections. Changes to DNS records may not be picked up. It might be better to manage the HttpClient lifecycle inside MailGunSender and MailPaceSender and set the PooledConnectionLifetime to some reasonable default. Then it won't matter how ISender is bound.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Would passing in
IHttpClientFactory
be a better option? Let the DI container handleHttpClient
lifetimes?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes I think that should work too.
I had a play around with this for MailGunSender in #382