pyhton 163 email ssl attach file

import smtplib
from email import encoders
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.header import Header

EMAIL_PASS = "XXX"
EMAIL_SENDER = "XXX@163.com"
EMAIL_HOST = "smtp.163.com"
EMAIL_PORT = 465
RECEIVER_EMAILS = ["XXX@163.com"]

def send_email(file_name, file_content=None):
    if file_content:
        assert isinstance(file_content, bytes)
    email_file = MIMEApplication(file_content)
    encoders.encode_base64(email_file)
    email_file.set_payload(email_file.get_payload())

    email_file.add_header('Content-Disposition',
                          'attachment; filename="{}"'.format(file_name))
    subject = '文件:{}'.format(file_name)
    message = MIMEMultipart()
    message['From'] = EMAIL_SENDER
    message['To'] = ','.join(RECEIVER_EMAILS)
    message['Subject'] = Header(subject, 'utf-8')
    message.attach(email_file)
    smtp_obj = smtplib.SMTP_SSL(EMAIL_HOST, EMAIL_PORT)
    smtp_obj.set_debuglevel(1)
    smtp_obj.login(EMAIL_SENDER, EMAIL_PASS)
    smtp_obj.sendmail(EMAIL_SENDER, RECEIVER_EMAILS, message.as_string())
    smtp_obj.quit()


with open('emm.txt', 'rb') as f:
    send_email(file_name='emm.txt', file_content=f.read())

posted @ 2019-08-26 09:53  twfb  阅读(198)  评论(0编辑  收藏  举报