Python发送带有特定日期的MIMEText邮件
发布时间:2023-12-11 13:50:30
以下是一个Python发送带有特定日期的MIMEText邮件的示例代码:
import smtplib
from email.mime.text import MIMEText
from email.utils import formatdate
# 发件人邮箱信息
smtp_server = 'smtp.gmail.com'
smtp_port = 587
sender_email = 'your_email@gmail.com'
sender_password = 'your_password'
# 收件人邮箱信息
receiver_email = 'recipient_email@example.com'
# 构建邮件内容
subject = 'Important Date Reminder'
date = '2021-12-31'
message_text = f"Hi,
Just a reminder that the deadline for the project is {date}.
Best regards,
Your Name"
# 构建邮件对象
msg = MIMEText(message_text)
msg['Subject'] = subject
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Date'] = formatdate(localtime=True)
try:
# 连接到SMTP服务器
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(sender_email, sender_password)
# 发送邮件
server.sendmail(sender_email, receiver_email, msg.as_string())
server.quit()
print("邮件发送成功!")
except Exception as e:
print("邮件发送失败:", str(e))
在上面的代码中,需要根据实际情况修改以下信息:
- smtp_server:SMTP服务器地址。在此例中使用的是Gmail的SMTP服务器,如果使用其他邮件提供商,请将其替换为相应的服务器地址。
- smtp_port:SMTP服务器端口号。Gmail的SMTP端口号是587,如果使用其他邮件提供商,请将其替换为相应的端口号。
- sender_email:发件人邮箱地址。替换为您自己的邮箱地址。
- sender_password:发件人邮箱密码。替换为您自己的邮箱密码。
- receiver_email:收件人邮箱地址。替换为您要发送邮件的收件人邮箱地址。
- subject:邮件主题。
- date:特定日期。您可以根据需要修改日期。
- message_text:邮件内容。
- Your Name:您的姓名。将其替换为您自己的姓名。
请确保已在Python环境中安装smtplib库并导入所需的模块。此外,确保SMTP服务器允许使用您的邮箱地址发送邮件。
