This repository has been archived by the owner on May 4, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
EmailSnippets.java
547 lines (491 loc) · 19.5 KB
/
EmailSnippets.java
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
/*
* Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the bottom of this file.
*/
package com.microsoft.office365.snippetapp.Snippets;
import com.microsoft.office365.snippetapp.AndroidSnippetsApplication;
import com.microsoft.outlookservices.Attachment;
import com.microsoft.outlookservices.BodyType;
import com.microsoft.outlookservices.EmailAddress;
import com.microsoft.outlookservices.FileAttachment;
import com.microsoft.outlookservices.Folder;
import com.microsoft.outlookservices.Item;
import com.microsoft.outlookservices.ItemAttachment;
import com.microsoft.outlookservices.ItemBody;
import com.microsoft.outlookservices.Message;
import com.microsoft.outlookservices.Recipient;
import com.microsoft.outlookservices.odata.OutlookClient;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
public class EmailSnippets {
public static final String MICROSOFT_OUTLOOK_SERVICES_ITEM_ATTACHMENT = "#Microsoft.OutlookServices.ItemAttachment";
OutlookClient mOutlookClient;
public EmailSnippets(OutlookClient mailClient) {
mOutlookClient = mailClient;
}
/**
* Gets a list of the 10 most recent email messages in the
* user Inbox, sorted by date and time received.
*
* @return List of type com.microsoft.outlookservices.Message
*/
public List<Message> getMailMessages()
throws ExecutionException, InterruptedException {
List<Message> messages = mOutlookClient
.getMe()
.getFolders()
.getById("Inbox")
.getMessages()
.select("Subject")
.orderBy("DateTimeReceived desc")
.top(10)
.read()
.get();
return messages;
}
/**
* Gets an email message by the id of the desired message
*
* @return com.microsoft.outlookservices.Message
*/
public Message getMailMessageById(String mailId)
throws ExecutionException, InterruptedException {
return mOutlookClient
.getMe()
.getMessages()
.select("ID")
.getById(mailId)
.read()
.get();
}
/**
* Gets a list of all recent email messages in the
* user Inbox whose subject matches, sorted by date and time received
*
* @param subjectLine The subject of the email to be matched
* @return List of String. The mail Ids of the matching messages
* @see 'https://msdn.microsoft.com/en-us/office/office365/api/complex-types-for-mail-contacts-calendar'
*/
public List<String> getInboxMessagesBySubject(String subjectLine)
throws ExecutionException, InterruptedException {
List<Message> inboxMessages = mOutlookClient
.getMe()
.getFolders()
.getById("Inbox")
.getMessages()
.filter("Subject eq '" + subjectLine.trim() + "'")
.read()
.get();
ArrayList<String> mailIds = new ArrayList<>();
for (Message message : inboxMessages) {
mailIds.add(message.getId());
}
return mailIds;
}
/**
* Gets a list of all recent email messages in the
* named mail folder whose subject matches, sorted by date and time received
*
* @param subjectLine The subject of the email to be matched
* @param folderName The display name of the mail folder
* @return List of String. The mail Ids of the matching messages
* @see 'https://msdn.microsoft.com/en-us/office/office365/api/complex-types-for-mail-contacts-calendar'
*/
public List<Message> getMailboxMessagesByFolderNameSubject(
String subjectLine
, String folderName) throws ExecutionException, InterruptedException {
List<Folder> sentFolder = mOutlookClient.getMe()
.getFolders()
.select("ID")
.filter("DisplayName eq '" + folderName + "'")
.read()
.get();
return mOutlookClient
.getMe()
.getFolder(sentFolder.get(0).getId())
.getMessages()
.select("ID")
.filter("Subject eq '" + subjectLine.trim() + "'")
.read()
.get();
}
/**
* Gets a list of all recent email messages in the
* user Inbox whose subject matches subjectLine and sent date&time are greater than the
* sentDate parameter. Results are sorted by date and time received
*
* @param subjectLine The subject of the email to be matched
* @param sentDate The UTC (Zulu) time that the mail was sent.
* @return List of String. The mail Ids of the matching messages
* @see 'https://msdn.microsoft.com/en-us/office/office365/api/complex-types-for-mail-contacts-calendar'
*/
public List<String> getInboxMessagesBySubject_DateTimeReceived(
String subjectLine,
Date sentDate,
String mailFolder) throws ExecutionException, InterruptedException {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
String filterString = "DateTimeReceived ge "
+ formatter.format(sentDate.getTime())
+ " and "
+ "Subject eq '"
+ subjectLine.trim() + "'";
List<Message> inboxMessages = mOutlookClient
.getMe()
.getFolders()
.getById(mailFolder)
.getMessages()
.select("ID")
.filter(filterString)
.read()
.get();
ArrayList<String> mailIds = new ArrayList<>();
for (Message message : inboxMessages) {
if (message.getSubject().equals(subjectLine.trim()))
mailIds.add(message.getId());
}
return mailIds;
}
/**
* Gets a list of all recent email messages in the
* user Inbox whose subject matches, sorted by date and time received
*
* @param textContent The content of the file to be attached
* @param fileName The name of the file to be attached
* @return com.microsoft.outlookservices.FileAttachment. The Attachment object
*/
private FileAttachment getTextFileAttachment(String textContent, String fileName) {
FileAttachment fileAttachment = new FileAttachment();
fileAttachment.setContentBytes(textContent.getBytes());
fileAttachment.setName(fileName);
fileAttachment.setSize(textContent.getBytes().length);
return fileAttachment;
}
/**
* Gets a message out of the user's draft folder by id and adds a text file attachment
*
* @param mailId The id of the draft email that will get the attachment
* @param fileContents The contents of the text file to be attached
* @param fileName The name of the file to be attached
* @return Boolean. The result of the operation. True if success
*/
public Attachment addTextFileAttachmentToMessage(
String mailId,
String fileContents,
String fileName,
boolean isInline) throws ExecutionException, InterruptedException {
FileAttachment attachment = getTextFileAttachment(fileContents, fileName);
attachment.setIsInline(isInline);
mOutlookClient
.getMe()
.getMessages()
.getById(mailId)
.getAttachments()
.add(attachment)
.get();
return attachment;
}
/**
* Gets a message out of the user's draft folder by id and adds a text file attachment
*
* @param mailId The id of the draft email that will get the attachment
* @param itemToAttach The mail message to attach
* @return Boolean. The result of the operation. True if success
*/
public Boolean addItemAttachment(
String mailId,
Item itemToAttach,
boolean isInline) throws ExecutionException, InterruptedException {
ItemAttachment itemAttachment = new ItemAttachment();
itemAttachment.setName(itemToAttach.getClass().getName());
itemAttachment.setItem(itemToAttach);
itemAttachment.setContentType(MICROSOFT_OUTLOOK_SERVICES_ITEM_ATTACHMENT);
itemAttachment.setIsInline(false);
itemAttachment.setId(itemToAttach.getId());
itemAttachment.setIsInline(isInline);
mOutlookClient
.getMe()
.getMessages()
.getById(mailId)
.getAttachments()
.add(itemAttachment)
.get();
return true;
}
/**
* Gets a list of Attachment objects representing the contents of a set of email attachments
*
* @param mailID The email id of the message whose attachments are wanted
* @return List. A list of Byte array objects
*/
public List<Attachment> getAttachmentsFromEmailMessage(String mailID)
throws ExecutionException, InterruptedException {
return mOutlookClient
.getMe()
.getMessages()
.getById(mailID)
.getAttachments()
.read()
.get();
}
/**
* Deletes all attachments from a message attachment collection and update
* the message in the Drafts folder
*
* @param mailId The id of the message to update
* @return boolean. Success flag. True if attachments are deleted
*/
public void removeEmailAttachments(String mailId)
throws ExecutionException, InterruptedException {
List<Attachment> attachments = getAttachmentsFromEmailMessage(
mailId);
//Delete all attachments from current message
for (Attachment attachment : attachments) {
attachments.remove(attachment);
mOutlookClient
.getMe()
.getMessages()
.getById(mailId)
.getAttachments()
.getById(attachment.getId())
.delete()
.get();
}
}
/**
* Gets a message out of the user's draft folder by id and adds a text file attachment
*
* @param emailAddress The email address of the mail recipient
* @param subject The subject of the email
* @param body The body of the email
* @return String. The id of the email added to the draft folder
*/
public String addDraftMail(
final String emailAddress,
final String subject,
final String body) throws ExecutionException, InterruptedException {
// Prepare the message.
List<Recipient> recipientList = new ArrayList<>();
Recipient recipient = new Recipient();
EmailAddress email = new EmailAddress();
email.setAddress(emailAddress);
recipient.setEmailAddress(email);
recipientList.add(recipient);
Message messageToSend = new Message();
messageToSend.setToRecipients(recipientList);
ItemBody bodyItem = new ItemBody();
bodyItem.setContentType(BodyType.HTML);
bodyItem.setContent(body);
messageToSend.setBody(bodyItem);
messageToSend.setSubject(subject);
// Contact the Office 365 service and try to add the message to
// the draft folder.
Message draft = mOutlookClient
.getMe()
.getMessages()
.add(messageToSend)
.get();
return draft.getId();
}
/**
* Sends the Exchange server copy of a new mail message
*
* @param mailId The email to be sent from the draft folder
* @return Boolean. The result of the operation
*/
public Boolean sendMail(String mailId) throws ExecutionException, InterruptedException {
mOutlookClient
.getMe()
.getMessages()
.getById(mailId)
.getOperations()
.send();
return true;
}
/**
* Creates and sends an email
*
* @param emailAddress The email address of the mail recipient
* @param subject The subject of the email
* @param body The body of the email
* @return String. The id of the sent email
*/
public String createAndSendMail(
final String emailAddress,
final String subject,
final String body) throws ExecutionException, InterruptedException {
// Prepare the message.
List<Recipient> recipientList = new ArrayList<>();
Recipient recipient = new Recipient();
EmailAddress email = new EmailAddress();
email.setAddress(emailAddress);
recipient.setEmailAddress(email);
recipientList.add(recipient);
Message messageToSend = new Message();
messageToSend.setToRecipients(recipientList);
ItemBody bodyItem = new ItemBody();
bodyItem.setContentType(BodyType.HTML);
bodyItem.setContent(body);
messageToSend.setBody(bodyItem);
messageToSend.setSubject(subject);
// Contact the Office 365 service and try to deliver the message.
Message draft = mOutlookClient
.getMe()
.getMessages()
.select("ID")
.add(messageToSend)
.get();
mOutlookClient.getMe()
.getOperations()
.sendMail(draft, false)
.get();
return draft.getId();
}
/**
* Forwards a message out of the user's Inbox folder by id
*
* @param emailId The id of the mail to be forwarded
* @param recipientEmailAddress The email address string of the recipient
* @return String. The id of the sent email
*/
public String forwardDraftMail(String emailId, String recipientEmailAddress) throws ExecutionException, InterruptedException {
Message forwardMessage = mOutlookClient
.getMe()
.getMessages()
.getById(emailId)
.getOperations()
.createForward()
.get();
//Get the new draft email to forward to the specified email recipient
Message draftMessage = getDraftMessageMap()
.get(forwardMessage.getConversationId());
//Set the recipient list for the draft message
draftMessage.setToRecipients(createEmailRecipientList(recipientEmailAddress));
mOutlookClient
.getMe()
.getOperations()
.sendMail(draftMessage, false)
.get();
return draftMessage.getId();
}
/**
* Deletes a message out of the user's Sent folder by id
*
* @param emailID The id of the mail to be deleted
* @return Boolean. The result of the operation
*/
public void deleteMail(String emailID) throws ExecutionException, InterruptedException {
mOutlookClient
.getMe()
.getMessages()
.getById(emailID)
.delete()
.get();
}
/**
* Generates a hash table whose key is a mail conversation Id and value is corresponding
* mail message
*
* @return Map of type String, Message. The result of the operation
*/
public Map<String, Message> getDraftMessageMap()
throws ExecutionException, InterruptedException {
Map<String, Message> draftMessageMap = new HashMap<>();
for (Message draftMessage : getDraftMessages()) {
draftMessageMap.put(draftMessage.getConversationId(), draftMessage);
}
return draftMessageMap;
}
/**
* Gets a List of type Message representing the contents of
* the user's email drafts folder
*
* @return List. The result of the operation
*/
public List<Message> getDraftMessages() throws ExecutionException, InterruptedException {
return mOutlookClient
.getMe()
.getFolder("Drafts")
.getMessages()
.select("ID,Subject,ConversationID")
.read()
.get();
}
/**
* Forwards a message out of the user's Inbox folder by id
*
* @param emailId The id of the mail to be forwarded
* @param messageBody The body of the message as a string
* @return String. The id of the sent email
*/
public String replyToEmailMessage(String emailId, String messageBody)
throws ExecutionException, InterruptedException {
//Create a new message in the user draft items folder
Message replyEmail = mOutlookClient
.getMe()
.getFolder("Drafts")
.getMessages()
.getById(emailId)
.getOperations()
.createReply()
.get();
if (replyEmail != null) {
//Create a message subject body and set in the reply message
ItemBody bodyItem = new ItemBody();
bodyItem.setContentType(BodyType.HTML);
bodyItem.setContent(messageBody);
replyEmail.setBody(bodyItem);
// Send the email reply
mOutlookClient
.getMe()
.getOperations()
.sendMail(replyEmail, false)
.get();
return replyEmail.getId();
} else {
return "";
}
}
private ArrayList<Recipient> createEmailRecipientList(String emailAddress){
//Create an EmailAddress from string method argument
EmailAddress recipientAddress = new EmailAddress();
recipientAddress.setAddress(emailAddress);
//Create a recipient and populate with an email address
Recipient recipient = new Recipient();
recipient.setEmailAddress(recipientAddress);
ArrayList<Recipient> recipients = new ArrayList<Recipient>();
recipients.add(recipient);
return recipients;
}
}
// *********************************************************
//
// O365-Android-Snippets, https://github.com/OfficeDev/O365-Android-Snippets
//
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// MIT License:
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// *********************************************************