发邮件
Posted sleep10000years
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了发邮件相关的知识,希望对你有一定的参考价值。
代码
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()
以上是关于发邮件的主要内容,如果未能解决你的问题,请参考以下文章