import smtplib from email.mime.text import MIMEText from email.header import Header # 邮件服务器地址和端口号 mail_host = 'smtp.example.com' mail_port = 25 # 发件人邮箱地址和密码 mail_user = 'sender@example.com' mail_password = 'password' # 收件人邮箱地址 mail_receiver = 'receiver@example.com' # 邮件内容和标题 mail_content = '这是一封测试邮件' mail_title = '测试邮件' # 构造MIME邮件对象 message = MIMEText(mail_content, 'plain', 'utf-8') message['From'] = Header(mail_user, 'utf-8') message['To'] = Header(mail_receiver, 'utf-8') message['Subject'] = Header(mail_title, 'utf-8') # 发送邮件 try: # 连接邮件服务器并登录 smtp_obj = smtplib.SMTP(host=mail_host, port=mail_port) smtp_obj.login(mail_user, mail_password) # 发送邮件 smtp_obj.sendmail(mail_user, mail_receiver, message.as_string()) print('邮件发送成功') except Exception as e: print('邮件发送失败,请检查邮件配置:', e) finally: # 关闭连接 smtp_obj.quit()