准备工作:

1.qq邮箱smtp打开 如下图所示:

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是一个非常快速容易上手的语言,如果有问题,欢迎指出!
我等采石之人,当心怀大教堂之愿景!