Last active
August 29, 2015 14:02
-
-
Save 65/89d676353b2cdee16be8 to your computer and use it in GitHub Desktop.
Gmail Script - email to pdf to xero
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function send_Gmail_as_PDF() { | |
var gLabel = "#Receipt"; | |
var thread = GmailApp.search("label:" + gLabel); | |
for (var x = 0; x < thread.length; x++) {//for all emails | |
var messages = thread[x].getMessages(); | |
for (var y = 0; y < 1; y++) {// only do on the first email, use messages.length otherwise | |
var attach = messages[y].getAttachments(); | |
var body = messages[y].getBody(); | |
var rBody = 'See attachment : ' + messages[y].getSubject() + '<br/>Date : ' + messages[y].getDate() + '<br/>From :' + messages[y].getFrom(); | |
var rSubject = 'Invoice sent to Xero : ' + messages[y].getSubject() + ' ' + messages[y].getDate(); | |
// Create an HTML File from the Message Body | |
var bodydochtml = DocsList.createFile('body.html', body, "text/html") | |
var bodyId = bodydochtml.getId() | |
// Convert the HTML to PDF | |
var bodydocpdf = bodydochtml.getAs('application/pdf').getBytes(); | |
var body_to_send = { | |
fileName: messages[y].getSubject() + ' ' + messages[y].getDate(), | |
content: bodydocpdf, | |
mimeType: 'application/pdf' | |
}; | |
var attachmentList = []; | |
attachmentList.push(body_to_send); | |
// Trash the temporary file | |
bodydochtml.setTrashed(true); | |
// Process all attachments | |
for (var att = 0; att < attach.length; att++) { | |
var file = DocsList.createFile(attach[att]); | |
var pdf = file.getAs('application/pdf').getBytes(); | |
var attach_to_send = { | |
fileName: 'pdftest.pdf', | |
content: pdf, | |
mimeType: 'application/pdf' | |
}; | |
attachmentList.push(attach_to_send); | |
// Trash the temporary file | |
file.setTrashed(true); | |
} | |
messages[y].markRead(); | |
} | |
// Send the PDF to any email address | |
// | |
MailApp.sendEmail('[YOUR UNIQUE EMAIL]@xerofiles.com', | |
rSubject, | |
rBody, { | |
attachments: attachmentList | |
}); | |
// Message Processed; Remove the GMail Label | |
GmailApp.getUserLabelByName(gLabel) | |
.removeFromThread(thread[x]); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
MailApp.sendEmail('[YOUR UNIQUE EMAIL]@xerofiles.com', |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment