Created
February 19, 2021 06:48
-
-
Save pangyuteng/b1e5cd003bd2310cbf335791e9d08d1d to your computer and use it in GitHub Desktop.
python email utils
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import warnings | |
import traceback | |
import smtplib | |
from email.mime.text import MIMEText | |
from email.mime.multipart import MIMEMultipart | |
from email.mime.application import MIMEApplication | |
import getpass | |
# email_server coule be email_server+":"+port | |
# password could be optional `None` | |
# send email | |
def send_email( | |
email_server, | |
sender_email, | |
to_email_list, | |
to_subject, | |
text_body, | |
file_list=[], | |
password=None): | |
msg = MIMEMultipart() | |
msg["From"] = sender_email | |
msg["To"] = ", ".join(to_email_list) | |
msg["Subject"] = to_subject | |
msg.attach(MIMEText(text_body, "plain")) | |
for file_path in file_list: | |
with open(file_path, "rb") as fil: | |
part = MIMEApplication( | |
fil.read(), | |
Name=os.path.basename(file_path) | |
) | |
part['Content-Disposition'] = f'attachment; filename="{os.path.basename(file_path)}"' | |
msg.attach(part) | |
text = msg.as_string() | |
s = smtplib.SMTP(email_server) | |
if password is not None: | |
s.ehlo() | |
s.starttls() | |
s.login(sender_email,password) | |
s.sendmail(sender_email,to_email_list,text) | |
s.quit() | |
return True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment