This blog is only for my spare time to record articles , Publish to , Only for users to read , If there is any infringement , Please let me know , I'll delete it .
Quite a few Little whore
The message said this article of no avail
, Because the weather forecast can be received directly by turning on the mobile phone , Why do you want to send it to your email !!! Then I can only say : Because you're useless , So you're useless !!!
ps: In fact, some of them are reasonable , I think it's troublesome to check the weather forecast , So it's not too much trouble checking email ? Ha ha ha
The main introduction here is Ideas
, It's not the weather forecast ! It's not the weather forecast !! It's not the weather forecast !!!
The weather forecast is just for example . Please don't be so rigid !!!
Here are two scenarios I'll use :
The following has not been changed , Consistent with the initial post .
It's getting cooler recently , I will check the weather every day when I get up . But I find it troublesome to check the weather , So the idea of automatically getting the weather forecast every day and sending it to your personal mailbox .
If you find it troublesome to check the weather , Look at this article .
And this article !! Will explain in detail how to achieve daily 8:00 am will be the latest 7 The weather condition will be sent to your personal email .
There are four steps to automatically send weather conditions to your personal email address .
1. The picture below is Wind weather :https://dev.heweather.com/ Home page , Open the registration .
2. After the account is registered successfully, click New application , Create a Key, This Key It's for carrying on Wind weather API Called .
You can see that after the new building is successful Key It's a long string , This is the key to get weather information .
API Developing documents , Click to jump to .
As you can see from the above figure ( There are commercial version and free version. I use free version here ), There are many kinds of weather-type, Here we use forecast, This is to get 3-10 Weather forecast .
According to the above request URL The example shows that , We need to call url by
https://free-api.heweather.net/s6/weather/forecast?location= City Code &key= self-created Key
City can fill in Chinese , You can also fill in City Code City code query .
import requests
url = 'https://free-api.heweather.net/s6/weather/forecast?location= Guangzhou &key=xxxxxxxxx'
res = requests.get(url)
print(res.text)
The return is json File format , You can see that it returns from the beginning of the query day 7 Weather forecast information .
The next task is to analyze this pile of json Format data .
import json
import requests
url = 'https://free-api.heweather.net/s6/weather/forecast?location= Guangzhou &key=xxxxxxxxx'
res = requests.get(url).json() # Because the return is json Format file
result = res['HeWeather6'][0]['basic']
print(result)
# This is the longitude and latitude of the city in question , Time zone and so on .
## {
'cid': 'CN101280101', 'location': ' Guangzhou ', 'parent_city': ' Guangzhou ', 'admin_area': ' guangdong ', 'cnty': ' China ', 'lat': '23.12517738', 'lon': '113.28063965', 'tz': '+8.00'}
import requests
url = 'https://free-api.heweather.net/s6/weather/forecast?location= Guangzhou &key=xxxxxxxxx'
res = requests.get(url).json() # The data returned is json Format
result = res['HeWeather6'][0]['daily_forecast']
print(result)
Because it's called here API Returns the 7 Days of data , So it will return 7 Group the data below .
{
"cond_code_d": "100", # Weather conditions during the day 100 For the sake of clearing 101 For cloudy 104 For Yin etc.
"cond_code_n": "100", # Night weather conditions
"cond_txt_d": " Fine ", # Description of weather conditions during the day
"cond_txt_n": " Fine ", # Description of weather conditions at night
"date": "2019-11-10", # Forecast date
"hum": "50", # Relative humidity
"mr": "16:33", # Monthly rise time
"ms": "04:21", # The setting of the moon
"pcpn": "0.0", # precipitation
"pop": "0", # Probability of precipitation
"pres": "1013", # Atmospheric pressure
"sr": "06:37", # Sunrise time
"ss": "17:43", # Sunset time
"tmp_max": "27", # maximum temperature
"tmp_min": "16", # Minimum temperature
"uv_index": "7", # UV intensity index
"vis": "25", # visibility , Company : km
"wind_deg": "-1", # wind direction 360 angle
"wind_dir": " No sustained wind direction ", # wind direction
"wind_sc": "1-2", # wind
"wind_spd": "6" # The wind speed , km / Hours
}
......
import csv
import requests
url = 'https://free-api.heweather.net/s6/weather/forecast?location= Guangzhou &key=xxxxxx'
res = requests.get(url).json()
result = res['HeWeather6'][0]['daily_forecast']
location = res['HeWeather6'][0]['basic']
city = location['parent_city']+location['location']
names = [' City ',' Time ',' weather condition ',' Maximum temperature ',' Minimum temperature ',' sunrise ',' Sunset ']
for data in result:
date = data['date']
cond = data['cond_txt_d']
max = data['tmp_max']
min = data['tmp_min']
sr = data['sr']
ss = data['ss']
print(city,date,cond,max,min,sr,ss)
## Returned data
Guangzhou, Guangzhou 2019-11-10 Fine 27 16 06:37 17:43
Guangzhou, Guangzhou 2019-11-11 Fine 28 18 06:38 17:43
Guangzhou, Guangzhou 2019-11-12 Fine 29 18 06:39 17:42
Guangzhou, Guangzhou 2019-11-13 cloudy 28 17 06:39 17:42
Guangzhou, Guangzhou 2019-11-14 Fine 25 15 06:40 17:42
Guangzhou, Guangzhou 2019-11-15 Fine 26 15 06:40 17:42
Guangzhou, Guangzhou 2019-11-16 Fine 27 16 06:41 17:41
Reference here Novice tutorial Of Python SMTP Send E-mail
1. First go QQ mailbox
open Set up - Account - Opening service - Turn on POP3/SMTP service , And then click Generate authorization code ,python To send mail, you need to use .
Go straight to the code , Don't explain .
# Simple mail transfer protocol
import smtplib
import email
import time
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
# Set the domain name of the mailbox
HOST = 'smtp.qq.com'
# Set the subject line
SUBJECT = ' Today's weather forecast has arrived , Master '
# Set the sender's mailbox
FROM = '[email protected]'
# Set up the recipient mailbox
TO = '[email protected],[email protected]' # You can fill in more than one mailbox , Separate with commas , I'll use it later split Do the comma division
message = MIMEMultipart('related')
# -------------------------------------- Send text -----------------
# Send the email body to the other party's mailbox
message_html = MIMEText(" Master, your email has arrived \n\nThis is test", 'plain', 'utf-8') # \n For newline
message.attach(message_html)
# ------------------------------------- Add files ---------------------
# Make sure that the current directory has test.csv This file
message_xlsx = MIMEText(open('test.csv', 'rb').read(), 'base64', 'utf-8')
# Set the name of the file in the attachment
message_xlsx['Content-Disposition'] = 'attachment;filename="test01.csv"'
message.attach(message_xlsx)
# Set the email sender
message['From'] = FROM
# Set up mail recipients
message['To'] = TO
# Set the subject line
message['Subject'] = SUBJECT
# Get a certificate for the Simple Mail Transfer Protocol
email_client = smtplib.SMTP_SSL()
# Set the domain name and port of the sender's mailbox , Port is 465
email_client.connect(HOST, '465')
# --------------------------- Email authorization code ------------------------------
result = email_client.login(FROM, ' Your authorization code ')
print(' Login results ', result)
email_client.sendmail(from_addr=FROM, to_addrs=TO.split(','), msg=message.as_string())
# Turn off the email sending client
email_client.close()
# coding=gbk ## notes :linux This line is not needed on the server ,window need
import csv
import time
import requests
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
url = r'https://free-api.heweather.net/s6/weather/forecast?location= Guangzhou &key=xxxxxx'
# Get the time of the day 2019-11-10
today_time = time.strftime('%Y-%m-%d', time.localtime(time.time()))
def get_weather_data():
res = requests.get(url).json()
# res.encoding = 'utf-8'
result = res['HeWeather6'][0]['daily_forecast']
location = res['HeWeather6'][0]['basic']
city = location['parent_city'] + location['location']
names = [' City ', ' Time ', ' weather condition ', ' Maximum temperature ', ' Minimum temperature ', ' sunrise ', ' Sunset ']
with open('today_weather.csv', 'w', newline='')as f:
writer = csv.writer(f)
writer.writerow(names)
for data in result:
date = data['date']
cond = data['cond_txt_d']
max = data['tmp_max']
min = data['tmp_min']
sr = data['sr']
ss = data['ss']
writer.writerows([(city, date, cond, max, min, sr, ss)])
send_email()
def send_email():
# Set the domain name of the mailbox
HOST = 'smtp.qq.com'
# Set the subject line
SUBJECT = '%s Daily weather forecast information , Enclosed please find '%today_time
# Set the sender's mailbox
FROM = '[email protected]'
# Set up the recipient mailbox
TO = '[email protected],[email protected]' # It can be sent to multiple email addresses at the same time
message = MIMEMultipart('related')
# -------------------------------------- Send text -----------------
# Send the email body to the other party's mailbox
message_html = MIMEText("%s The daily weather forecast has arrived , Enclosed please find " % today_time, 'plain', 'utf-8')
message.attach(message_html)
# ------------------------------------- Add files ---------------------
# today_weather.csv This file
message_xlsx = MIMEText(open('today_weather.csv', 'rb').read(), 'base64', 'utf-8')
# Set the name of the file in the attachment
message_xlsx['Content-Disposition'] = 'attachment;filename="today_weather.csv"'
message.attach(message_xlsx)
# Set the email sender
message['From'] = FROM
# Set up mail recipients
message['To'] = TO
# Set the subject line
message['Subject'] = SUBJECT
# Get a certificate for the Simple Mail Transfer Protocol
email_client = smtplib.SMTP_SSL(host='smtp.qq.com')
# Set the domain name and port of the sender's mailbox , Port is 465
email_client.connect(HOST, '465')
# --------------------------- Email authorization code ------------------------------
result = email_client.login(FROM, ' Your authorization code ')
print(' Login results ', result)
email_client.sendmail(from_addr=FROM, to_addrs=TO.split(','), msg=message.as_string())
# Turn off the email sending client
email_client.close()
get_weather_data()
It's called code deployment , In other words, copy the code to the server , Then let the code run .
Here we'll use a toss and throw linux Knowledge .
This is an easy step , Copy and paste directly .
Create a sum python Files in the same folder startup.sh file ( Name at will ), And then in startup.sh Fill in the document with
python3 ./python File name # Remember / There's a little bit ahead .
And then again /etc/crontab Fill in stratup.sh The path of the file can be .
Now that you've learned to send the weather forecast , How about sending a voice or short video every day ? , With customized loliyin , Yu Jie Yin sends the voice of weather forecast information to the other party or attaches a short video , Beauty is not true ?? Click the link below to jump to , Study diy Voice and how to get short video .
Click through :【 It's a wonderful trick 】 series -Python Realization Voice to text ?? no !! It's text to speech ,DIY The loliyin you want !!!
Click through : Super simple !!! utilize python Download some audio and video without watermark
above , You can do it with your hands , Every day 8 I got the latest weather forecast on time .
If you're too lazy to do it , You can try to leave your mailbox + City ( I won't do it for you anyway )
This sharing is here . If you have any questions, please leave a message below .