количество сообщений, отправленных с использованием smtplib python - PullRequest
1 голос
/ 12 апреля 2020

У меня есть базовый c 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()

Ответы [ 2 ]

2 голосов
/ 12 апреля 2020

Вы можете использовать этот код для хранения / печати количества успешных писем в формате 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)

запустите этот код, и он создаст данные в файл, а затем будет считывать данные из самого файла .

1 голос
/ 12 апреля 2020

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

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)
...