pythonpython-3.xemailsmtplibmail-sender

I want my python script to send emails 1 by 1 from email list (like 1st done then repeat task and go to second until finish)


I want my task to be 1 by 1 not bulk so I'm sending from list of emails. I want it sending to first one then repeats task and sends to second one. The code already works properly but it sends as bulk all emails together so when recipient gets the email it's like all the emails list included in header. That's why I want it to send it one by one from my list.

import smtplib, ssl
from time import strftime
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from colorama import *
from datetime import datetime


context = ssl.create_default_context()

def get_contacts(filename):
    
    emails = []
    with open(filename, mode='r', encoding='utf-8') as contacts_file:
        for a_contact in contacts_file:
            emails.append(a_contact.split()[0])
    return emails

mails = get_contacts('smtp/contacts.txt')


smtp_user = 'mYsmtp@smtp.com'

def smtp(smtp_server, port, user, password):
    
    
        context = ssl.create_default_context()
        with smtplib.SMTP_SSL(smtp_server, port) as server:
            try:
                 message = MIMEMultipart('alternative')
                 
                 
                 message['Subject'] = 'TESTING'
                 message['From'] = str(Header(f'INFO <{smtp_user}>'))
                 message['To'] = ', '.join(mails)
                
                
                 myfile = open('smtp/letter.txt', 'r')      
                 data = myfile.read()
                 part = MIMEText(data, 'html')
                 message.attach(part)
                
                 now = datetime.now()
                 current_time = now.strftime("%H:%M:%S")
   
                 server.login(user, password)
                 server.sendmail(user, mails, message.as_string())
                 for email in mails:
                    print('\n',email + ''' SENT! ''')
            except smtplib.SMTPAuthenticationError or smtplib.SMTPConnectError :
                 print('Dead SMTP')    

Solution

  • Response:

    You just have to move put inside your for email in mails:

    for email in mails:
        print('\n',email + ''' SENT! ''')
        message['To'] = email
        server.sendmail(user, mails, message.as_string())
    

    Remove from your original script:

    message['To'] = ', '.join(mails)
    

    and

    server.sendmail(user, mails, message.as_string())
    
    Notes: