Python 使用 Requests 和 SMTP 实现天气预警邮件系统
随着科技的发展,人们对天气的关注度越来越高。特别是在一些特殊天气条件下,如雨天、高温等,及时获取预警信息对于人们的出行和生活至关重要。本文将介绍如何使用 Python 的 Requests 库和 SMTP 库来实现一个简单的天气预警邮件系统。
系统需求
1. 获取实时天气数据。
2. 根据设定的条件(如雨天、高温)判断是否触发预警。
3. 使用 SMTP 发送预警邮件。
技术选型
1. Requests:用于发送 HTTP 请求,获取天气数据。
2. SMTP:用于发送邮件。
实现步骤
1. 获取天气数据
我们需要从某个天气API获取实时天气数据。这里以和风天气API为例,其API文档地址为:https://www.seniverse.com/docs/api/weather/now
注册和风天气API后,你将获得一个API Key,用于获取数据。
2. 判断预警条件
根据设定的条件(如雨天、高温),判断是否触发预警。以下是一个简单的判断逻辑:
- 如果降雨概率大于等于50%,则触发雨天预警。
- 如果温度大于等于35℃,则触发高温预警。
3. 发送邮件
使用 Python 的 SMTP 库发送邮件。以下是一个简单的邮件发送示例:
python
import smtplib
from email.mime.text import MIMEText
from email.header import Header
def send_email(subject, content, to_email):
sender = 'your_email@example.com'
password = 'your_password'
smtp_server = 'smtp.example.com'
msg = MIMEText(content, 'plain', 'utf-8')
msg['From'] = Header(sender, 'utf-8')
msg['To'] = Header(to_email, 'utf-8')
msg['Subject'] = Header(subject, 'utf-8')
try:
smtp_obj = smtplib.SMTP_SSL(smtp_server, 465)
smtp_obj.login(sender, password)
smtp_obj.sendmail(sender, to_email, msg.as_string())
print("邮件发送成功")
except smtplib.SMTPException as e:
print("邮件发送失败", e)
finally:
smtp_obj.quit()
代码实现
以下是一个简单的天气预警邮件系统的实现:
python
import requests
import smtplib
from email.mime.text import MIMEText
from email.header import Header
获取天气数据
def get_weather_data(api_key, location):
url = f"http://api.seniverse.com/v3/weather/now.json?key={api_key}&location={location}&language=zh-Hans&unit=c"
response = requests.get(url)
return response.json()
判断预警条件
def check_weather_alert(weather_data):
rain_probability = weather_data['results'][0]['now']['rain_probability']
temperature = weather_data['results'][0]['now']['temperature']
if rain_probability >= 50:
return '雨天预警'
elif temperature >= 35:
return '高温预警'
else:
return '无预警'
发送邮件
def send_email(subject, content, to_email):
sender = 'your_email@example.com'
password = 'your_password'
smtp_server = 'smtp.example.com'
msg = MIMEText(content, 'plain', 'utf-8')
msg['From'] = Header(sender, 'utf-8')
msg['To'] = Header(to_email, 'utf-8')
msg['Subject'] = Header(subject, 'utf-8')
try:
smtp_obj = smtplib.SMTP_SSL(smtp_server, 465)
smtp_obj.login(sender, password)
smtp_obj.sendmail(sender, to_email, msg.as_string())
print("邮件发送成功")
except smtplib.SMTPException as e:
print("邮件发送失败", e)
finally:
smtp_obj.quit()
主函数
def main():
api_key = 'your_api_key'
location = 'your_location'
to_email = 'recipient@example.com'
weather_data = get_weather_data(api_key, location)
alert_type = check_weather_alert(weather_data)
if alert_type:
subject = f"{location} {alert_type}"
content = f"当前{location}天气情况:{alert_type}"
send_email(subject, content, to_email)
if __name__ == '__main__':
main()
总结
本文介绍了如何使用 Python 的 Requests 和 SMTP 库实现一个简单的天气预警邮件系统。通过获取实时天气数据,判断预警条件,并使用 SMTP 发送邮件,用户可以及时获取天气预警信息。在实际应用中,可以根据需求对系统进行扩展,如增加更多预警条件、支持更多天气API等。
Comments NOTHING