Skip to content Skip to sidebar Skip to footer

How To Send Different Content Email To Different Recipient In Python?

I am writing a python script to help a friend's after-school program to send tuition bill to parents. I have student tuition in a {studentName, tuition} dict, and parent contacts

Solution 1:

You are adding another body part each time through the loop. So the first parent receives only their own body part, the second parent receives two body parts, the first of which is that of the previous student, etc. By the end of the loop, the last parent receives n different body parts, where the last one is actually theirs, but they also receive those of all the previous students.

I would simply move the msg = MimeMultipart() etc initialization inside the loop; recycling an empty multipart is a dubious optimization anyway (and of course as of now, the one you were recycling wasn't empty).

If you are only sending a single part, putting it inside a multipart container is pointless, anyway.

def send_mail(studentParentContact, studentTuition):
    s = smtplib.SMTP('smtp.gmail.com', 587)
    s.starttls()
    s.login(username, PASSWORD)

    for student in studentParentContact:    
        ParentEmail=studentParentContact[student]
        tuition=studentTuition[student]

        body="Hi, \nThe tuition for "+student+' is '+'$'+ str(tuition)
        msg=MIMEText(body, 'plain')
        msg['Subject'] = "Your Kid's After-school Program Tuition Bill"
        msg['From'] = FLPEmail    
        msg['To'] = ParentEmail

        text=msg.as_string()
        #print FLPEmail, ParentEmail, text
        s.sendmail(FLPEmail, ParentEmail, text)
    s.quit()

Having multiple dict variables with the same keys isn't a bug, but it feels a bit cluttered. A common design is to have a dict of dicts, where each record has a number of identical keys (in this case, maybe student[s]['parent_email'] to get the parent's email, student[s]['name'] to get the student's full name, student[s]['tuition'] to get the tuition fee, etc. Eventually you might want to encapsulate these as attributes of a student class.)

Post a Comment for "How To Send Different Content Email To Different Recipient In Python?"