I tried to write a script that automatically sends email to a list of email addresses, and want to customize the body content a bit differently using formatter as below:
<html>
Hello {name}, it is me
</html>
So I wrote below script referring to this and had no problem sending the emails to each receivers - but the problem is that email body content accumulates as the number of receiver increases. For example 4th receiver in the list ends up getting an email with 4 body contents, a summation of 1st, 2nd and 3rd receiver's email content. Why is this happening and how can I fix this?
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import time
import random
fromaddr = "sender_gmail_account"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['Subject'] = "Subject_line"
#list of receivers
s = open("list.txt", "r")
emails = s.readlines()
print emails
s.close()
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "gmail_password")
for address in emails:
address = address.strip().split(",") # Removing White spaces.
toname = address[0]
toaddr = address[1].strip()
if toaddr == "":
continue
f = open('mail_template.html')
body = f.read()
f.close()
msg['To'] = toaddr
body = body.format(name=toname)
msg.attach(MIMEText(body, 'html'))
text = msg.as_string()
body = ""
server.sendmail(fromaddr, toaddr, text)
rand = random.randrange(2,5) # Set range of the waiting time.
time.sleep(rand)
server.quit()