1
votes

I am using smtplib and calling server_ssl.ehlo to send mail using my gmail account .I am trying to import the recipients as well as the mail body from a txt file. Also, it would be great if somebody can help me out on how to add attachment in the mail .

Here's my code :

recipients = []
names = []
f = open("listOfRecipients.txt", 'r')

recp_list = f.read().split('\n')

# load recipients from text file into a list (recipients), strip the \n from the strings
for line in recp_list:
    if len(line.split(':')) < 2:
        continue
    names.append(line.split(':')[0])
    recipients.append(line.split(':')[1])

f.close()

f1 = open('cont.txt', 'r')
msg = f1.read()
f1.close()

sub = 'Script Test - Man, am I awesome !!'

cc_recp = ['[email protected]', '[email protected]']


from_mail = ['[email protected]']
to = recipients
cc = cc_recp
#to = ['[email protected]', '[email protected]']
msg = """From: %s\nTo: %s\nCC: %s\nSubject: %s\n\n%s""" % (from_mail, ", ".join(to), ', '.join(cc), sub, msg)
server_ssl.sendmail(from_mail, to, msg)
#server_ssl.quit()
server_ssl.close()
print 'successfully sent the mail'

However, I get the following error each time I run. Note : The mails are going file if I mention the 'To' email ids(commented out here) in the code body instead of calling from a txt file.

File "mail_sender.py", line 37, in <module>
    server_ssl.sendmail(from_mail, to, msg)
  File "/usr/lib/python2.7/smtplib.py", line 747, in sendmail
    raise SMTPRecipientsRefused(senderrs)
smtplib.SMTPRecipientsRefused: {}
1

1 Answers

0
votes

I know this is an old question, but I stumbled upon this. Make sure you are using the correct encoding on your txt file.