Created
April 26, 2017 03:08
-
-
Save zh4n7wm/618ca55283f8def70bd54bf1e06b6dc0 to your computer and use it in GitHub Desktop.
send email with Python
This file contains hidden or 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
#!/usr/bin/env python | |
# encoding: utf-8 | |
from __future__ import unicode_literals, print_function | |
import smtplib | |
from email.mime.multipart import MIMEMultipart | |
from email.mime.base import MIMEBase | |
from email.mime.text import MIMEText | |
from email.utils import formatdate | |
from email import encoders | |
def send_mail(send_from, send_to, subject, text, filename): | |
''' | |
send_from: str | |
send_to: list | |
subject: str | |
text: str | |
filename: file path | |
''' | |
msg = MIMEMultipart() | |
msg['From'] = send_from | |
msg['To'] = ', '.join(send_to) | |
msg['Date'] = formatdate(localtime=True) | |
msg['Subject'] = subject | |
msg.attach(MIMEText(text, _subtype='plain', _charset='utf8')) | |
# html = '<html><head><title>test</title></head><body>hello</body></html>' | |
# msg.attach(MIMEText(html, _subtype='html', _charset='utf8')) | |
part = MIMEBase('application', 'octet-stream') | |
part.set_payload(open(filename, 'rb').read()) | |
encoders.encode_base64(part) | |
part.add_header('Content-Disposition', 'attachment; filename="{}"'.format(filename)) | |
msg.attach(part) | |
# FIXME: using you smtp server and login information | |
server = '' | |
port = 587 | |
username = '' | |
password = '' | |
conn = get_smtp_conn(server, port, username, password) | |
conn.sendmail(send_from, send_to, msg.as_string()) | |
conn.quit() | |
def get_smtp_conn(server, port, username, password, isTls=True): | |
smtp = smtplib.SMTP(server, port) | |
if isTls: | |
smtp.starttls() | |
smtp.login(username, password) | |
return smtp |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment