-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathMailjetClient.cs
More file actions
167 lines (137 loc) · 6.92 KB
/
MailjetClient.cs
File metadata and controls
167 lines (137 loc) · 6.92 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
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
using Mailjet.Client.Exceptions;
using Mailjet.Client.Helpers;
using Mailjet.Client.Resources;
using Mailjet.Client.TransactionalEmails;
using Mailjet.Client.TransactionalEmails.Response;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace Mailjet.Client
{
/// <summary>
/// Mailjet API wrapper
/// </summary>
public class MailjetClient : IMailjetClient
{
private HttpClient _httpClient;
public MailjetClient(string apiKey, string apiSecret, HttpMessageHandler httpMessageHandler = null)
{
InitHttpClient(httpMessageHandler);
_httpClient.UseBasicAuthentication(apiKey, apiSecret);
}
public MailjetClient(string token, HttpMessageHandler httpMessageHandler = null)
{
InitHttpClient(httpMessageHandler);
_httpClient.UseBearerAuthentication(token);
}
/// <summary>
/// Create MailJet client with predefined HttpClient instance
/// </summary>
/// <param name="httpClient"></param>
public MailjetClient(HttpClient httpClient)
{
if (httpClient == null)
{
throw new ArgumentNullException(nameof(httpClient));
}
if (httpClient.BaseAddress == null)
{
httpClient.SetDefaultSettings();
}
_httpClient = httpClient;
}
public string BaseAdress
{
get { return _httpClient.BaseAddress != null ? _httpClient.BaseAddress.ToString() : null; }
set { _httpClient.BaseAddress = !string.IsNullOrEmpty(value) ? new Uri(value) : null; }
}
public async Task<MailjetResponse> GetAsync(MailjetRequest request)
{
string url = request.BuildUrl();
var responseMessage = await _httpClient.GetAsync(url).ConfigureAwait(false);
JsonObject content = await HttpContentHelper.GetContentAsync(responseMessage).ConfigureAwait(false);
return new MailjetResponse(responseMessage.IsSuccessStatusCode, (int)responseMessage.StatusCode, content);
}
public async Task<MailjetResponse> PostAsync(MailjetRequest request)
{
string url = request.BuildUrl();
var output = request.Body.ToString();
HttpContent contentPost = new StringContent(output, Encoding.UTF8, MailjetConstants.JsonMediaType);
var responseMessage = await _httpClient.PostAsync(url, contentPost).ConfigureAwait(false);
JsonObject content = await HttpContentHelper.GetContentAsync(responseMessage).ConfigureAwait(false);
return new MailjetResponse(responseMessage.IsSuccessStatusCode, (int)responseMessage.StatusCode, content);
}
public async Task<MailjetResponse> PutAsync(MailjetRequest request)
{
string url = request.BuildUrl();
var output = request.Body.ToString();
HttpContent contentPut = new StringContent(output, Encoding.UTF8, MailjetConstants.JsonMediaType);
var responseMessage = await _httpClient.PutAsync(url, contentPut).ConfigureAwait(false);
JsonObject content = await HttpContentHelper.GetContentAsync(responseMessage).ConfigureAwait(false);
MailjetResponse mailjetResponse = new MailjetResponse(responseMessage.IsSuccessStatusCode, (int)responseMessage.StatusCode, content);
return mailjetResponse;
}
public async Task<MailjetResponse> DeleteAsync(MailjetRequest request)
{
string url = request.BuildUrl();
var responseMessage = await _httpClient.DeleteAsync(url).ConfigureAwait(false);
JsonObject content = await HttpContentHelper.GetContentAsync(responseMessage).ConfigureAwait(false);
return new MailjetResponse(responseMessage.IsSuccessStatusCode, (int)responseMessage.StatusCode, content);
}
private void InitHttpClient(HttpMessageHandler httpMessageHandler)
{
// Create HttpClient
_httpClient = (httpMessageHandler != null) ? new HttpClient(httpMessageHandler) : new HttpClient();
_httpClient.SetDefaultSettings();
}
/// <summary>
/// Sends a single transactional email using send API v3.1
/// </summary>
/// <exception cref="MailjetClientConfigurationException">Thrown when email count exceeds the max allowed number</exception>
/// <exception cref="MailjetServerException">Thrown when generic error returned from the server</exception>
public Task<TransactionalEmailResponse> SendTransactionalEmailAsync(TransactionalEmail transactionalEmail, bool isSandboxMode = false, bool advanceErrorHandling = true)
{
return SendTransactionalEmailsAsync(new[] { transactionalEmail }, isSandboxMode, advanceErrorHandling);
}
/// <summary>
/// Sends transactional emails using send API v3.1
/// </summary>
/// <exception cref="MailjetClientConfigurationException">Thrown when email count exceeds the max allowed number</exception>
/// <exception cref="MailjetServerException">Thrown when generic error returned from the server</exception>
public async Task<TransactionalEmailResponse> SendTransactionalEmailsAsync(IEnumerable<TransactionalEmail> transactionalEmails, bool isSandboxMode = false, bool advanceErrorHandling = true)
{
if (transactionalEmails.Count() > SendV31.MaxEmailsPerBatch || !transactionalEmails.Any())
throw new MailjetClientConfigurationException($"Send Emails API v3.1 allows to send not more than {SendV31.MaxEmailsPerBatch} emails per call");
var request = new SendEmailRequest
{
Messages = transactionalEmails.ToList(),
SandboxMode = isSandboxMode,
AdvanceErrorHandling = advanceErrorHandling
};
var serializerOptions = new JsonSerializerOptions()
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault
};
serializerOptions.Converters.Add(new JsonStringEnumConverter());
var clientRequest = new MailjetRequest
{
Resource = SendV31.Resource,
Body = JsonSerializer.SerializeToNode(request, serializerOptions).AsObject()
};
MailjetResponse clientResponse = await PostAsync(clientRequest)
.ConfigureAwait(false);
TransactionalEmailResponse result = clientResponse.Content.Deserialize<TransactionalEmailResponse>();
if (result.Messages == null && !clientResponse.IsSuccessStatusCode)
{
throw new MailjetServerException(clientResponse);
}
return result;
}
}
}