-
Notifications
You must be signed in to change notification settings - Fork 0
/
emails.py
38 lines (30 loc) · 1.25 KB
/
emails.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#!/usr/bin/env python3
import email.message
import mimetypes
import os.path
import smtplib
def generate_email(sender: str, recipient: str, subject: str, body: str, attachment_path: str = None)\
-> email.message.EmailMessage:
"""Creates an email with an attachment."""
# Basic Email formatting
message = email.message.EmailMessage()
message["From"] = sender
message["To"] = recipient
message["Subject"] = subject
message.set_content(body)
# Process the attachment and add it to the email
if attachment_path is not None:
attachment_filename = os.path.basename(attachment_path)
mime_type, _ = mimetypes.guess_type(attachment_path)
mime_type, mime_subtype = mime_type.split('/', 1)
with open(attachment_path, 'rb') as ap:
message.add_attachment(ap.read(),
maintype=mime_type,
subtype=mime_subtype,
filename=attachment_filename)
return message
def send_email(message: email.message.EmailMessage) -> None:
"""Sends the message to the configured local SMTP server."""
mail_server = smtplib.SMTP('localhost')
mail_server.send_message(message)
mail_server.quit()