使用Python发送邮件时生成纯文本内容
发布时间:2023-12-24 01:10:01
要在Python中发送纯文本邮件,可以使用smtplib模块。下面是一个使用smtplib发送纯文本邮件的示例代码。
首先,我们需要导入smtplib模块并实例化一个SMTP对象。然后,我们需要使用SMTP对象的login方法登录到我们的邮件服务器。接下来,我们可以使用SMTP对象的sendmail方法发送电子邮件。
import smtplib
def send_email(sender_email, sender_password, receiver_email, subject, body):
smtp_server = "smtp.example.com"
smtp_port = 587
# 实例化SMTP对象
smtp_obj = smtplib.SMTP(smtp_server, smtp_port)
try:
# 登录到邮件服务器
smtp_obj.starttls()
smtp_obj.login(sender_email, sender_password)
# 构造邮件内容
message = f"Subject: {subject}
{body}"
# 发送邮件
smtp_obj.sendmail(sender_email, receiver_email, message)
print("邮件发送成功")
except Exception as e:
print("邮件发送失败:", str(e))
finally:
# 退出登录
smtp_obj.quit()
# 示例用法
sender_email = "your_email@example.com"
sender_password = "your_password"
receiver_email = "recipient@example.com"
subject = "测试邮件"
body = "这是一封测试邮件。"
send_email(sender_email, sender_password, receiver_email, subject, body)
在上面的例子中,我们定义了一个send_email函数,它接受发送者邮箱、发送者密码、收件人邮箱、主题和正文作为输入参数。在函数内部,我们使用smtplib模块创建了一个SMTP对象,并调用其starttls方法启用TLS加密。然后,我们使用SMTP对象的login方法登录到我们的邮件服务器。接下来,我们根据输入参数构造了邮件内容,并使用SMTP对象的sendmail方法发送了邮件。最后,我们调用SMTP对象的quit方法退出登录。
请注意,在使用此示例之前,您需要将smtp_server和smtp_port更改为您的邮件服务器的地址和端口,sender_email和sender_password更改为您的发送者邮箱和密码,以及receiver_email更改为您的接收者邮箱。确保您已经具备相应的邮件服务器访问权限。
希望这个例子能帮助你使用Python发送纯文本邮件!
