Sent email using Python for different users

Hi, I am receiving an email showing the list of tables. And in that table, example lets say 5 rows , and in that 5 rows i have to sent email to different 5 person but same domain. example all email using gmail.com

How to achieve this using python?

Welcome aboard! I’m fairly new to Python as well.

  1. Please provide a sample of the table you are referring to so we can have an idea what the data looks like.
  2. You send email with an SMTP server. Have you gotten the SMTP server info for Gmail? You will need the SMTP server name, an SMTP username, an SMTP password. Here is how it’s done from 2024. How to Set Up and Configure Gmail SMTP to Send Emails [2024]

I have a function to send SMTP email so it’s not hard.

This is the typical template i receiving via email. then next step i copy paste this info this into excel file. so using this excel file i have to sent email to the respective person based on the email i provided here

@c-rob pls see above.

Pls note that i am using company email to sent this alert notification not a normal gmail.

Here are the general steps.

  1. Read the Excel file.
  2. For each row in the Excel file get the email address.
  3. Send an email via SMTP for that address.

Do you know how to do any of these steps? Have you done tutorials on these steps? We don’t write whole programs here unless they are short. But we can help you with snippets of code.

Do you need to send attachments with the email? That adds a little more code.

thanks for the reply greatly appreciate it. i am new to python and quite struggling in this requirement. I am using jupyter notebook , i know how to import excel file using panda.

Ok I made a program with an email function you can plug into your program. Use this as a test program to make sure you can get things to work before you integrate the function into your app.

""" Test emailsendg()
Created 4/30/2024 


See this page to use Gmail SMTP server. You need to set things up on the Gmail site first. https://mailtrap.io/blog/gmail-smtp/

"""

import inspect
import os
import re
import sys
import glob # To get list of files.

VER = '1.0.0' # App version. 



#####################################################
# Functions
#####################################################
def emailsendg(fromaddr, toaddr, subject, msgbody, files, smtplogfn, otherdict): 
    r'''Function: emailsendg
    PARAMETERS IN: 
    - fromaddr = REQUIRED. one single valid email address as a string.
    - toaddr = REQUIRED. string, list of valid email addresses separated by commas. Add last comma to make a tuple. 
    - subject = REQUIRED. string for subject.
    - msgbody = REQUIRED. string with CRLF for body of message. 
    - files = list of files or blank. For no files do "filelist = list()". Each file must have a complete path and look like: 'c:\\fullpath\\myprog/done/myfile.xlsx' with slash as last separator.
    - smtplogfn = Optional. full path and filename to log. 
    - otherdict = REQUIRED. has info for SMTP server from main program with keys: 
        'smtpserver', 'smtpport', 'smtpuser', 'smtppw'

    PARAMETERS OUT: 
    errmsg = an error message. Blank message = no error. 
    
    NOTE: This uses TLS to send email. 
    ''' 
    procname = str(inspect.stack()[0][3]) + ":"
    # Importing the Required Libraries
    print("\n")
    print(procname,"Constructing email to %s..." % (toaddr,))
    
    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email.mime.base import MIMEBase
    from email import encoders
    import time
    # import dotenv

    errflag = False
    err = '' # Error message
    
    # Check if toaddr is a string.
    if not isinstance(fromaddr,str):
        print(procname, "ERROR-notstring: parameter 'fromaddr' should be a string not something else")
        errflag = True
    if not isinstance(toaddr,str):
        print(procname, "ERROR-notstring: parameter 'toaddr' should be a string not something else")
        errflag = True
    if not isinstance(msgbody,str):
        print(procname, "ERROR-notstring: parameter 'msgbody' should be a string not something else")
        errflag = True
    if not isinstance(files,list):
        print(procname, "ERROR-notlist: parameter 'files' should be a list not something else")
        errflag = True
    if not otherdict: 
        print(procname, "ERROR-nootherdict: parameter 'otherdict' is required.")
        errflag = True
        
    if errflag: # Exit on any error. 
        sys.exit()

    smtpserver = otherdict['smtpserver']
    smtpport = otherdict['smtpport']
    smtpuser = otherdict['smtpuser']
    smtppw = otherdict['smtppw']

    if len(smtppw)==0:
        print(procname,"\nERROR-nosmtppw: No SMTP password was found.")
        sys.exit()
        
    # First check if all attachable files exist. 
    for fn in files: 
        if not exists(fn): 
            print(procname,f"\nERROR: File '{fn}' does not exist. Please check for typos.")
            errflag = True
        if '/' not in fn: 
            print(procname,f"\nERROR-noslash: files must end with a slash as the last separator. {fn}")
            errflag = True
    if errflag: 
        sys.exit(procname + " Stopping program. Email not sent.")
            
    # Creating the Email Object
    # print(procname,"Sending email to",toaddr)
    exitflag = False
    message = MIMEMultipart()
    message["From"] = fromaddr
    message["To"] = toaddr # This must be a string!
    message["Subject"] = subject
    message.attach(MIMEText(msgbody)) # 4/15/24

    errflag = False
    for fn in files: 
        # fn = '"' + fn + '"' # Add double quotes for spaces in fn.
        # Check for .py file, Outlook won't receive it. 
        p = re.compile(r'.py$', re.IGNORECASE) 
        m = p.search(fn) # Match ctrs anywhere in this string
        if m:
            print(procname,"WARNING-pyfile: .py files will be blocked by Outlook. Sending file %s anyway." % (fn))
            time.sleep(3)
        # Attach the file using the MIMEBase class.
        # We need full filepath for this to work.
        print(procname,f"Attaching file: %s" % (fn))
        attachment = open(fn, "rb") # Make attachment object.
        part = MIMEBase("application", "octet-stream") # Make payload object.
        part.set_payload((attachment).read())
        encoders.encode_base64(part)
        # DEBUG
        tfn = fn.split(r'/')[-1] # Windows only. Get just base filename with no path.
        if ' ' in tfn: 
            print(procname,f"ERROR-fnspace1: Filenames cannot have spaces. {tfn}")
            errflag = True
        if len(tfn)==0: 
            print(procname,f"ERROR-notfn: Could not find base filename in the file '{fn}'")
            errflag = True
        part.add_header("Content-Disposition", f"attachment; filename={tfn}") # Use quote around tfn?
        message.attach(part)
    if errflag: 
        sys.exit(procname + " ERROR: Message not sent due to errors.")

    print(procname,'Sending SMTP email to %s...' % (toaddr))
    try: 
        with smtplib.SMTP(smtpserver, smtpport) as server:
            server.starttls()
            server.login(smtpuser, smtppw)
            server.send_message(message)
    except Exception as e:
        print(procname,f"ERROR-smtpsend: error was {e}")
        return(e) # Return the error.
     
    tstr = [str(item) for item in files]
    mystr = ', '. join(tstr)
    mymsg = "Sent email to %s with files %s" % (toaddr,mystr)
    
    if smtplogfn: 
        # Now log error message in logsmtp.txt.
        file = open('logsmtp.txt', 'a') # Open a text file.
        # \n needed before new line is added. 
        content = '\n' + mymsg # \n is CRLF.
        file.write(content)
        file.close() # Always close file when done.

        return '' # Success = no error message.
        

#####################################################
# Main program
helpstr = r'''Generic send email with support for multiple attachments.
When sending files, each file in the files var must be in the same directory as this program or just pass in the full path to the file. 
'''

# Do stuff here.
smtpdict = {'smtpserver': 'my.smtp.com', # Put server name here. 
'smtpport': 587, # Use 587 to TLS 
'smtpuser': 'youremail@gmail.com', 
'smtppw': 'enter_password_here'}

fromaddr = "myemail@somwhere.com"
toaddr = "boss@gmail.com"
subject = "My test email subject"
msgbody = "This is line 1 of body.\nThis is line 2 of body.\nHave a nice day."
files = [] # No files to attach.
smtplogfn = ""

msg = emailsendg(fromaddr, toaddr, subject, msgbody, files, smtplogfn, smtpdict)

if not msg: 
    print("Success! The email was sent.")
else: 
    print(f"Email not sent.")

thanks for reply.
I did something like this
import pandas as pd
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_email(sender_email, sender_password, receiver_email, subject, body):
msg = MIMEMultipart()
msg[‘From’] = sender_email
msg[‘To’] = receiver_email
msg[‘Subject’] = subject

msg.attach(MIMEText(body, 'plain'))

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender_email, sender_password)
text = msg.as_string()
server.sendmail(sender_email, receiver_email, text)
server.quit()

Replace these values with your actual SMTP server details

smtp_server = “smtp.gmail.com
smtp_port = 587
sender_email = “assume i type email”
sender_password = “assumy i type password”

Read the Excel file

#excel_file_path = r"C:\Users\ta0907\OneDrive - MISC Group\Desktop\Alert Email.xlsx"

df = pd.read_excel(r"C:\path file.xlsx")
#df = pd.read_excel(excel_file_path)

Iterate through each row in the DataFrame

for index, row in df.iterrows():
email_address = row[‘Email’] # Assuming ‘Email’ is the column containing email addresses
subject = “Your subject here”
body = “Your email body here”

try:
    send_email(sender_email, sender_password, email_address, subject, body)
    print(f"Email sent successfully to {email_address}")
except Exception as e:
    print(f"Failed to send email to {email_address}: {str(e)}")

but the error showing

Failed to send email to millionthamim @gmail.com: (535, b’5.7.8 Username and Password not accepted. For more information, go to\n5.7.8 Can't sign in to your Google Account - Gmail Help c24-20020aa78818000000b006f319bdcfbesm13877525pfo.132 - gsmtp’)

  1. The username is the email and it has a space in it. millionthamim @gmail.com
  2. The error means either the username or password was wrong. Check the case of the password and make sure you didn’t confuse a letter ‘O’ with a zero, or number one with a lowercase ‘ell’.

You can paste the password into a text editor that uses a fixed-width font, fixed width fonts are better for telling similar letters apart.