版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39591494/article/details/85158199
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import smtplib
from smtplib import SMTP_SSL
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
def get_password(): # 获取邮箱授权码
return "xxxxxxxxxxxxxx"
def send_email(username):
smtp = SMTP_SSL("smtp.qq.com") # 邮件服务器地址
smtp.set_debuglevel(1)
smtp.ehlo("smtp.qq.com") # 验证是否成功
smtp.login("[email protected]", get_password()) # 邮件账户密码
text = f"{username}: \n 欢迎来到yankerp公司!"
msg = MIMEText(text, "plain", "utf-8")
msg["Subject"] = Header("会员注册成功", "utf-8") # 邮件的标题.
msg["from"] = "[email protected]" # 谁发到谁
msg["to"] = "[email protected]" # 发到此邮箱
smtp.sendmail("[email protected]", "[email protected]", msg.as_string())
smtp.quit()
# TODO:发一个附件
def send_email_attach(body, attachment):
msg = MIMEMultipart()
msg["Subject"] = Header("会员注册成功", "utf-8")
msg["from"] = "[email protected]"
# msg["to"] = "[email protected]"
to_mail = ["[email protected]", "[email protected]"]
msg["To"] = ",".join(to_mail)
# plain表示纯文本
msg.attach(MIMEText(body, 'plain', 'utf-8'))
# 二进制方式模式文件
with open(attachment, "rb") as f:
mime = MIMEBase("text", "txt", filename=attachment)
mime.add_header("Content-Disposition", "attachment", filename=attachment)
mime.set_payload(f.read())
encoders.encode_base64(mime)
msg.attach(mime)
try:
smtp.sendmail("[email protected]", to_mail, msg.as_string())
smtp.quit()
except smtplib.SMTPException as e:
print(e)
if __name__ == "__main__":
send_email("zhangsan")