-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathProgram.cs
More file actions
406 lines (340 loc) · 14 KB
/
Program.cs
File metadata and controls
406 lines (340 loc) · 14 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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
using System.Diagnostics.CodeAnalysis;
using System.Net.Mime;
using Mailtrap;
using Mailtrap.Core.Models;
using Mailtrap.Core.Validation;
using Mailtrap.Emails.Models;
using Mailtrap.Emails.Requests;
using Mailtrap.Emails.Responses;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
/// <summary>
/// Example to demonstrate ways on how to send emails in batch
/// Also shows different ways of creating BatchEmailRequest
/// with a variety of parameters and attributes.
/// </summary>
[SuppressMessage("CodeQuality", "IDE0051:Remove unused private members", Justification = "Example")]
internal sealed class Program
{
private static async Task Main(string[] args)
{
HostApplicationBuilder hostBuilder = Host.CreateApplicationBuilder(args);
IConfigurationSection config = hostBuilder.Configuration.GetSection("Mailtrap");
hostBuilder.Services.AddMailtrapClient(config);
using IHost host = hostBuilder.Build();
ILogger logger = host.Services.GetRequiredService<ILogger<Program>>();
try
{
IMailtrapClient mailtrapClient = host.Services.GetRequiredService<IMailtrapClient>();
// Create batch email request
BatchEmailRequest request = BatchRequest();
// It is better to validate request before sending,
// since send method will do that anyway and throw an exception
// in case of validation failure.
ValidationResult validationResult = request.Validate();
if (!validationResult.IsValid)
{
logger.LogError("Malformed email request:\n{ValidationResult}", validationResult.ToString("\n"));
return;
}
// Send email batch and get response
BatchEmailResponse? response = await mailtrapClient.BatchEmail().Send(request);
// Analyze response in case for failures
if (response is not null)
{
//Analyze errors
foreach (var error in response.Errors)
{
logger.LogError("Error: {Error}", error);
}
//Analyze individual message responses
foreach (BatchSendEmailResponse messageResponse in response.Responses)
{
if (messageResponse.Success)
{
logger.LogInformation("Message is successful");
}
else
{
logger.LogError("Message sending failed");
//Iterate message ids to identify which recipient(s) it was failed
foreach (var messageId in messageResponse.MessageIds)
{
logger.LogError("Message ID {Id} failed", messageId);
}
//Analyze message errors
foreach (var error in messageResponse.Errors)
{
logger.LogError("Error: {Error}", error);
}
}
}
}
}
catch (Exception ex)
{
logger.LogError(ex, "An error occurred while sending email.");
Environment.ExitCode = -1;
throw;
}
}
/// <summary>
/// Very basic example of creating BatchEmailRequest.
/// </summary>
private static BatchEmailRequest BatchRequest()
{
var from = new EmailAddress("john.doe@galaxy.net", "John Doe");
var replyTo = new EmailAddress("noreply@galaxy.net");
// Base request contains common properties for all emails in the batch.
// You can override base request properties in each individual email request.
var baseRequest = new EmailRequest
{
From = from,
ReplyTo = replyTo
};
// Creating batch request itself.
// Put in as many individual email requests as you need.
var request = new BatchEmailRequest
{
Base = baseRequest,
Requests = new List<SendEmailRequest>()
{
BasicRequest(),
UsingFluentStyle(),
EmailFromTemplate(),
WithAttachments(),
RegularKitchenSink(),
FluentStyleKitchenSink()
}
};
return request;
}
/// <summary>
/// You can use <see cref="BatchEmailRequestBuilder"/> and <see cref="EmailRequestBuilder"/> to create request in a fluent style.<br/>
/// Much cleaner and easier to read.
/// </summary>
private static BatchEmailRequest BatchRequestFluentStyle()
{
var from = new EmailAddress("john.doe@galaxy.net", "John Doe");
var replyTo = new EmailAddress("noreply@galaxy.net");
// Base request contains common properties for all emails in the batch.
// You can override base request properties in each individual email request.
// Creating batch request itself.
// Put in as many individual email requests as you need.
return BatchEmailRequest
.Create()
.Base(b => b
.From(from)
.ReplyTo(replyTo))
.Requests(
BasicRequest(),
UsingFluentStyle(),
EmailFromTemplate(),
WithAttachments(),
RegularKitchenSink(),
FluentStyleKitchenSink())
.Requests(r => r
.To("hero.bill@galaxy.net")
.Text("Dear Bill,\n\nSee you soon!"));
}
/// <summary>
/// Very basic example of creating <see cref="SendEmailRequest"/>.
/// </summary>
private static SendEmailRequest BasicRequest()
{
var from = new EmailAddress("john.doe@demomailtrap.com", "John Doe");
var to = new EmailAddress("hero.bill@galaxy.net");
var cc = new EmailAddress("star.lord@galaxy.net");
var request = new SendEmailRequest
{
From = from,
Subject = "Invitation to Earth",
TextBody = "Dear Bill,\n\nIt will be a great pleasure to see you on our blue planet next weekend.\n\nBest regards, John."
};
// You can specify up to 1000 recipients in total across the To, Cc, and Bcc fields.
// At least one of recipient collections must contain at least one recipient.
request.To.Add(to);
request.Cc.Add(cc);
request.Bcc.Add(from);
return request;
}
/// <summary>
/// You can use <see cref="SendEmailRequestBuilder"/> to create request in a fluent style.<br/>
/// Much cleaner and easier to read.
/// </summary>
private static SendEmailRequest UsingFluentStyle()
{
return SendEmailRequest
.Create()
.From("john.doe@demomailtrap.com", "John Doe")
.To("hero.bill@galaxy.net")
.Cc("star.lord@galaxy.net")
.Subject("Invitation to Earth")
.Text("Dear Bill,\n\nIt will be a great pleasure to see you on our blue planet next weekend.\n\nBest regards, John.");
}
/// <summary>
/// In case of using templates, you can specify predefined template ID instead of subject, category and body. <br/>
/// Subject, Category, HTML and text body must be left empty in this scenario.
/// </summary>
private static SendEmailRequest EmailFromTemplate()
{
return SendEmailRequest
.Create()
.From("john.doe@demomailtrap.com", "John Doe")
.To("hero.bill@galaxy.net")
.Template("60dca11e-0bc2-42ea-91a8-5ff196acb3f9") // ID of template obtained/created via EmailTemplates API
.TemplateVariables(new Dictionary<string, string>
{
{ "name", "Bill" },
{ "sender", "John" }
});
}
/// <summary>
/// You can attach files to the email
/// </summary>
private static SendEmailRequest WithAttachments()
{
SendEmailRequest request = SendEmailRequest
.Create()
.From("john.doe@demomailtrap.com", "John Doe")
.To("hero.bill@galaxy.net")
.Subject("Invitation to Earth")
.Text("Dear Bill,\n\nIt will be a great pleasure to see you on our blue planet next weekend.\n\nBest regards, John.");
var filePaths = new[] { @"C:\files\preview.pdf", @"C:\files\logo.png" };
foreach (var filePath in filePaths)
{
if (!File.Exists(filePath))
{
continue;
}
var fileName = Path.GetFileName(filePath);
var bytes = File.ReadAllBytes(filePath);
var fileContent = Convert.ToBase64String(bytes);
var ext = Path.GetExtension(filePath).ToUpperInvariant();
var mimeType = ext switch
{
".PNG" => MediaTypeNames.Image.Png,
".PDF" => MediaTypeNames.Application.Pdf,
_ => MediaTypeNames.Application.Octet
};
request.Attach(
content: fileContent,
fileName: fileName,
disposition: DispositionType.Attachment,
mimeType: mimeType);
}
return request;
}
/// <summary>
/// Everything in one place.
/// </summary>
private static SendEmailRequest RegularKitchenSink()
{
var request = new SendEmailRequest
{
From = new("john.doe@demomailtrap.com", "John Doe"),
Subject = "Invitation to Earth"
};
request.To.Add(new("hero.bill@galaxy.net"));
request.Cc.Add(new("ursa@ursamajor.gov"));
request.Bcc.Add(new("aliens@milkyway.net"));
request.ReplyTo = new("no-reply@earth.com");
// HTML body.
// At least one of the Text or Html body must be specified.
request.HtmlBody =
"<h2>Greetings, Bill!</h2>" +
"<p>It will be a great pleasure to see you on our blue planet next weekend.</p>" +
"<p>Regards,<br/>" +
"John</p>";
// Plain text body.
// Will be used in case HTML body is missing or is not supported by the recipient.
request.TextBody =
"Dear Bill,\n\n" +
"It will be a great pleasure to see you on our blue planet next weekend.\n\n" +
"Best regards, John.";
// Set category for better classification.
request.Category = "Invitation";
// Add an attachment
var filePath = @"C:\files\preview.pdf";
var fileName = "preview.pdf";
var bytes = File.ReadAllBytes(filePath);
var fileContent = Convert.ToBase64String(bytes);
var attachment = new Attachment(
content: fileContent,
fileName: fileName,
disposition: DispositionType.Attachment,
mimeType: MediaTypeNames.Application.Pdf,
contentId: "attachment_1");
request.Attachments.Add(attachment);
// Add custom variables
request.CustomVariables.Add("var_key_1", "var_value_1");
// Alternatively, you can use indexer
request.CustomVariables["var_key_2"] = "var_value_2";
// Add custom headers
request.Headers.Add("X-Custom-Header-1", "Custom Value 1");
return request;
}
/// <summary>
/// Everything in one place, using fluent style.
/// </summary>
private static SendEmailRequest FluentStyleKitchenSink()
{
var request = SendEmailRequest.Create();
// Sender (Display name is optional)
request.From("john.doe@demomailtrap.com", "John Doe");
// Reply To
request.ReplyTo("info@domain.com");
// You can use simple email as recipient
request.To("hero.bill@galaxy.net");
// Add additional recipients by subsequent calls (Display name is optional)
request.To("steel.rat@galaxy.net", "James");
// Alternatively, existing EmailAddress instance can be used.
var vipEmail = new EmailAddress("star.lord@galaxy.net");
request.Cc(vipEmail);
// Alternatively, you could pass a collection at once
request.Bcc(
new EmailAddress("first@domain.com"),
new EmailAddress("second@domain.com"));
// Subject
request.Subject("Invitation to Earth");
// HTML body.
// At least one of Text or Html body must be specified.
request.Html(
"<h2>Greetings, Bill!</h2>" +
"<p>It will be a great pleasure to see you on our blue planet next weekend.</p>" +
"<p>Regards,<br/>" +
"John</p>");
// Plain text body.
// Will be used in case HTML body is missing or is not supported by the recipient.
request.Text("Dear Bill,\n\nIt will be a great pleasure to see you on our blue planet next weekend.\n\nBest regards, John.");
// Categorize
request.Category("Invitation");
// Add an attachment
var filePath = @"C:\files\preview.pdf";
var fileName = "preview.pdf";
var bytes = File.ReadAllBytes(filePath);
var fileContent = Convert.ToBase64String(bytes);
request.Attach(
content: fileContent,
fileName: fileName,
disposition: DispositionType.Attachment,
mimeType: MediaTypeNames.Application.Pdf,
contentId: "attachment_1");
// Add custom variables
request.CustomVariable("var_key", "var_value");
// Adding few at once also supported
request.CustomVariable(
new("var_key_1", "var_value_1"),
new("var_key_2", "var_value_2"),
new("var_key_3", "var_value_3"));
// Add custom headers
request.Header("X-Custom-Header", "Custom Value");
request.Header(
new("X-Custom-Header-1", "Custom Value 1"),
new("X-Custom-Header-2", "Custom Value 2"),
new("X-Custom-Header-3", "Custom Value 3"));
return request;
}
}