Skip to content

Commit 0fcae15

Browse files
committed
[ASP.NET Core] Replaced custom SendGrid implementation with NuGet package
1 parent bbf52bd commit 0fcae15

File tree

14 files changed

+53
-221
lines changed

14 files changed

+53
-221
lines changed

ASP.NET Core/Services/AspNetCoreTemplate.Services.Messaging/AspNetCoreTemplate.Services.Messaging.csproj

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
<Project Sdk="Microsoft.NET.Sdk">
22

33
<PropertyGroup>
4-
<TargetFramework>netcoreapp3.1</TargetFramework>
4+
<TargetFramework>netstandard2.0</TargetFramework>
55
<LangVersion>latest</LangVersion>
66
</PropertyGroup>
77

@@ -13,9 +13,7 @@
1313
</ItemGroup>
1414

1515
<ItemGroup>
16-
<PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="3.1.0" />
17-
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="3.1.0" />
18-
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
16+
<PackageReference Include="Sendgrid" Version="9.12.0" />
1917
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.113" PrivateAssets="all">
2018
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
2119
</PackageReference>
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
namespace AspNetCoreTemplate.Services.Messaging
2+
{
3+
public class EmailAttachment
4+
{
5+
public byte[] Content { get; set; }
6+
7+
public string FileName { get; set; }
8+
9+
public string MimeType { get; set; }
10+
}
11+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
namespace AspNetCoreTemplate.Services.Messaging
2+
{
3+
using System.Collections.Generic;
4+
using System.Threading.Tasks;
5+
6+
public interface IEmailSender
7+
{
8+
Task SendEmailAsync(string to, string subject, string htmlContent, IEnumerable<EmailAttachment> attachments = null);
9+
}
10+
}

ASP.NET Core/Services/AspNetCoreTemplate.Services.Messaging/ISmsSender.cs

Lines changed: 0 additions & 9 deletions
This file was deleted.

ASP.NET Core/Services/AspNetCoreTemplate.Services.Messaging/NullMessageSender.cs

Lines changed: 3 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,12 @@
11
namespace AspNetCoreTemplate.Services.Messaging
22
{
3+
using System.Collections.Generic;
34
using System.Threading.Tasks;
45

5-
using Microsoft.AspNetCore.Identity.UI.Services;
6-
7-
// This class is used by the application to send Email and SMS
8-
// when you turn on two-factor authentication in ASP.NET Identity.
9-
// For more details see this link https://go.microsoft.com/fwlink/?LinkID=532713
10-
public class NullMessageSender : IEmailSender, ISmsSender
6+
public class NullMessageSender : IEmailSender
117
{
12-
public Task SendEmailAsync(string email, string subject, string message)
13-
{
14-
// Plug in your email service here to send an email.
15-
return Task.CompletedTask;
16-
}
17-
18-
public Task SendSmsAsync(string number, string message)
8+
public Task SendEmailAsync(string to, string subject, string htmlContent, IEnumerable<EmailAttachment> attachments = null)
199
{
20-
// Plug in your SMS service here to send a text message.
2110
return Task.CompletedTask;
2211
}
2312
}

ASP.NET Core/Services/AspNetCoreTemplate.Services.Messaging/SendGrid/SendGridContent.cs

Lines changed: 0 additions & 23 deletions
This file was deleted.

ASP.NET Core/Services/AspNetCoreTemplate.Services.Messaging/SendGrid/SendGridEmail.cs

Lines changed: 0 additions & 23 deletions
This file was deleted.

ASP.NET Core/Services/AspNetCoreTemplate.Services.Messaging/SendGrid/SendGridMessage.cs

Lines changed: 0 additions & 46 deletions
This file was deleted.

ASP.NET Core/Services/AspNetCoreTemplate.Services.Messaging/SendGrid/SendGridPersonalization.cs

Lines changed: 0 additions & 18 deletions
This file was deleted.

ASP.NET Core/Services/AspNetCoreTemplate.Services.Messaging/SendGridEmailSender.cs

Lines changed: 25 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -1,101 +1,52 @@
11
namespace AspNetCoreTemplate.Services.Messaging
22
{
33
using System;
4-
using System.Net.Http;
5-
using System.Net.Http.Headers;
6-
using System.Text;
4+
using System.Collections.Generic;
5+
using System.Linq;
76
using System.Threading.Tasks;
87

9-
using AspNetCoreTemplate.Services.Messaging.SendGrid;
8+
using SendGrid;
9+
using SendGrid.Helpers.Mail;
1010

11-
using Microsoft.AspNetCore.Identity.UI.Services;
12-
using Microsoft.Extensions.Logging;
13-
14-
using Newtonsoft.Json;
15-
16-
// Documentation: https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/index.html
1711
public class SendGridEmailSender : IEmailSender
1812
{
19-
private const string AuthenticationScheme = "Bearer";
20-
private const string BaseUrl = "https://api.sendgrid.com/v3/";
21-
private const string SendEmailUrlPath = "mail/send";
13+
private readonly SendGridClient client;
2214

23-
private readonly string fromAddress;
24-
private readonly string fromName;
25-
private readonly HttpClient httpClient;
26-
private readonly ILogger logger;
15+
private readonly EmailAddress from;
2716

28-
public SendGridEmailSender(ILoggerFactory loggerFactory, string apiKey, string fromAddress, string fromName)
17+
public SendGridEmailSender(string apiKey, string fromAddress, string fromName)
2918
{
30-
if (loggerFactory == null)
31-
{
32-
throw new ArgumentNullException(nameof(loggerFactory));
33-
}
34-
35-
if (string.IsNullOrWhiteSpace(apiKey))
36-
{
37-
throw new ArgumentOutOfRangeException(nameof(apiKey));
38-
}
39-
40-
if (string.IsNullOrWhiteSpace(fromAddress))
41-
{
42-
throw new ArgumentOutOfRangeException(nameof(fromAddress));
43-
}
44-
45-
if (string.IsNullOrWhiteSpace(fromName))
46-
{
47-
throw new ArgumentOutOfRangeException(nameof(fromName));
48-
}
49-
50-
this.logger = loggerFactory.CreateLogger<SendGridEmailSender>();
51-
this.httpClient = new HttpClient();
52-
this.httpClient.DefaultRequestHeaders.Authorization =
53-
new AuthenticationHeaderValue(AuthenticationScheme, apiKey);
54-
this.httpClient.BaseAddress = new Uri(BaseUrl);
55-
this.fromAddress = fromAddress;
56-
this.fromName = fromName;
19+
this.client = new SendGridClient(apiKey);
20+
this.from = new EmailAddress(fromAddress, fromName);
5721
}
5822

59-
public async Task SendEmailAsync(string email, string subject, string message)
23+
public async Task SendEmailAsync(string to, string subject, string htmlContent, IEnumerable<EmailAttachment> attachments = null)
6024
{
61-
if (string.IsNullOrWhiteSpace(this.fromAddress))
62-
{
63-
throw new ArgumentOutOfRangeException(nameof(this.fromAddress));
64-
}
65-
66-
if (string.IsNullOrWhiteSpace(email))
25+
if (string.IsNullOrWhiteSpace(subject) && string.IsNullOrWhiteSpace(htmlContent))
6726
{
68-
throw new ArgumentOutOfRangeException(nameof(email));
27+
throw new ArgumentException("Subject and message should be provided.");
6928
}
7029

71-
if (string.IsNullOrWhiteSpace(subject) && string.IsNullOrWhiteSpace(message))
30+
var toAddress = new EmailAddress(to);
31+
var message = MailHelper.CreateSingleEmail(this.from, toAddress, subject, null, htmlContent);
32+
if (attachments?.Any() == true)
7233
{
73-
throw new ArgumentException("Subject and/or message must be provided.");
34+
foreach (var attachment in attachments)
35+
{
36+
message.AddAttachment(attachment.FileName, Convert.ToBase64String(attachment.Content), attachment.MimeType);
37+
}
7438
}
7539

76-
var msg = new SendGridMessage(
77-
new SendGridEmail(email),
78-
subject,
79-
new SendGridEmail(this.fromAddress, this.fromName),
80-
message);
8140
try
8241
{
83-
var json = JsonConvert.SerializeObject(msg);
84-
var response = await this.httpClient.PostAsync(
85-
SendEmailUrlPath,
86-
new StringContent(json, Encoding.UTF8, "application/json"));
87-
88-
if (!response.IsSuccessStatusCode)
89-
{
90-
// See if we can read the response for more information, then log the error
91-
var errorJson = await response.Content.ReadAsStringAsync();
92-
throw new Exception(
93-
$"SendGrid indicated failure! Code: {response.StatusCode}, reason: {errorJson}");
94-
}
42+
var response = await this.client.SendEmailAsync(message);
43+
Console.WriteLine(response.StatusCode);
44+
Console.WriteLine(await response.Body.ReadAsStringAsync());
9545
}
96-
catch (Exception ex)
46+
catch (Exception e)
9747
{
98-
this.logger.LogError($"Exception during sending email: {ex}");
48+
Console.WriteLine(e);
49+
throw;
9950
}
10051
}
10152
}

0 commit comments

Comments
 (0)