python邮件发送(超全详细版本)

由于最近在搞数据统计和日报的东西,所以专门整理了一下python发送邮件的整个流程以及测试规范,废话不多说,直接进入操作。

1.前期准备 :开启邮箱smtp权限、安装python 所需模块(记住python命名不要叫email.py 会和原有的有冲突)

 

2.源码直接上: 

# -*- coding: utf-8 -*-
import smtplib
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from os.path import basename

EMAIL_ACCOUNT = {
    'test': {
        'username': "1162******@qq.com",
        'password': "ybbjyvnymibkbach",
        'host': 'smtp.qq.com',
    }
}


#  subject 邮件标题  html 内容  to 发送给谁
def send_email(subject, html, to, files, account=EMAIL_ACCOUNT["test"]):
    msg = MIMEMultipart('alternative')

    msg['From'] = account['username']
    msg['To'] = ','.join(to)
    msg['Subject'] = subject

    html_part = MIMEText(html, 'html', 'utf-8')
    msg.attach(html_part)

    # 发送附件  不想带附件 files=none即可
    for f in files or []:
        with open(f, "rb") as fil:
            part = MIMEApplication(
                fil.read(),
                Name=basename(f)
            )
        # After the file is closed
        part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
        msg.attach(part)

    # 校验smtp
    smtp = smtplib.SMTP(account['host'])
    smtp.login(account['username'], account['password'])
    # 校验发送方是否是username
    smtp.sendmail(account['username'], to, msg.as_string())
    smtp.quit()


if __name__ == "__main__":
    send_email("测试邮件发送", "测试内容哈哈", ["***@****.com"], ["test.py"])

 

3.总结 python是一个非常快速容易上手的语言,如果有问题,欢迎指出!

我等采石之人,当心怀大教堂之愿景!

你可能感兴趣的:(python)