python发送邮件代码
时间: 2024-09-27 09:00:35 浏览: 62
在Python中,你可以使用内置的`smtplib`和`email`库来发送电子邮件。以下是一个基本的示例,展示了如何使用这两个模块创建并发送一封简单的邮件:
```python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# 邮件配置
sender_email = 'your-email@example.com'
receiver_email = 'recipient-email@example.com'
password = 'your-password'
smtp_server = 'smtp.example.com' # 根据你的SMTP服务器填写
subject = 'Hello from Python'
body = 'This is a test email sent using Python.'
# 创建邮件对象
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = subject
# 添加邮件正文
msg.attach(MIMEText(body, 'plain'))
try:
# 连接SMTP服务器
server = smtplib.SMTP(smtp_server, 587)
server.starttls() # 加密连接
# 登录邮箱
server.login(sender_email, password)
# 发送邮件
server.sendmail(sender_email, receiver_email, msg.as_string())
print(f"Email sent successfully to {receiver_email}.")
except Exception as e:
print(f"Error sending email: {e}")
finally:
# 关闭连接
server.quit()
```
记得替换上述代码中的`your-email@example.com`、`recipient-email@example.com`、`your-password`和`smtp.example.com`为你自己的信息。
阅读全文