python发送邮件方法
时间: 2023-10-12 18:55:46 浏览: 41
在Python中,你可以使用smtplib库来发送邮件。下面是一个简单的示例代码,展示了如何使用SMTP服务器发送邮件:
```python
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
def send_email(sender_email, sender_password, receiver_email, subject, message):
try:
# 创建一个MIMEText对象,用于构建邮件内容
msg = MIMEText(message, 'plain', 'utf-8')
msg['From'] = formataddr(('Sender Name', sender_email))
msg['To'] = formataddr(('Receiver Name', receiver_email))
msg['Subject'] = subject
# 连接SMTP服务器
server = smtplib.SMTP('smtp.example.com', 587) # 请替换为你的SMTP服务器地址和端口号
server.starttls() # 开启TLS加密
# 登录SMTP服务器
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))
# 调用发送邮件函数
sender_email = "your_email@example.com"
sender_password = "your_password"
receiver_email = "recipient@example.com"
subject = "测试邮件"
message = "这是一封测试邮件"
send_email(sender_email, sender_password, receiver_email, subject, message)
```
请注意,你需要将上述代码中的`smtp.example.com`替换为你的SMTP服务器地址和端口号,并提供正确的发件人和收件人的邮箱地址及密码。