Created
October 30, 2024 16:13
-
-
Save ScDor/8b54b18f436a6fcafd158bb2c7c59d1d to your computer and use it in GitHub Desktop.
This file contains hidden or 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 searchAndReadPDFs() { | |
var threads = GmailApp.search("from:[email protected] has:attachment filename:pdf"); | |
for (var thread of threads){ | |
Logger.log(thread.getId()); | |
var foundCodes = []; // TODO use Set | |
for (var message of thread.getMessages()){ | |
for (var attachment of message.getAttachments()) { | |
Logger.log(message.getSubject()); | |
Logger.log(message.getDate()); | |
Logger.log(attachment.getName()); | |
var raw_content = getRawPDFContent(message.getId(), (attachment.getName())); | |
var b64 = Utilities.base64Decode(raw_content); | |
var string_content = b64.getDataAsString(); | |
Logger.log(string_content); | |
while ((match = /CODE:(s*(\S+)\s*)/gi.exec(string_content)) !== null) { | |
foundCodes.push(match[1]); | |
} | |
if (foundCodes.length > 0) { | |
Logger.log("Found " + foundCodes.length + " code(s):"); | |
foundCodes.forEach(function(code, index) { | |
Logger.log("Code " + (index + 1) + ": " + code); | |
}); | |
} else { | |
Logger.log("No codes found in " + attachment.getName()); | |
} | |
} | |
} | |
} | |
} | |
function getRawPDFContent(messageId, attachmentName) { | |
var rawContent = Gmail.Users.Messages.get('me', messageId, {format: 'raw'}).raw; | |
// Find the attachment in the raw content | |
var attachmentIndex = rawContent.indexOf('Content-Disposition: attachment; filename="' + attachmentName + '"'); | |
if (attachmentIndex === -1) return null; | |
var contentTypeIndex = rawContent.indexOf('Content-Type: application/pdf', attachmentIndex); | |
if (contentTypeIndex === -1) return null; | |
var contentStart = rawContent.indexOf('\r\n\r\n', contentTypeIndex) + 4; | |
var contentEnd = rawContent.indexOf('--', contentStart); | |
return rawContent.substring(contentStart, contentEnd); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment