У меня есть базовый код Python, который отправляет электронное письмо на адреса из списка в листе Google.

Я хочу посчитать, сколько раз электронное письмо отправлялось на определенный адрес электронной почты скриптом 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()
0
Sourav Chatterjee 12 Апр 2020 в 22:20

2 ответа

Вы можете использовать этот код для хранения / печати количества успешных писем в формате JSON.

import smtplib
import ssl
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):
    print("Creating a JSON file to store the data")       
    print("a JSON file has been created with name: " + fileName)
    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.
# with open(fileName) as jsonFile:
#     success_mail_count = json.load(jsonFile)
# print(success_mail_count)
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] = 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] = 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)
# if you want to store data into file you can use this funtion
store_data_to_file(success_mail_count)

Запустите этот код, как только он создаст данные в файл, а затем раскомментируйте

# with open(fileName) as jsonFile:
#     success_mail_count = json.load(jsonFile)
# print(success_mail_count)

Комментарий success_mail_count = {} поэтому он будет читать данные из файла для дальнейшей обработки. Я также преобразовал счет в строку.

1
Shivam Singh 13 Апр 2020 в 08:26

Я бы предложил вам создать список успешных электронных писем, которые будут заполняться на каждой итерации, а затем использовать модуль Counter из collections, который получает итерацию и возвращает объект с числом вхождений каждого элемент в повторяемом. Вы можете попробовать следующий код:

from collections import Counter
import json

counter_file_path = "counter.json"
with open(counter_file_path, "r") as f:
    email_stats = json.load(f)

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)
0
Gabip 13 Апр 2020 в 07:03