
作者:CPP手艺人 来源: CPP手艺人 日期:2026-12-01 18:08:27
要使(shi)用Python发送电子邮件,可以(yi)使用smtplib库和email库,以下是(shi)一个简单的(de)示例:(图(tu)片来源网络,侵删)
1、确保已经(jing)安装了smtplib和email库,如果没有安装,可以使用以(yi)下命令安装:

pip install securesmtplibpip install email
2、编写一个Python脚本来发送电子邮件,以下是一个示例:

import smtplibfrom email.mime.text import MIMETextfrom email.header import Header发件人和收件人的邮箱地址sender = 'your_email@example.com'receiver = 'receiver_email@example.com'邮件(jian)主题和内容subject = '邮件主题'content = '邮件(jian)正文'创建邮件对象message = MIMEText(content, 'plain', 'utf8')message['From'] = Header(sender, 'utf8')message['To'] = Header(receiver, 'utf8')message['Subject'] = Header(subject, 'utf8')发送邮件try: smtp_obj = smtplib.SMTP('smtp.example.com', 587) # 使用你的SMTP服务(wu)器地址和端口 smtp_obj.login('your_email@example.com', 'your_password') # 使用你的邮箱地址和密码登录 smtp_obj.sendmail(sender, [receiver], message.as_string()) print("邮件发送成功")except smtplib.SMTPException as e: print("Error: 无法发送邮件", e)请将上述代码中的your_email@example.com、receiver_email@example.com、smtp.example.com、your_password替换为实际的发件人邮箱地址、收件人邮箱地址、SMTP服务(wu)器地址和发件人邮箱密码。
