此脚本可用于根据特定条件自动发送电子邮件。以下是如何使用 Python 发送电子邮件的示例:
import smtplib
from email.mime.text import MIMEText
# Set the SMTP server and login credentials
smtp_server = "smtp.gmail.com"
smtp_port = 587
username = "your@email.com"
pd = "yourpassword"
# Set the email parameters
recipient = "recipient@email.com"
subject = "Test email from Python"
body = "This is a test email sent from Python."
# Create the email message
msg = MIMEText(body)
msg["Subject"] = subject
msg["To"] = recipient
msg["From"] = username
# Send the email
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(username, password)
server.send_message(msg)
server.quit()import smtplib
from email.mime.text import MIMEText
# Set the SMTP server and login credentials
smtp_server = "smtp.gmail.com"
smtp_port = 587
username = "your@email.com"
pd = "yourpassword"
# Set the email parameters
recipient = "recipient@email.com"
subject = "Test email from Python"
body = "This is a test email sent from Python."
# Create the email message
msg = MIMEText(body)
msg["Subject"] = subject
msg["To"] = recipient
msg["From"] = username
# Send the email
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(username, password)
server.send_message(msg)
server.quit()
- 此脚本使用 smtplib 和电子邮件模块,通过简单邮件传输协议 (SMTP) 发送电子邮件。smtplib 模块中的 SMTP 类用于创建 SMTP 客户端,starttls 和登录方法用于建立安全连接,电子邮件模块中的 MIMEText 类用于在多用途 Internet 邮件扩展中创建电子邮件消息( MIME) 格式。MIMEText 构造函数将电子邮件正文作为参数,您可以使用 setitem 方法设置电子邮件的主题、收件人和发件人。
- 创建电子邮件消息后,将使用 SMTP 对象的 send_message 方法发送电子邮件。然后调用 quit 方法关闭与 SMTP 服务器的连接。