Skip to content

Instantly share code, notes, and snippets.

@quest4i
Created August 12, 2021 05:21
Show Gist options
  • Save quest4i/c45ec3381094c1852530e708f973e336 to your computer and use it in GitHub Desktop.
Save quest4i/c45ec3381094c1852530e708f973e336 to your computer and use it in GitHub Desktop.
Microsoft 365 SMTP
import smtplib
import mimetypes
import os
from email.message import EmailMessage
# References
# https://support.microsoft.com/en-us/office/pop-imap-and-smtp-settings-8361e398-8af4-4e97-b147-6c6c4ac95353
# https://docs.python.org/ko/3/library/email.examples.html#email-examples
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types
# https://developer.mozilla.org/ko/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
EMAIL_ADDRESS = "M365_EMAIL_ADDRESS"
EMAIL_PASSWORD = "APP_PASSWORD"
M365_SMTP_SERVER = "smtp.office365.com"
M365_SMTP_PORT = 587
M365_SMTP_ENCRYPTION = "STARTTLS"
M365_IMAP_SERVER = "outlook.office365.com"
M365_IMAP_PORT = "993"
M365_IMAP_ENCRYPTION = "SSL/TLS"
to_list = ["[email protected]"]
cc_list = []
bcc_list = []
subject = "메일 제목"
body = "메일 본문"
attach_directory_list = ['attachments']
msg = EmailMessage()
msg["From"] = EMAIL_ADDRESS
msg["To"] = ", ".join(to_list)
if cc_list:
msg["Cc"] = ", ".join(cc_list)
if bcc_list:
msg["Bcc"] = ", ".join(bcc_list)
msg["Subject"] = subject
msg.set_content(body)
def attach_files(directory: str) -> None:
for filename in os.listdir(directory):
path = os.path.join(directory, filename)
if not os.path.isfile(path):
continue
ctype, encoding = mimetypes.guess_type(filename)
if ctype is None or encoding is not None:
ctype = 'application/octet-stream'
# ['application', 'vnd.openxmlformats-officedocument.spreadsheetml.sheet']
maintype, subtype = ctype.split('/', 1)
with open(path, 'rb') as fp:
# msg.add_attachment(f.read(), maintype="image", subtype="png", filename=f.name)
msg.add_attachment(fp.read(), maintype=maintype, subtype=subtype, filename=filename)
# Attachments
if attach_directory_list:
for directory in attach_directory_list:
attach_files(directory=directory)
with smtplib.SMTP(M365_SMTP_SERVER, M365_SMTP_PORT) as smtp:
smtp.ehlo() # 연결 수립 확인
smtp.starttls()
smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
smtp.send_message(msg)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment