Set message header value for to
also as:
msg['to'] = "someone@somesite.com"
You may have to populate that value from the to
list that you've read from the file. So you may have to iterate over all the values either one at a time or all of them together, structuring it how your mail provider supports it.
Something like:
#!/usr/bin/python
# -*- coding= utf-8 -*-
SMTPserver = ''
import sys
import os
import re
import email
from smtplib import SMTP
from email.MIMEText import MIMEText
body="""\
hello
"""
with open("email.txt") as myfile:
lines = myfile.readlines(500)
to = [line.strip() for line in lines]
for to_email in to:
try:
msg = MIMEText(body.encode('utf-8'), 'html', 'UTF-8')
msg['Subject'] = 'subject'
msg['From'] = email.utils.formataddr(('expert', 'mymail@site.com'))
msg['Content-Type'] = "text/html; charset=utf-8"
msg['to'] = to_email
conn = SMTP(SMTPserver)
conn.set_debuglevel(False)
conn.login('info', 'password')
conn.sendmail(msg.get('From'), to, msg.as_string())
except Exception, exc:
sys.exit( "mail failed; %s" % str(exc))
finally:
conn.close()
There is no need to have nested
try
blocks.You may create the connection outside the loop and keep it open until all the mails are sent and close it afterwards.
This is not a copy-paste code, I haven't tested it too. Please use it to implement a suitable solution.