-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathSendGridService.cs
More file actions
50 lines (45 loc) · 1.58 KB
/
SendGridService.cs
File metadata and controls
50 lines (45 loc) · 1.58 KB
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
using Newtonsoft.Json;
using OrderCloud.Catalyst;
using SendGrid;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace OrderCloud.Integrations.Messaging.SendGrid
{
public class SendGridService : OCIntegrationService, ISingleEmailSender
{
protected readonly SendGridClient _client;
protected readonly string URL = "https://api.sendgrid.com/v3/mail/send";
public SendGridService(SendGridConfig defaultConfig) : base(defaultConfig)
{
_client = new SendGridClient(defaultConfig.ApiKey);
}
/// <summary>
/// See https://docs.sendgrid.com/api-reference/mail-send/mail-send
/// </summary>
public async Task SendSingleEmailAsync(EmailMessage message, OCIntegrationConfig overrideConfig = null)
{
var client = _client;
if (overrideConfig != null)
{
var config = ValidateConfig<SendGridConfig>(overrideConfig);
client = new SendGridClient(config.ApiKey);
}
var sendGridModel = SendGridSingleEmailMessageMapper.ToSendGridMessage(message);
var response = await client.SendEmailAsync(sendGridModel);
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
throw new IntegrationAuthFailedException(overrideConfig ?? _defaultConfig, URL, 401);
}
else if (!response.IsSuccessStatusCode)
{
var jsonString = await response.Body.ReadAsStringAsync();
var body = JsonConvert.DeserializeObject<SendGridErrorResponse>(jsonString);
throw new IntegrationErrorResponseException(overrideConfig ?? _defaultConfig, URL, (int)response.StatusCode, body);
}
}
}
}