I'm trying to send email to multiple people using Python.
def getRecipients(fileWithRecipients):
recipients = []
f = open(fileWithRecipients, 'r')
for line in f:
recipients.append(line)
return recipients
def test_email():
gmail_user = "csarankings@gmail.com"
gmail_pass = getPassword("pass.txt")
FROM = "csarankings@gmail.com"
TO = getRecipients("recipients.txt")
date = getCurrentDate()
SUBJECT = "Current CSA Rankings: " + date
TEXT = createEmailMessageFromFile("rankings.txt")
message = """\From: %s\nTo: %s\nSubject: %s\n\n%s """ % (FROM, ", ".join(TO), SUBJECT, TEXT)
try:
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login(gmail_user, gmail_pass)
server.sendmail(FROM, TO, message)
server.close()
print("it worked")
except:
print("it failed :(")
For whatever reason, my emails only go to the first recipient in my list of recipients (the TO
variable within my test_email()
function.
My recipients file just consists of an email address per line (only has two in there at the moment). I thought there might be something wrong with my getRecipients() function, so I just hardcoded two emails into the TO
variable and it works for the first email address and not the second.
Any idea why this might be happening? I suspect it has something to do with:
", ".join(TO)
where I set my message
variable.
NB: My test_email()
is largely based on the most upvoted answer here:
How to send an email with Gmail as provider using Python?
EDIT: For what it's worth, when I hardcode a list of a single email address into the TO variable, the subject displays properly in the email. When I use the getRecipients() function (even with only one email address in the recipients.txt file), it displays this in the body of the email:
Subject: Current CSA Rankings 6/13/15
Not sure if relevant but thought it might be related to the issue.
EDIT_2: I don't think my question is a duplicate of:
How to send email to multiple recipients using python smtplib?
because, while I use the smtplib.sendmail()
function, I don't use the email module at all, so our code is very different...