This repository has been archived by the owner on Jul 31, 2019. It is now read-only.
/
EmailSnippets.cs
566 lines (458 loc) · 20 KB
/
EmailSnippets.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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Office365.Discovery;
using Microsoft.Office365.OutlookServices;
using Microsoft.Office365.OutlookServices.Extensions;
//Snippets in this file:
//
//GetOutlookClientAsync
//GetInboxMessagesAsync
//GetMessagesAsync
//GetMessagesAsync(string subject, DateTimeOffset after)
//SendMessageAsync
//CreateDraftAsync
//CreateDraftAndSendAsync
//UpdateMessageAsync
//ReplyMessageAsync
//ReplyAllAsync
//ForwardMessageAsync
//MoveMessageAsync
//CopyMessageAsync
//DeleteMessageAsync
//GetMailFoldersAsync
//CreateMailFolderAsync
//UpdateMailFolderAsync
//MoveMailFolderAsync
//CopyMailFolderAsync
//DeleteMailFolderAsync
namespace O365_Win_Snippets
{
class EmailSnippets
{
private static OutlookServicesClient _outlookClient = null;
/// <summary>
/// Checks that an OutlookServicesClient object is available.
/// </summary>
/// <returns>The OutlookServicesClient object. </returns>
public static async Task<OutlookServicesClient> GetOutlookClientAsync()
{
if (_outlookClient != null && !String.IsNullOrEmpty(AuthenticationHelper.LastAuthority))
{
Debug.WriteLine("Got an Outlook client for Mail.");
return _outlookClient;
}
else
{
try
{
//First, look for the authority used during the last authentication.
//If that value is not populated, use CommonAuthority.
string authority = null;
if (String.IsNullOrEmpty(AuthenticationHelper.LastAuthority))
{
authority = AuthenticationHelper.CommonAuthority;
}
else
{
authority = AuthenticationHelper.LastAuthority;
}
// Create an AuthenticationContext using this authority.
AuthenticationHelper._authenticationContext = new AuthenticationContext(authority);
// Set the value of _authenticationContext.UseCorporateNetwork to true so that you
// can use this app inside a corporate intranet. If the value of UseCorporateNetwork
// is true, you also need to add the Enterprise Authentication, Private Networks, and
// Shared User Certificates capabilities in the Package.appxmanifest file.
AuthenticationHelper._authenticationContext.UseCorporateNetwork = true;
//See the Discovery Service Sample (https://github.com/OfficeDev/Office365-Discovery-Service-Sample)
//for an approach that improves performance by storing the discovery service information in a cache.
DiscoveryClient discoveryClient = new DiscoveryClient(
async () => await AuthenticationHelper.GetTokenHelperAsync(AuthenticationHelper._authenticationContext, AuthenticationHelper.DiscoveryResourceId));
// Get the specified capability ("Calendar").
CapabilityDiscoveryResult result =
await discoveryClient.DiscoverCapabilityAsync("Mail");
var token = await AuthenticationHelper.GetTokenHelperAsync(AuthenticationHelper._authenticationContext, result.ServiceResourceId);
// Check the token
if (String.IsNullOrEmpty(token))
{
// User cancelled sign-in
return null;
}
else
{
_outlookClient = new OutlookServicesClient(
result.ServiceEndpointUri,
async () => await AuthenticationHelper.GetTokenHelperAsync(AuthenticationHelper._authenticationContext, result.ServiceResourceId));
Debug.WriteLine("Got an Outlook client for Mail.");
return _outlookClient;
}
}
// The following is a list of exceptions you should consider handling in your app.
// In the case of this sample, the exceptions are handled by returning null upstream.
catch (DiscoveryFailedException dfe)
{
Debug.WriteLine(dfe.Message);
}
catch (ArgumentException ae)
{
Debug.WriteLine(ae.Message);
}
AuthenticationHelper._authenticationContext.TokenCache.Clear();
return null;
}
}
public static async Task<List<IMessage>> GetInboxMessagesAsync()
{
try
{
// Make sure we have a reference to the Exchange client
OutlookServicesClient outlookClient = await GetOutlookClientAsync();
//Get messages from a specific folder. Using Inbox this time because it is most likely to be populated.
var results = await outlookClient.Me.Folders.GetById("Inbox").Messages.ExecuteAsync();
if (results.CurrentPage.Count > 0)
{
Debug.WriteLine("First message from Inbox folder:" + results.CurrentPage[0].Id);
}
return results.CurrentPage.ToList();
}
catch { return null; }
}
public static async Task<List<IMessage>> GetMessagesAsync()
{
try
{
// Make sure we have a reference to the Exchange client
var outlookClient = await GetOutlookClientAsync();
//Get messages (from Inbox by default)
var results = await outlookClient.Me.Messages.ExecuteAsync();
if (results.CurrentPage.Count > 0)
{
Debug.WriteLine("First message from Inbox folder:" + results.CurrentPage[0].Id);
}
return results.CurrentPage.ToList();
}
catch { return null; }
}
public static async Task<IMessage> GetMessagesAsync(string subject, DateTimeOffset after)
{
try
{
// Make sure we have a reference to the Exchange client
var outlookClient = await GetOutlookClientAsync();
//Get messages (from Inbox by default).
// Note: This query is not guaranteed to return 0 or 1 message, so
// I need to use ExecuteAsync. Otherwise, ExecuteSingleAsync will throw
// InvalidOperationException.
var result = await outlookClient.Me.Messages
.Where(m => m.Subject == subject && m.DateTimeReceived > after)
.ExecuteAsync();
return (result.CurrentPage.Count > 0) ? result.CurrentPage[0] : null;
}
catch { return null; }
}
public static async Task<bool> SendMessageAsync(
string Subject,
string Body,
string RecipientAddress
)
{
try
{
// Make sure we have a reference to the Outlook Services client
var outlookClient = await GetOutlookClientAsync();
//Create Body
ItemBody body = new ItemBody
{
Content = Body,
ContentType = BodyType.HTML
};
List<Recipient> toRecipients = new List<Recipient>();
toRecipients.Add(new Recipient
{
EmailAddress = new EmailAddress
{
Address = RecipientAddress
}
});
Message newMessage = new Message
{
Subject = Subject,
Body = body,
ToRecipients = toRecipients
};
// To send a message without saving to Sent Items, specify false for
// the SavetoSentItems parameter.
await outlookClient.Me.SendMailAsync(newMessage, true);
Debug.WriteLine("Sent mail: " + newMessage.Id);
return true;
}
catch { return false; }
}
public static async Task<string> CreateDraftAsync(
string Subject,
string Body,
string RecipientAddress)
{
try
{
// Make sure we have a reference to the Outlook Services client
OutlookServicesClient outlookClient = await GetOutlookClientAsync();
ItemBody body = new ItemBody
{
Content = Body,
ContentType = BodyType.HTML
};
List<Recipient> toRecipients = new List<Recipient>();
toRecipients.Add(new Recipient
{
EmailAddress = new EmailAddress
{
Address = RecipientAddress
}
});
Message draftMessage = new Message
{
Subject = Subject,
Body = body,
ToRecipients = toRecipients,
Importance = Importance.High
};
// Save the draft message. Saving to Me.Messages saves the message in the Drafts folder.
await outlookClient.Me.Messages.AddMessageAsync(draftMessage);
Debug.WriteLine("Created draft: " + draftMessage.Id);
return draftMessage.Id;
}
catch { return null; }
}
public static async Task<string> CreateDraftAndSendAsync(
string Subject,
string Body,
string RecipientAddress)
{
try
{
// Make sure we have a reference to the Outlook Services client
OutlookServicesClient outlookClient = await GetOutlookClientAsync();
ItemBody body = new ItemBody
{
Content = Body,
ContentType = BodyType.HTML
};
List<Recipient> toRecipients = new List<Recipient>();
toRecipients.Add(new Recipient
{
EmailAddress = new EmailAddress
{
Address = RecipientAddress
}
});
Message draftMessage = new Message
{
Subject = Subject,
Body = body,
ToRecipients = toRecipients,
Importance = Importance.High
};
// Save the draft message. This ensures that we'll get a message Id to return.
await outlookClient.Me.Messages.AddMessageAsync(draftMessage);
//Send the message.
await outlookClient.Me.Messages[draftMessage.Id].SendAsync();
Debug.WriteLine("Created and sent draft: " + draftMessage.Id);
return draftMessage.Id;
}
catch { return null; }
}
public static async Task<bool> UpdateMessageAsync(string MessageId, string UpdatedContent)
{
try
{
// Make sure we have a reference to the Outlook Services client
OutlookServicesClient outlookClient = await GetOutlookClientAsync();
// Get the message to update and set changed properties
IMessage message = await outlookClient.Me.Messages[MessageId].ExecuteAsync();
message.Body = new ItemBody
{
Content = UpdatedContent,
ContentType = BodyType.HTML
};
await message.UpdateAsync();
Debug.WriteLine("Updated message: " + message.Id);
return true;
}
catch { return false; }
}
public static async Task<bool> ReplyMessageAsync(string MessageId, string ReplyContent)
{
try
{
// Make sure we have a reference to the Outlook Services client
OutlookServicesClient outlookClient = await GetOutlookClientAsync();
IMessage message = await outlookClient.Me.Messages[MessageId].ExecuteAsync();
await message.ReplyAsync(ReplyContent);
Debug.WriteLine("Replied to message: " + message.Id);
return true;
}
catch { return false; }
}
public static async Task<bool> ReplyAllAsync(string MessageId, string ReplyContent)
{
try
{
// Make sure we have a reference to the Outlook Services client
OutlookServicesClient outlookClient = await GetOutlookClientAsync();
IMessage message = await outlookClient.Me.Messages[MessageId].ExecuteAsync();
await message.ReplyAllAsync(ReplyContent);
Debug.WriteLine("Replied all to message: " + message.Id);
return true;
}
catch { return false; }
}
public static async Task<bool> ForwardMessageAsync(
string MessageId,
string ForwardMessage,
string RecipientAddress)
{
try
{
// Make sure we have a reference to the Outlook Services client
OutlookServicesClient outlookClient = await GetOutlookClientAsync();
List<Recipient> toRecipients = new List<Recipient>();
toRecipients.Add(new Recipient
{
EmailAddress = new EmailAddress
{
Address = RecipientAddress
}
});
await outlookClient.Me.Messages[MessageId].ForwardAsync(ForwardMessage, toRecipients);
Debug.WriteLine("Forwarded message: " + MessageId);
return true;
}
catch { return false; }
}
public static async Task<bool> MoveMessageAsync(string MessageId, string OriginalFolder, string ToFolder)
{
try
{
// Make sure we have a reference to the Outlook Services client
OutlookServicesClient outlookClient = await GetOutlookClientAsync();
IMessage messageToMove = await outlookClient.Me.Messages[MessageId].ExecuteAsync();
IMessage movedMessage = await messageToMove.MoveAsync(ToFolder);
Debug.WriteLine("Moved message: " + MessageId + " from " + OriginalFolder + " to " + ToFolder);
return true;
}
catch { return false; }
}
public static async Task<bool> CopyMessageAsync(string MessageId, string OriginalFolder, string ToFolder)
{
try
{
// Make sure we have a reference to the Outlook Services client
OutlookServicesClient outlookClient = await GetOutlookClientAsync();
IMessage messageToMove = await outlookClient.Me.Messages[MessageId].ExecuteAsync();
IMessage movedMessage = await messageToMove.CopyAsync(ToFolder);
Debug.WriteLine("Copied message: " + MessageId + " from " + OriginalFolder + " to " + ToFolder);
return true;
}
catch { return false; }
}
public static async Task<bool> DeleteMessageAsync(string MessageId)
{
try
{
// Make sure we have a reference to the Outlook Services client
OutlookServicesClient outlookClient = await GetOutlookClientAsync();
// Get the message to delete.
IMessage message = await outlookClient.Me.Messages[MessageId].ExecuteAsync();
await message.DeleteAsync();
Debug.WriteLine("Deleted message: " + MessageId)
;
return true;
}
catch { return false; }
}
//Mail Folders operations
public static async Task<IPagedCollection<IFolder>> GetMailFoldersAsync()
{
try
{
OutlookServicesClient outlookClient = await GetOutlookClientAsync();
IPagedCollection<IFolder> foldersResults = await outlookClient.Me.Folders.ExecuteAsync();
string folderId = foldersResults.CurrentPage[0].Id;
if (string.IsNullOrEmpty(folderId)) return null;
Debug.WriteLine("First mail folder in the collection: " + folderId);
return foldersResults;
}
catch { return null; }
}
public static async Task<string> CreateMailFolderAsync(string ParentFolder, string NewFolderName)
{
try
{
OutlookServicesClient outlookClient = await GetOutlookClientAsync();
Folder newFolder = new Folder
{
DisplayName = NewFolderName
};
await outlookClient.Me.Folders[ParentFolder].ChildFolders.AddFolderAsync(newFolder);
Debug.WriteLine("Created folder: " + newFolder.Id);
// Get the ID of the new folder.
return newFolder.Id;
}
catch { return null; }
}
public static async Task<bool> UpdateMailFolderAsync(string FolderId, string NewFolderName)
{
try
{
OutlookServicesClient outlookClient = await GetOutlookClientAsync();
IFolder folder = await outlookClient.Me.Folders[FolderId].ExecuteAsync();
folder.DisplayName = NewFolderName;
await folder.UpdateAsync();
string updatedName = folder.DisplayName;
Debug.WriteLine("Updated folder name: " + FolderId + " " + NewFolderName);
return true;
}
catch { return false; }
}
public static async Task<bool> MoveMailFolderAsync(string folderId, string ToFolderName)
{
try
{
OutlookServicesClient outlookClient = await GetOutlookClientAsync();
IFolder folderToMove = await outlookClient.Me.Folders[folderId].ExecuteAsync();
await folderToMove.MoveAsync(ToFolderName);
Debug.WriteLine("Moved folder: " + folderId + " to " + ToFolderName);
return true;
}
catch { return false; }
}
public static async Task<string> CopyMailFolderAsync(string folderId, string ToFolderName)
{
try
{
OutlookServicesClient outlookClient = await GetOutlookClientAsync();
IFolder folderToCopy = await outlookClient.Me.Folders[folderId].ExecuteAsync();
IFolder copiedFolder = await folderToCopy.CopyAsync(ToFolderName);
Debug.WriteLine("Copied folder: " + folderId + " to " + ToFolderName);
return copiedFolder.Id;
}
catch { return null; }
}
public static async Task<bool> DeleteMailFolderAsync(string folderId)
{
try
{
OutlookServicesClient outlookClient = await GetOutlookClientAsync();
IFolder folder = await outlookClient.Me.Folders[folderId].ExecuteAsync();
await folder.DeleteAsync();
Debug.WriteLine("Deleted folder: " + folderId);
return true;
}
catch { return false; }
}
}
}