计算使用smtplib-python发送的电子邮件数



我有一个基本的python代码,可以向谷歌工作表中的列表中的地址发送电子邮件。

我想计算python脚本向特定电子邮件地址发送电子邮件的次数。我试着研究它。我没有发现任何与之相关的东西。作为一个完全的初学者并没有帮助我取得多大进步。

如果有人能给我指明一个特别的方向,那将是非常有帮助的。提前非常感谢。

以下是代码

import smtplib
import ssl
from email.mime.text import MIMEText  # New line
from email.utils import formataddr  # New line
# User configuration
sender_email = 'email ID'
sender_name = 'name'
password = "password"
receiver_emails = [RECEIVER_EMAIL_1, RECEIVER_EMAIL_2, RECEIVER_EMAIL_3]
receiver_names = [RECEIVER_NAME_1, RECEIVER_NAME_2, RECEIVER_NAME_3]
# 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!')
except Exception as e:
print(f'Oh no! Something bad happened!n {e}')
finally:
print('Closing the server...')
server.quit()

我建议您创建一个成功的电子邮件列表,该列表将在每次迭代时填充,然后使用collections模块中的Counter,该模块接收一个可迭代项,并返回一个对象,该对象包含可迭代项中每个元素的出现次数。您可以尝试以下代码:

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 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!')
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()
print(email_stats) # output - all occurrences for each email 
with open(counter_file_path, "w") as f:
json.dump(email_stats, f)

您可以使用此代码将成功邮件计数存储/打印为JSON格式。

import smtplib
import SSL
import json
import os
from email.mime.text import MIMEText  # New line
from email.utils import formataddr  # New line
fileName = "sendMail_count.json"
# To store data into json file.
# It will create file in datetime format.
def store_data_to_file(jsonStr):
jsonFile = open(fileName, "w")
json.dump(jsonStr, jsonFile)
print("data stored successfully")
# User configuration
sender_email = 'email ID'
sender_name = 'name'
password = "password"
receiver_emails = [RECEIVER_EMAIL_1, RECEIVER_EMAIL_2, RECEIVER_EMAIL_3]
receiver_names = [RECEIVER_NAME_1, RECEIVER_NAME_2, RECEIVER_NAME_3]
# To store the count of successful mail received by receiver with their respective email.
if not os.path.exists(fileName) or os.stat(fileName).st_size == 0:
print("File is empty or not found")
print("Creating a JSON file to store the data")
jsonFile = open(fileName, "w+")
print("a JSON file has been created with name: " + str(fileName))
success_mail_count = {}
else:
with open(fileName) as jsonFile:
success_mail_count = json.load(jsonFile)
print(success_mail_count)
# 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):
count = 0
print("Sending the email to..." + receiver_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())
# Check if recevier is already present in the dict, 
# then add 1 to its current count
if receiver_email in success_mail_count:
success_mail_count[receiver_email] = str(int(success_mail_count[receiver_email]) + 1)
# If reciever isn't present in map then create new entry for receiver and 
# Update the count with one for successfull mail sent.
else:
success_mail_count[receiver_email] = str(count + 1)
print('Email sent!')
except Exception as e:
print(f'Oh no! Something bad happened!n {e}')
finally:
print('Closing the server...')
server.quit()
print(success_mail_count)
store_data_to_file(success_mail_count)

运行此代码,它将在文件中创建数据,然后从文件本身读取数据。

最新更新