/
Operations.cs
529 lines (459 loc) · 20.5 KB
/
Operations.cs
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
using SmtpMailConfiguration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Net.Mail;
using System.Runtime.CompilerServices;
using System.Threading;
using LoggingLibrary;
using MailLibrary.BaseClasses;
using MailLibrary.Extensions;
namespace MailLibrary
{
public class Operations
{
private bool _writeToLog;
private FileInfo _LogInfo;
/// <summary>
/// Init class for deciding to log or not.
/// </summary>
/// <param name="pUseLogging">True to log, false not to log to file</param>
/// <param name="pFileName">Log file name</param>
public Operations(bool pUseLogging = false, string pFileName = "")
{
if (pUseLogging && !string.IsNullOrWhiteSpace(pFileName))
{
_writeToLog = true;
_LogInfo = new FileInfo(pFileName);
}
}
//
/// <summary>
/// Uses settings from unit test app.config to configuring/setting up
/// the MailConfiguration, MailMessage (from address) and properties
/// for SmtpClient object. subject and message are static.
///
/// Message properties
/// - Subject adds the caller name e.g. the test method calling this method.
/// - Plain and HTML message comes from SQL-Server table
/// </summary>
/// <param name="pConfig">appropriate <see cref="MailConfiguration"/> item</param>
/// <param name="pSendToo">Valid email address to send message too</param>
/// <param name="identifier">SQL-Server table key</param>
/// <param name="name">Represents who called this method</param>
public void ExampleSend1(string pConfig, string pSendToo, int identifier, [CallerMemberName]string name = "")
{
var ops = new DataOperations();
var data = ops.Read(identifier);
var mc = new MailConfiguration(pConfig);
var mail = new MailMessage
{
From = new MailAddress(mc.FromAddress),
Subject = $"Sent from test: '{name}'"
};
mail.To.Add(pSendToo);
mail.IsBodyHtml = true;
mail.AlternateViews.PlainTextView(data.TextMessage);
mail.AlternateViews.HTmlView(data.HtmlMessage);
using (var smtp = new SmtpClient(mc.Host, mc.Port))
{
smtp.Credentials = new NetworkCredential(mc.UserName, mc.Password);
smtp.EnableSsl = mc.EnableSsl;
smtp.Send(mail);
}
}
//
/// <summary>
/// Uses settings from unit test app.config to configuring/setting up
/// the MailConfiguration, MailMessage (from address) and properties
/// for SmtpClient object. subject and message are static.
///
/// Message properties
/// - Subject adds the caller name e.g. the test method calling this method.
/// - Plain and HTML message comes from SQL-Server table
/// </summary>
/// <param name="pConfig">appropriate <see cref="MailConfiguration"/> item</param>
/// <param name="pSendToo">Valid email address to send message too</param>
/// <param name="identifier">SQL-Server table key</param>
/// <param name="name">Represents who called this method</param>
public void ExampleSendWithRepyToList(string pConfig, string pSendToo, int identifier, [CallerMemberName]string name = "")
{
var ops = new DataOperations();
var data = ops.Read(identifier);
var mc = new MailConfiguration(pConfig);
var mail = new MailMessage
{
From = new MailAddress(mc.FromAddress),
Subject = $"Sent from test: '{name}'"
};
mail.To.Add(pSendToo);
/*
* Using non-existing addresses for testing purposes
*/
mail.ReplyToList.Add(new MailAddress("jane@gmail.com"));
mail.ReplyToList.Add(new MailAddress("kevin@comcast.net"));
mail.IsBodyHtml = true;
mail.AlternateViews.PlainTextView(data.TextMessage);
mail.AlternateViews.HTmlView(data.HtmlMessage);
using (var smtp = new SmtpClient(mc.Host, mc.Port))
{
smtp.Credentials = new NetworkCredential(mc.UserName, mc.Password);
smtp.EnableSsl = mc.EnableSsl;
smtp.Send(mail);
}
}
/// <summary>
/// Since MailAddress.To is a collection you can add many addresses for sending.
/// For testing this means you need multiple email addresses. It's easier in a
/// company were they can create multiple test addresses while for personal use
/// you need to create them and then be able to monitor them in testing.
/// </summary>
private void SendMultiples()
{
throw new NotImplementedException();
}
/// <summary>
/// Helper method to create a MailAddress with friendly name for FROM or TO address
/// </summary>
/// <param name="sender"></param>
/// <returns>MailAddress</returns>
/// <remarks>
/// Could be a in line function to if only used in one method for C# 7.
/// </remarks>
private MailAddress CreateFriendltAddress(MailFriendly sender) => new MailAddress(sender.Address, sender.Display);
/// <summary>
/// Example for showing friendly names in an email
/// </summary>
/// <param name="pConfig"></param>
/// <param name="identifier"></param>
/// <param name="pFromAddress"></param>
/// <param name="pToAddress"></param>
/// <param name="name">Method name as default with an empty string</param>
public void ExampleSendMaskNames(string pConfig, int identifier, MailFriendly pFromAddress, MailFriendly pToAddress, [CallerMemberName]string name = "")
{
var ops = new DataOperations();
var data = ops.Read(identifier);
var mc = new MailConfiguration(pConfig);
var mail = new MailMessage
{
From = CreateFriendltAddress(pFromAddress),
Subject = $"Sent from test: '{name}'"
};
mail.To.Add(CreateFriendltAddress(pToAddress));
var plainMessage = AlternateView.CreateAlternateViewFromString(
data.TextMessage,
null, "text/plain");
var htmlMessage = AlternateView.CreateAlternateViewFromString(
data.HtmlMessage,
null, "text/html");
mail.IsBodyHtml = true;
mail.AlternateViews.Add(plainMessage);
mail.AlternateViews.Add(htmlMessage);
using (var smtp = new SmtpClient(mc.Host, mc.Port))
{
smtp.Credentials = new NetworkCredential(mc.UserName, mc.Password);
smtp.EnableSsl = mc.EnableSsl;
smtp.Send(mail);
}
}
/// <summary>
/// Example for showing friendly names in an email
/// </summary>
/// <param name="pConfig"></param>
/// <param name="identifier"></param>
/// <param name="pFromAddress"></param>
/// <param name="pToAddress"></param>
/// <param name="userPickupFolder">Toggle between sending live or sending to file</param>
/// <param name="name">Method name as default with an empty string</param>
public void UsePickupFolderExample(string pConfig, int identifier, MailFriendly pFromAddress, MailFriendly pToAddress,bool userPickupFolder = true, [CallerMemberName]string name = "")
{
var ops = new DataOperations();
var data = ops.Read(identifier);
var mc = new MailConfiguration(pConfig);
var mail = new MailMessage
{
From = CreateFriendltAddress(pFromAddress),
Subject = $"Sent from test: '{name}'"
};
mail.To.Add(CreateFriendltAddress(pToAddress));
mail.IsBodyHtml = true;
mail.AlternateViews.PlainTextView(data.TextMessage);
mail.AlternateViews.HTmlView(data.HtmlMessage);
using (var smtp = new SmtpClient(mc.Host, mc.Port))
{
smtp.Credentials = new NetworkCredential(mc.UserName, mc.Password);
if (userPickupFolder)
{
smtp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
smtp.PickupDirectoryLocation = mc.PickupFolder;
}
smtp.EnableSsl = !userPickupFolder;
smtp.Send(mail);
}
}
/// <summary>
/// Example for incorrect port used to send a email message.
/// </summary>
/// <param name="pConfig">appropriate <see cref="MailConfiguration"/> item</param>
/// <param name="pSendToo">Valid email address to send message too</param>
/// <param name="identifier">SQL-Server table key</param>
/// <param name="name">Represents who called this method</param>
public void ExampleSend2(string pConfig, string pSendToo, int identifier, [CallerMemberName]string name = "")
{
var ops = new DataOperations();
var data = ops.Read(identifier);
var mc = new MailConfiguration(pConfig);
var mail = new MailMessage
{
From = new MailAddress(mc.FromAddress),
Subject = $"Sent from test: '{name}'"
};
mail.To.Add(pSendToo);
var plainMessage = AlternateView.CreateAlternateViewFromString(
data.TextMessage,
null,
"text/plain");
var htmlMessage = AlternateView.CreateAlternateViewFromString(
data.HtmlMessage,
null,
"text/html");
mail.IsBodyHtml = true;
mail.AlternateViews.Add(plainMessage);
mail.AlternateViews.Add(htmlMessage);
using (var smtp = new SmtpClient("Bad host", mc.Port))
{
smtp.Credentials = new NetworkCredential(mc.UserName, mc.Password);
smtp.EnableSsl = mc.EnableSsl;
smtp.SendCompleted += Smtp_SendCompleted;
try
{
smtp.Send(mail);
}
catch (Exception generalException)
{
switch (generalException)
{
case SmtpFailedRecipientsException _:
{
if (_writeToLog)
{
WriteToLogFile("SmtpFailedRecipientsException", generalException.GetExceptionMessages());
}
break;
}
case SmtpException _:
{
if (_writeToLog)
{
WriteToLogFile("General SmtpException", $"{generalException.GetExceptionMessages()}, Status code: {((SmtpException) generalException).StatusCode}");
}
break;
}
default:
if (_writeToLog)
{
Logger.Start(_LogInfo);
try
{
// ReSharper disable once PossibleInvalidCastException
WriteToLogFile("General Exception", $"{generalException.GetExceptionMessages()}, Status code: {((SmtpException)generalException).StatusCode}");
}
finally
{
Logger.ShutDown();
}
}
break;
}
}
}
}
/// <summary>
/// Send email with a callback, not no using statement is used as
/// doing so would circumvent the callback.
/// </summary>
/// <param name="pConfigurationSection"></param>
/// <param name="pSendToo"></param>
/// <returns></returns>
public async Task ExampleSend3Async(string pConfigurationSection, string pSendToo, [CallerMemberName]string name = "")
{
var ops = new DataOperations();
var data = ops.Read(5);
var mc = new MailConfiguration(pConfigurationSection);
var mail = new MailMessage
{
Subject = $"Called from: {name}",
From = new MailAddress(mc.FromAddress)
};
mail.To.Add(pSendToo);
mail.Priority = MailPriority.High;
mail.IsBodyHtml = true;
mail.AlternateViews.PlainTextView(data.TextMessage);
mail.AlternateViews.HTmlView(data.HtmlMessage);
//send the message
var smtp = new SmtpClient(mc.Host, mc.Port)
{
Credentials = new NetworkCredential(mc.UserName, mc.Password),
EnableSsl = mc.EnableSsl
};
smtp.SendCompleted += Smtp_SendCompleted;
smtp.SendCompleted += (s, e) => {
smtp.Dispose();
mail.Dispose();
};
// ReSharper disable once AsyncConverter.AsyncAwaitMayBeElidedHighlighting
await smtp.SendMailAsync(mail).ConfigureAwait(false);
}
#region For part 3 of this series - to be written shortly
/// <summary>
/// Example which sends all files in a specific folder
/// </summary>
/// <param name="pConfig">appropriate <see cref="MailConfiguration"/> item</param>
/// <param name="pSendToo">Valid email address to send message too</param>
/// <param name="identifier">SQL-Server table key</param>
/// <param name="name">Represents who called this method</param>
/// <remarks>
/// For a real application
/// - make sure the folder exists and there are files if this is a busness requirement.
/// </remarks>
public void SendMultipleAttachementsFromDisk(string pConfig, string pSendToo, int identifier, [CallerMemberName]string name = "")
{
var files = Directory.GetFiles(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"Files1"));
var ops = new DataOperations();
var data = ops.Read(identifier);
var mc = new MailConfiguration(pConfig);
var mail = new MailMessage
{
From = new MailAddress(mc.FromAddress),
Subject = $"Sent from test: '{name}'"
};
mail.To.Add(pSendToo);
mail.IsBodyHtml = true;
mail.AlternateViews.PlainTextView(data.TextMessage);
mail.AlternateViews.HTmlView(data.HtmlMessage);
foreach (var file in files)
{
mail.Attachments.Add(new Attachment(file));
}
using (var smtp = new SmtpClient(mc.Host, mc.Port))
{
smtp.Credentials = new NetworkCredential(mc.UserName, mc.Password);
smtp.EnableSsl = mc.EnableSsl;
smtp.Send(mail);
}
}
/// <summary>
/// Add attachments from a folder were each file in the folder is added without
/// any conditions.
/// </summary>
/// <param name="pConfig">appropriate <see cref="MailConfiguration"/> item</param>
/// <param name="pSendToo">Valid email address to send message too</param>
/// <param name="identifier">SQL-Server table key</param>
/// <param name="name">Represents who called this method</param>
public void SendMultipleAttachementsFromByeArray(string pConfig, string pSendToo, int identifier, [CallerMemberName]string name = "")
{
var files = Directory.GetFiles(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Files1"));
var ops = new DataOperations();
var data = ops.Read(identifier);
var mc = new MailConfiguration(pConfig);
var mail = new MailMessage
{
From = new MailAddress(mc.FromAddress),
Subject = $"Sent from test: '{name}'"
};
mail.To.Add(pSendToo);
mail.IsBodyHtml = true;
mail.AlternateViews.PlainTextView(data.TextMessage);
mail.AlternateViews.HTmlView(data.HtmlMessage);
mail.Attachments.AddFilesFromStream(files);
using (var smtp = new SmtpClient(mc.Host, mc.Port))
{
smtp.Credentials = new NetworkCredential(mc.UserName, mc.Password);
smtp.EnableSsl = mc.EnableSsl;
smtp.Send(mail);
}
}
/// <summary>
/// Embed an image into an email message. In this sample the image is setup
/// within this method but could have been passed in as a parameter.
/// </summary>
/// <param name="pConfig">appropriate <see cref="MailConfiguration"/> item</param>
/// <param name="pSendToo">Valid email address to send message too</param>
/// <param name="name">Represents who called this method</param>
public void EmbedImageFromDisk(string pConfig, string pSendToo, [CallerMemberName]string name = "")
{
var mc = new MailConfiguration(pConfig);
var mail = new MailMessage
{
From = new MailAddress(mc.FromAddress),
Subject = $"Sent from test: '{name}'"
};
var plainMessage = AlternateView.CreateAlternateViewFromString(
"This email desires html",
null, "text/plain");
/*
* This is the identifier for embeding an image into the email message.
* A variable is used because the identifier is needed into two areas,
* first in the AlternateView for HTML and secondly for the LinkedResource.
*/
var imageIdentifier = "Miata";
var htmlMessage = AlternateView.CreateAlternateViewFromString(
$"<p>This is what I'm purchasing in <b>2019</b> to go along with my 2016 model.</p><img src=cid:{imageIdentifier}><p>Karen</p>",
null, "text/html");
var fileName = $"{Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images1")}\\2017Miata.jpg";
var miataImage = new LinkedResource(fileName, "image/jpeg") {ContentId = imageIdentifier };
mail.AlternateViews.Add(plainMessage);
mail.AlternateViews.Add(htmlMessage);
htmlMessage.LinkedResources.Add(miataImage);
mail.To.Add(pSendToo);
mail.IsBodyHtml = true;
using (var smtp = new SmtpClient(mc.Host, mc.Port))
{
smtp.Credentials = new NetworkCredential(mc.UserName, mc.Password);
smtp.EnableSsl = mc.EnableSsl;
smtp.Send(mail);
}
}
#endregion
#region Logging
/// <summary>
/// Central code for writing to log file
/// </summary>
/// <param name="pTitle"></param>
/// <param name="pMessage"></param>
private void WriteToLogFile(string pTitle, string pMessage)
{
Logger.Start(_LogInfo);
try
{
var log = new Logger(pTitle);
log.Log("", pMessage);
}
finally
{
Logger.ShutDown();
}
}
#endregion
/// <summary>
/// Callback for sending an email
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Smtp_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
if (e.Cancelled == false && e.Error == null)
{
WriteToLogFile("Sent","Mail sent");
}
else
{
WriteToLogFile("Sent", "Mail not sent");
}
}
}
}