Hello all.
read_and_send_emails.py:
from python_for_outlook.outlook import create_attachment
def send_emails(headers, attachments):
file_path = ''
df = ...
endpoint = f'{MS_GRAPH_BASE_URL}/me/sendMail'
for row in df.iterrows():
content = '...'
msg = {
'message': {
'subject': row['subject'],
'body': {
'contentType': 'HTML',
'content': content
},
'toRecipients': [
{
'emailAddress': {
'address': row['to']
}
}
],
'ccRecipients': [
{
'emailAddress': {
'address': row['cc']
}
}
],
'importance': 'high',
'attachments': attachments
}
}
response = httpx.post(endpoint, headers=headers, json=msg)
if response.status_code != 202:
raise Exception(f'Failed to send email: {response.text}')
def main():
dir_attachments = Path('./python_for_onedrive/Downloads')
attachments = [
create_attachment(attachment)
for attachment in dir_attachments.iterdir()
if attachment.is_file()
]
send_emails(headers, attachments)```
`outlook.py`:```
def get_mime_type(file_path):
mime_type, _ = mimetypes.guess_type(file_path)
return mime_type or "application/octet-stream"
def create_attachment(file_path):
with open(file_path, 'rb') as file:
content = file.read()
encoded_content = base64.b64encode(content).decode('utf-8')
return {
'@odata.type': '#microsoft.graph.fileAttachment',
'name': os.path.basename(file_path),
'contentType': get_mime_type(file_path),
'contentBytes': encoded_content
}```