如何用Python发送email
时间: 2023-11-16 08:02:59 浏览: 73
要使用Python发送电子邮件,可以使用Python的内置smtplib模块。以下是一个示例脚本,该示例脚本使用smtplib模块发送电子邮件:
```python
import smtplib
# 配置SMTP服务器
smtp_server = 'smtp.gmail.com'
smtp_port = 587
smtp_username = 'your_email@gmail.com' # 发送方email
smtp_password = 'your_password' # 发送方email的密码
# 配置邮件内容
sender = 'your_email@gmail.com' # 发送方email
receiver = 'recipient_email@gmail.com' # 接收方email
subject = 'Test email'
body = 'This is a test email sent using Python.'
# 将邮件内容组成字符串
message = f'Subject: {subject}\n\n{body}'
# 发送邮件
try:
smtp_obj = smtplib.SMTP(smtp_server, smtp_port)
smtp_obj.starttls()
smtp_obj.login(smtp_username, smtp_password)
smtp_obj.sendmail(sender, receiver, message)
print('Email sent successfully')
except Exception as e:
print('Error occurred while sending the email:', e)
finally:
smtp_obj.quit()
```
在脚本中,首先配置SMTP服务器和邮件内容。然后,将邮件内容组成字符串,并使用smtplib模块中的SMTP类发送邮件。发送邮件时,需要登录SMTP服务器以验证身份。最后,使用quit()方法关闭SMTP连接。
阅读全文
相关推荐

















