发邮件
代码
import smtplib from email.mime.text import MIMEText from email.header import Header import os def send_email(): sender = 'tianxiaodema@163.com' # 发送邮箱 receiver = '601814578@qq.com' # 接收邮箱 smtpserver = 'smtp.163.com' # 服务 username = 'tianxiaodema@163.com' # 用户名 password = 'XXX' # 密码 # 邮件主题 mail_title = '邮件主题' # 读取html文件内容 mail_path = './pytest.html' if os.path.exists(mail_path): with open(mail_path, "rb") as f: mail_body = f.read() else: print("要发送的文件不存在,请检查文件") print("邮件发送失败!") exit() # 邮件内容, 格式, 编码 message = MIMEText(mail_body, 'html', 'utf-8') message['From'] = sender message['To'] = receiver message['Subject'] = Header(mail_title, 'utf-8') try: smtp = smtplib.SMTP() smtp.connect(smtpserver) smtp.login(username, password) smtp.sendmail(sender, receiver, message.as_string()) print("发送邮件成功!!!") smtp.quit() except smtplib.SMTPException: print("发送邮件失败!!!") if __name__ == '__main__': send_email()