Skip to content

Instantly share code, notes, and snippets.

@wecsam
Last active November 24, 2018 03:57
Show Gist options
  • Select an option

  • Save wecsam/ddf004c1f01e8dec5a8d25c08099a020 to your computer and use it in GitHub Desktop.

Select an option

Save wecsam/ddf004c1f01e8dec5a8d25c08099a020 to your computer and use it in GitHub Desktop.
Creates a MailItem object in Microsoft Outlook with stuff already filled in
import win32com.client
class AttachmentInfo:
def __init__(self, file_path, mime_type, attachment_id=None):
self.file_path = file_path
self.mime_type = mime_type
self.id = attachment_id
def draft_html(
to=(),
cc=(),
bcc=(),
subject="",
attachments=(),
body="",
display=True
):
draft = win32com.client.gencache.EnsureDispatch(
"Outlook.Application"
).CreateItem(
win32com.client.constants.olMailItem
)
# Add the To, Cc, and Bcc fields.
for recipient in to:
draft.Recipients.Add(recipient)
for recipient in cc:
draft.Recipients.Add(recipient).Type = win32com.client.constants.olCC
for recipient in bcc:
draft.Recipients.Add(recipient).Type = win32com.client.constants.olBCC
draft.Recipients.ResolveAll()
# Add the subject.
draft.Subject = subject
# Add attachments.
for attachment in attachments:
assert isinstance(attachment, AttachmentInfo)
attachment_property_accessor = \
draft.Attachments.Add(attachment.file_path).PropertyAccessor
if isinstance(attachment.mime_type, str):
attachment_property_accessor.SetProperty(
"http://schemas.microsoft.com/mapi/proptag/0x370E001E",
attachment.mime_type
)
if isinstance(attachment.id, str):
attachment_property_accessor.SetProperty(
"http://schemas.microsoft.com/mapi/proptag/0x3712001E",
attachment.id
)
# Set the e-mail body.
draft.HTMLBody = body
# Open the e-mail draft in an Outlook window if it is wanted. This is here
# because an earlier version of the function did this and did not have the
# display argument.
if display:
draft.Display()
# The caller can call other methods of the MailItem object.
# https://docs.microsoft.com/en-us/office/vba/api/outlook.mailitem
return draft
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment