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

count number of emails sent using smtplib python

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

我想计算 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,该模块接收可迭代的 returns 一个对象,其中包含可迭代对象中每个元素的出现次数。 您可以试试下面的代码:

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)

您可以使用此代码将 store/print 成功邮件计数转换为 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)

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