Skip to content

Instantly share code, notes, and snippets.

@davidliyutong
Last active May 21, 2022 17:04
Show Gist options
  • Save davidliyutong/f3be09f5a3e9dbd33b77548323a76140 to your computer and use it in GitHub Desktop.
Save davidliyutong/f3be09f5a3e9dbd33b77548323a76140 to your computer and use it in GitHub Desktop.
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
import json
import os
import getpass
from typing import List, Tuple, Dict
EMAIL_SUBJECT = 'Notification of DM'
EMAIL_SENDER_DESC = 'NotificationBot'
EMAIL_HOST = 'mail.example.com'
EMAIL_SENDER_ACCOUNT = 'sender@example.com'
EMAIL_SENDER_SECRET = getpass.getpass('Input the password of your email account: ')
def send_email(server: smtplib.SMTPException,
content: str,
files_list: List[Tuple[str]],
destinations: str):
toaddrs = destinations
textpart = MIMEText(content)
m = MIMEMultipart()
m.attach(textpart)
for file in files_list:
filepart = MIMEApplication(file[1]) # file[1] The binary content of file
filepart.add_header('Content-Disposition',
'attachment', filename=file[0]) # file[0] The name of file
m.attach(filepart)
m['Subject'] = EMAIL_SUBJECT
m['From'] = EMAIL_SENDER_DESC
m['To'] = "".join([f"<{dest}>" for dest in destinations])
try:
server.sendmail(EMAIL_SENDER_ACCOUNT, toaddrs, m.as_string())
print('success')
return True
except smtplib.SMTPException as err:
print('error:', err) # Log error
return False
def get_server(email_host: str, account: str, secret: str):
server = smtplib.SMTP(email_host)
server.login(account, secret)
return server
def del_server(server: smtplib.SMTP):
server.quit()
def get_job():
"""Rewrite this function to generate new jobs
Returns:
A list of tuples with 'destination' and 'file' as key
"""
return [{ "destination": 'receiver@example.com',
"file": './python-smtp-send-file.py'}]
def main():
server = get_server(EMAIL_HOST, EMAIL_SENDER_ACCOUNT, EMAIL_SENDER_SECRET)
jobs = get_job()
for job in jobs:
filename = os.path.basename(job['file'])
filecontent = open(job['file'], 'rb').read()
send_email(server, 'helloworld', [(filename, filecontent)], job['destination'])
del_server(server)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment