构建一个Python脚本来发送电子邮件
发布时间:2023-12-04 14:42:02
以下是一个使用Python脚本发送电子邮件的例子:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_email(sender_email, sender_password, receiver_email, subject, message):
# 创建MIMEMultipart对象
email = MIMEMultipart()
email['From'] = sender_email
email['To'] = receiver_email
email['Subject'] = subject
# 添加邮件内容
email.attach(MIMEText(message, 'plain'))
try:
# 创建SMTP对象并连接到邮件服务器
smtp = smtplib.SMTP('smtp.gmail.com', 587)
smtp.starttls()
smtp.login(sender_email, sender_password)
# 发送邮件
smtp.send_message(email)
print("邮件发送成功")
except Exception as e:
print("邮件发送失败:", str(e))
finally:
# 断开连接
smtp.quit()
# 输入发件人邮箱、密码、收件人邮箱、主题和消息
sender_email = input("请输入发件人邮箱: ")
sender_password = input("请输入发件人邮箱密码: ")
receiver_email = input("请输入收件人邮箱: ")
subject = input("请输入邮件主题: ")
message = input("请输入邮件内容: ")
# 发送邮件
send_email(sender_email, sender_password, receiver_email, subject, message)
使用该脚本发送电子邮件的步骤如下:
1. 创建一个带有发件人邮箱、密码、收件人邮箱、主题和消息的Python脚本。
2. 运行脚本后,脚本会提示您输入以下信息:
- 发件人邮箱:您要使用的发件人邮箱地址。
- 发件人邮箱密码:您的发件人邮箱的密码。
- 收件人邮箱:您要发送电子邮件的收件人邮箱地址。
- 邮件主题:您要发送的电子邮件的主题。
- 邮件内容:您要发送的电子邮件的内容。
3. 输入完上述信息后,脚本将使用您提供的发件人邮箱和密码将电子邮件发送到收件人邮箱。
4. 如果邮件发送成功,脚本将打印出"邮件发送成功";如果邮件发送失败,脚本将打印出"邮件发送失败"以及失败的具体原因。
请注意,此示例使用的是Gmail的SMTP服务器,您需要将'smtp.gmail.com'更改为您所使用的邮件服务提供商的SMTP服务器地址,并根据需要更新端口号。确保在使用脚本之前已经设置了发件人邮箱的SMTP访问权限。
