整个代码 github 链接
linjie111/sendEmailWithWeather (github.com)https://github.com/linjie111/sendEmailWithWeather#readme
目录
main.py
import smtplib
from email.mime.text import MIMEText
from email.header import Header
def send(text):
# 这里使用的是163.com
mail_host = "smtp.163.com" # 设置服务器
mail_user = "*******@163.com" # 用户名
mail_pass = "******" # 口令 邮箱密码
sender = '*****@163.com' #发送邮箱 和上方用户名一致
receivers = ['***@163.com'] # 接收者的邮箱
message = MIMEText(text, 'plain', 'utf-8')
message['From'] = Header('wanglin')
message['To'] = Header("toyou")
subject = 'python send email'
message['Subject'] = Header(subject, 'utf-8')
try:
smtpObj = smtplib.SMTP()
print(1)
smtpObj.connect(mail_host, 25) # 25 为 SMTP 端口号
print(2)
smtpObj.login(mail_user, mail_pass)
print(3)
smtpObj.sendmail(sender, receivers, message.as_string())
print("邮件发送成功")
except smtplib.SMTPException:
print("Error: 无法发送邮件")
weather.py
注意 : 这是我个人的账户,每天只能调用30000次
import requests, json
# notice api地址
import CalDate
url = 'http://t.weather.sojson.com/api/weather/city/'
# weather api
response = requests.get(url + '101250101') # 城市编号,可以根据github 中的city.json中自行选择
r = requests.get('https://restapi.amap.com/v3/weather/weatherInfo?city=430121&key=b99f40bd4e3f03a9f66f1e04acbfa91a&extensions=all')
r.encoding='utf-8'
cc = r.json()
city = cc['forecasts'][0]['province']+cc['forecasts'][0]['city']
nowTime = cc['forecasts'][0]['reporttime']
weather = "白天 :"+cc['forecasts'][0]['casts'][0]['dayweather'] +" 晚上 :"+cc['forecasts'][0]['casts'][0]['nightweather']
tem = cc['forecasts'][0]['casts'][0]['nighttemp']+"°c ~ "+cc['forecasts'][0]['casts'][0]['daytemp']+"°c"
#将数据以json形式返回,这个d就是返回的json数据
d = response.json()
#当返回状态码为200,输出天气状况
if(d['status'] == 200):
notice = d["data"]["forecast"][0]["notice"]
time = "我和迪哥的第 "+ str(CalDate.Cal_Date()) + " day "
calDate.py
import datetime
def Cal_Date():
First_Day_We_Loved = datetime.datetime(2022, 4, 26)
Today = datetime.datetime.now()
The_Day_We_Loved = Today - First_Day_We_Loved
return The_Day_We_Loved.days
main.py
from timeit import Timer
from email163 import send
import Weather
import laugh
city = Weather.city
nowTime = Weather.nowTime
weather = Weather.weather
tem = Weather.tem
notice = Weather.notice
time = Weather.time
print(city)
print(nowTime)
print(weather)
print(tem)
print(notice)
print(time)
text = city + '\n' + '\n' + nowTime + '\n' + '\n' + weather + '\n' + '\n' + tem + '\n' + '\n' + notice + '\n' + '\n' + time
send(text)