Created
July 15, 2020 18:32
-
-
Save mhavrlent/714f6ba19d65d180cf9c5909835af1c8 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
#!/usr/bin/env python | |
""" | |
mail2cert.py: | |
Extracts certificates from Outlook emails. | |
Uses only emails received today and with specific subject. | |
Certificate is saved to a file, where file name is the first FQDN found | |
in the email. | |
Can be easily modified to extract anything using given regex. | |
""" | |
from win32com.client import constants | |
from win32com.client.gencache import EnsureDispatch as Dispatch | |
import datetime as dt | |
import re | |
outlook = Dispatch("Outlook.Application") | |
mapi = outlook.GetNamespace("MAPI") | |
ACCOUNT = "[email protected]" | |
INBOX_FOLDER = "Inbox" | |
SUBJECT = "Certificate approved. Installation next steps." | |
CERT_EXTENSION = ".p7b" | |
FQDN_REGEX = "(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.){2,}([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9]){2,}" | |
CERT_REGEX = "-+BEGIN CERTIFICATE-+\s+(.*?)\s+-+END CERTIFICATE-+" | |
class Oli(): | |
def __init__(self, outlook_object): | |
self._obj = outlook_object | |
def items(self): | |
array_size = self._obj.Count | |
for item_index in range(1, array_size+1): | |
yield (item_index, self._obj[item_index]) | |
def prop(self): | |
return sorted(self._obj._prop_map_get_.keys()) | |
def main(): | |
for inx, folder in Oli(mapi.Folders).items(): | |
if (folder.Name == ACCOUNT): | |
for inx, subfolder in Oli(folder.Folders).items(): | |
#print("(%i)" % inx, subfolder.Name,"=> ", subfolder) | |
if subfolder.Name == INBOX_FOLDER: | |
messages = subfolder.Items | |
lastDayDateTime = dt.datetime.now() - dt.timedelta(days=1) | |
todaysMessages = messages.Restrict( | |
"[ReceivedTime] >= '" + lastDayDateTime.strftime('%m/%d/%Y %H:%M %p')+"'") | |
certMessages = todaysMessages.Restrict( | |
"[Subject] = '%s'" % SUBJECT) | |
print("Number of messages: %s" % len(certMessages)) | |
for message in certMessages: | |
subject = message.Subject | |
# print(subject) | |
body_content = message.Body | |
m = re.search(FQDN_REGEX, body_content) | |
fqdn = m.group(0) | |
print(fqdn) | |
m = re.search(CERT_REGEX, body_content, flags=re.DOTALL) | |
cert = m.group(0) | |
print(cert) | |
f = open(fqdn+CERT_EXTENSION, "w") | |
f.write(cert) | |
f.close() | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment