怎么用python自动发邮件
时间: 2024-09-18 15:13:52 浏览: 37
在Python中,你可以使用内置的`smtplib`库或者第三方库如`smtplib`, `email`, 或者更高级的`yagmail`、`mailchimp`等来发送电子邮件。这里是一个基本的例子,展示如何使用`smtplib`发送纯文本邮件:
```python
import smtplib
from email.mime.text import MIMEText
# 邮件设置
sender = 'your_email@example.com'
receiver = 'recipient_email@example.com'
password = 'your_email_password'
subject = 'Hello from Python'
body = 'This is a test email sent using Python.'
# 创建邮件对象
msg = MIMEText(body)
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = subject
try:
# 连接到SMTP服务器
smtp_server = "smtp.example.com" # 替换为你邮箱的SMTP服务器地址
smtp_port = 587 # 或者465 for SSL/TLS
server = smtplib.SMTP(smtp_server, smtp_port)
# 启动TLS加密连接(如果需要)
server.starttls()
# 登录到邮箱
server.login(sender, password)
# 发送邮件
server.send_message(msg)
print("Email sent successfully!")
except Exception as e:
print(f"Failed to send email: {str(e)}")
finally:
# 关闭连接
server.quit()
```
阅读全文