用python在Windows 环境下用 smtp 实现 Email 客户端
时间: 2023-05-30 12:03:16 浏览: 80
以下是一个使用 Python SMTP 在 Windows 环境下实现 Email 客户端的示例代码:
```
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
# 发件人信息
sender_email = 'your_email@example.com'
sender_name = 'Your Name'
sender_password = 'your_email_password'
# 收件人信息
receiver_email = 'receiver_email@example.com'
receiver_name = 'Receiver Name'
# 邮件主题和内容
subject = 'Test Email'
body = 'This is a test email sent from Python SMTP.'
# 创建邮件对象
msg = MIMEText(body, 'plain', 'utf-8')
msg['From'] = formataddr((sender_name, sender_email))
msg['To'] = formataddr((receiver_name, receiver_email))
msg['Subject'] = subject
# 连接 SMTP 服务器并发送邮件
try:
smtp_server = smtplib.SMTP('smtp.example.com', 587)
smtp_server.starttls()
smtp_server.login(sender_email, sender_password)
smtp_server.sendmail(sender_email, [receiver_email], msg.as_string())
smtp_server.quit()
print('Email sent successfully.')
except Exception as e:
print('Failed to send email:', e)
```
在上述代码中,需要将 `your_email@example.com`、`Your Name`、`your_email_password`、`receiver_email@example.com`、`Receiver Name`、`smtp.example.com` 等信息替换为实际的发件人和收件人信息、SMTP 服务器信息。
此外,代码中使用了 Python 内置的 `smtplib` 模块和 `email` 模块来实现邮件发送功能。首先,通过 `MIMEText` 类创建邮件对象,并设置发件人、收件人、主题和邮件内容。然后,使用 `SMTP` 类连接 SMTP 服务器并登录发件人邮箱,最后使用 `sendmail` 方法发送邮件。
如果一切正常,程序将输出 `Email sent successfully.`,否则会输出错误信息。