-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathexportGmailMessage
More file actions
56 lines (46 loc) · 2.48 KB
/
exportGmailMessage
File metadata and controls
56 lines (46 loc) · 2.48 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
/**
* Exports a Gmail message as PDF (and optionally attachments)
* @param {int} recordNum Internal tracking number (to group messages and attachments together)
* @param {String} messageID GmailMessage id
* @param {String} userAccount Email address of person exporting
* @param {String} userAccountName Full name of person exporting
* @param {boolean} [includeAttachments=true] Whether to also save attachments (in original format)
* @param {Folder} [targetFolder] Folder to save PDF and attachments to. By default root folder ('My Drive')
* @return {File[]} resultArray Files generated
*
* Files will be created in targetFolder
* <recordNum>-0 <date>.pdf - GmailMessage body & headers
* <recordNum>-N <filename>.<ext> - attachments
*
*/
function exportGmailMessage(recordNum,messageID,userAccount,userAccountName,includeAttachments,targetFolder){
targetFolder = targetFolder || DriveApp.getRootFolder(); // targetFolder should be required, but putting this here until I figure out a better error response
includeAttachments = includeAttachments || true;
var resultArray = [];
var htmlT = HtmlService.createTemplateFromFile("ToFile_GmailPrintTemplate");
htmlT.gmailAccount = userAccount;
htmlT.gmailAccountName = userAccountName;
var originalMessageObject = GmailApp.getMessageById(messageID);
var preppedMessageObject = prepMessageObject(originalMessageObject);
/* prepMessageObject() basically does a few things the Gmail WebUI does intuitively - subject is (no subject) and in-line images are in body of message instead of an attachment */
htmlT.retrievedMessageObject = preppedMessageObject;
if(includeAttachments){
var atts = preppedMessageObject.cleanAttachments;
for(var i=0;i<atts.length;i++){
var result = DriveApp.createFile(atts[i]);
targetFolder.addFile(result);
resultArray.push(result);
var originalName = result.getName();
result.setName(recordNum + "-" + (i+1) + " - " + originalName);
result.setDescription("Exported from Gmail, user " + userAccountName + "(" + userAccount + ")");
}
}
var htmlFile = htmlT.evaluate().getAs("text/html");
var rf = htmlFile.getAs("application/pdf");
var result = DriveApp.createFile(rf);
targetFolder.addFile(result);
resultArray.push(result);
result.setName(recordNum + "-0 - " + preppedMessageObject.messageObject.getDate() + ".pdf");
result.setDescription("Exported from Gmail, user " + userAccountName + "(" + userAccount + ")");
return resultArray;
}