import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# 文本邮件
def sendEmail():
    host = ‘smtp.163.com‘
    sender = "fzwicc@163.com"
    user = ‘fzwicc@163.com‘
    password = ‘HTSBLLEAVBYJJANH‘  # 授权码
    to = [‘2584066573@qq.com‘]
    # Email 信息
    email = MIMEText("dd", ‘text‘, ‘utf-8‘)
    email[‘Subject‘] = "subject"
    email[‘From‘] = sender
    email[‘To‘] = to[0]
    msg = email.as_string()
    print(msg)
    # 连接
    # 登录
    print(‘Logging with server...‘)
    smtpObj = smtplib.SMTP()
    smtpObj.connect(host, 25)
    smtpObj.login(user, password)
    print(‘Login successful.‘)
    # 发送
    smtpObj.sendmail(sender, to, msg)
    smtpObj.quit()
    print(‘Email has been sent‘)
# 发送附件邮件
def sendEmailWithAttachment():
    host = ‘smtp.163.com‘
    sender = "fzwicc@163.com"
    user = ‘fzwicc@163.com‘
    password = ‘HTSBLLEAVBYJJANH‘  # 授权码
    to = [‘2584066573@qq.com‘]
    # Make content of email
    subject = ‘daily check report‘  # 邮件主题
    with open(‘./file/test.html‘, ‘r‘) as f:
        content = MIMEText(f.read(), ‘html‘, ‘utf-8‘)
        content[‘Content-Type‘] = ‘text/html‘
    # Make txt attachment
    with open(‘./file/txt.md‘, ‘r‘) as f:
        txt = MIMEText(f.read(), ‘plain‘, ‘utf-8‘)
        txt[‘Content-Type‘] = ‘application/octet-stream‘
        txt[‘Content-Disposition‘] = ‘attachment;filename="txt.md"‘
    # Make csv attachment
    part_attach1 = MIMEApplication(open(‘./file/data.csv‘, ‘rb‘).read())  # 打开附件
    part_attach1.set_payload("数据", ‘utf-8‘)
    part_attach1.add_header(‘Content-Disposition‘, ‘attachment‘, filename=‘newName.csv‘)  # 为附件命名v
    # Attach content & attachments to email
    email = MIMEMultipart()
    # email.attach(content)
    # email.attach(txt)
    email.attach(part_attach1)
    email.attach(MIMEText("这里是邮件内容", _subtype=‘html‘, _charset=‘utf-8‘))
    # Settings of the email string
    email[‘Subject‘] = subject
    email[‘From‘] = sender
    email[‘To‘] = to[0]
    msg = email.as_string()
    print(msg)
    # 登录
    print(‘Logging with server...‘)
    smtpObj = smtplib.SMTP()
    smtpObj.connect(host, 25)
    smtpObj.login(user, password)
    print(‘Login successful.‘)
    # 发送
    smtpObj.sendmail(sender, to, msg)
    smtpObj.quit()
    print(‘Email has been sent‘)
# sendEmailWithAttachment()
if __name__ == ‘__main__‘:
    sendEmailWithAttachment()
原文:https://www.cnblogs.com/lymcc/p/14857029.html