Таким образом, у меня есть этот код ниже, который показывает количество раз, когда электронные письма были отправлены на определенный адрес электронной почты (из списка электронных писем, сохраненных в Google Sheet), и он подсчитывает значение в различных сеансах, которые выполняет код. Значения хранятся в файле JSON.
Есть ли способ, которым я могу вывести sh эти значения из файла JSON в Google Sheet напрямую из Python. Я хочу сделать это без использования Pandas данных и функции IMPORT JSON в листе Google.
Как новичок ie в программировании и Python, я пытался исследовать это, но зашел в тупик. Любая помощь ценится за это.
import gspread
from oauth2client.service_account import ServiceAccountCredentials
# login & open sheet sheets
scope = ["https://spreadsheets.google.com/feeds", 'https://www.googleapis.com/auth/spreadsheets',
"https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive"]
credentials = ServiceAccountCredentials.from_json_keyfile_name('my-jsonfile.json', scope)
client = gspread.authorize(credentials)
sheet3 = client.open('Dashboard').worksheet('Sheet3') # Open the spreadsheet
sheet1 = client.open('Dashboard').worksheet('Sheet1') # Open the spreadsheet
sheet4 = client.open('Dashboard').worksheet('Sheet4') # Open the spreadsheet
###Countup ###########
import smtplib
import ssl
from email.mime.text import MIMEText # New line
from email.utils import formataddr # New line
# User configuration
sender_email = 'email'
sender_name = 'username'
password = "password"
x = sheet3.row_values(4)
c = len(sheet1.col_values(8))
cell = ("")
from collections import Counter
import json
counter_file_path = "counter.json"
try:
with open(counter_file_path, "r") as f:
email_stats = json.load(f)
except FileNotFoundError as ex:
email_stats = {}
successful_emails = []
for x in range (4, c):
names = sheet3.cell(x + 1, 6).value
emails = sheet3.cell(x + 1, 8).value
if names == cell and emails == cell:
print("no_data")
else:
receiver_names = list(names.split())
receiver_emails = list(emails.split())
# Email text
email_body = '''
This is a test email sent by Python. Isn't that cool?
'''
for receiver_email, receiver_name in zip(receiver_emails, receiver_names):
print("Sending the email...")
# Configurating user's info
msg = MIMEText(email_body, 'plain')
msg['To'] = formataddr((receiver_name, receiver_email))
msg['From'] = formataddr((sender_name, sender_email))
msg['Subject'] = 'Hello, my friend ' + receiver_name
try:
# Creating a SMTP session | use 587 with TLS, 465 SSL and 25
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
# Encrypts the email
context = ssl.create_default_context()
server.starttls(context=context)
# We log in into our Google account
server.login(sender_email, password)
# Sending email from sender, to receiver with the email body
server.sendmail(sender_email, receiver_email, msg.as_string())
print('Email sent!')
successful_emails.append(receiver_email)
if receiver_email in email_stats:
email_stats[receiver_email] += 1
else:
email_stats[receiver_email] = 1
except Exception as e:
print(f'Oh no! Something bad happened!n {e}')
finally:
print('Closing the server...')
server.quit()
# counter = Counter(successful_emails)
# print(counter)
print(email_stats) # output - all occurrences for each email
with open(counter_file_path, "w") as f:
results = json.dump(email_stats, f)
Результаты файла JSON: {"receiver_emails_1": 6, "receiver_emails_2": 6}