この記事では、Pythonを使用して天気情報を取得し、それをメールで送信する方法を説明します。APIからデータを取得し、必要な情報を抽出してメールにフォーマットします。
import requests
import json
api_url = 'https://weatherapi.example.com/v1/forecast?location=tokyo&key=your_api_key'
response = requests.get(api_url)
weather_data = json.loads(response.text)
email_body = ""
for forecast in weather_data["forecast_days"]:
date = forecast["date"]
max_temp = forecast["max_temperature"]
min_temp = forecast["min_temperature"]
condition = forecast["condition"]
wind_direction = forecast["wind_direction"]
wind_speed = forecast["wind_speed"]
humidity = forecast["humidity"]
precipitation = forecast["precipitation"]
pressure = forecast["pressure"]
visibility = forecast["visibility"]
cloud_cover = forecast["cloud_cover"]
email_body += f"日付: {date}\n"
email_body += f"最高気温: {max_temp} °C\n"
email_body += f"最低気温: {min_temp} °C\n"
email_body += f"天気状況: {condition}\n"
email_body += f"風向: {wind_direction}\n"
email_body += f"風速: {wind_speed} km/h\n"
email_body += f"湿度: {humidity}%\n"
email_body += f"降水量: {precipitation} mm\n"
email_body += f"気圧: {pressure} hPa\n"
email_body += f"視程: {visibility} km\n"
email_body += f"雲量: {cloud_cover}%\n"
email_body += "\n"
print(email_body)
上記のコードは、指定された都市の3日間の天気予報を取得し、その情報をメールの本文として整形します。APIキーとURLは、使用する天気予報サービスのドキュメントを参照してください。
メール送信用にはswaksを利用します。以下はその例です:
import subprocess
subject = "本日の天気予報"
recipient_email = "user@example.com"
sender_email = "weatherbot@weather.com"
mail_command = f"swaks --to {recipient_email} --from {sender_email} --body '{email_body}' --header 'Subject: {subject}'"
subprocess.run(mail_command, shell=True)
最後に、定期的にこのスクリプトを実行するために、Linuxのcrontabを使用します。例えば、毎日午前7時に実行するには次のようになります:
50 7 * * * /usr/bin/python3 /path/to/weather_script.py
これにより、指定した時間に自動的にスクリプトが実行され、メールが送信されます。