如何将json中的信息发送到电子邮件?

时间:2019-03-13 21:17:12

标签: python email automation

from dataclasses import dataclass
from operator import attrgetter
import urllib.request
import json
import datetime
import matplotlib.pyplot as plt
import smtplib

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('myemail@gmail.com', 'mypassword')
#rcvr = input('Where do you want to recieve email?')
server.sendmail('sender@gmail.com','reciever@gmail.com' , i need to send quake info here)

#Creating a dataclass with all the info that we gonna use
@dataclass 
class Feature:
    place: str
    long: float
    lat: float
    depth: float
    mag: float

    #Predefyning the variable that are gonna hold info from our json file    
    @classmethod
    def get_json(cls, featurejson):
        place = featurejson["properties"]["place"] #Location
        long, lat, depth = map(float, featurejson['geometry']['coordinates'])             
        #Longitude, latitude, and depth
        mag = float(featurejson["properties"]["mag"]) #Magnitude
        return cls(place, long, lat, depth, mag)

#Getting information from the json file URL 
def get_info(url = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/significant_week.geojson"):
with urllib.request.urlopen(url) as resp:
    data = json.loads(resp.read())

for feature in data["features"]:
    yield Feature.get_json(feature)

#Displaying the info in text format for now,s        
def show_info(features):
for feat in sorted(features, key=attrgetter("mag"), reverse = True):#Sorting by the magnitude in the reversed order
    print(feat)#Printing the result

#Drawing the plot        
def showplot(features):
    loc = [feat.place for feat in sorted(features, key=attrgetter("mag"))]#Location
    magn = [feat.mag for feat in features] #Magnitude
    y_pos = range(len(magn))

    plt.bar(y_pos, magn)
    plt.xticks(y_pos, loc)
    plt.ylabel('Magnitude')
    plt.show()


features = list(get_info()) #Storing our json information into a list 'Features'
show_info(features) #Displaying information in text format
showplot(features) #Displaying information in format of a plot

我的代码在上面,我需要一种将地震信息发送到用户将输入的电子邮件的方法,我可以发送简单的消息,但我想不出一种仅发送有关地震信息(又称为“功能”)的方法。我能想到的唯一方法是将信息写到文件上,然后将该文件附加到电子邮件中,但是步骤太多,对于接收者来说并不令人满意。

如何从我已经从json提取的代码中仅发送包含信息的电子邮件?

0 个答案:

没有答案