Send Email to multiple recipients from .txt file with Python smtplib

16,874

Solution 1

urlFile = open("mailList.txt", "r+")
mailList = [i.strip() for i in urlFile.readlines()]

and put each recipient on its own line (i.e. separate with a line break).

Solution 2

This question has sort of been answered, but not fully. The issue for me is that "To:" header wants the emails as a string, and the sendmail function wants it in a list structure.

# list of emails
emails = ["[email protected]", "[email protected]", "[email protected]"]

# Use a string for the To: header
msg['To'] = ', '.join( emails )

# Use a list for sendmail function
s.sendmail(from_email, emails, msg.as_string() )

Solution 3

The sendmail function requires a list of addresses, you are passing it a string.

If the addresses within the file are formatted as you say, you could use eval() to convert it into a list.

Solution 4

It needs to be a real list. So, with this in the file:

[email protected],[email protected],[email protected]

you can do

mailList = urlFile.read().split(',')

Solution 5

to_addrs in the sendmail function call is actually a dictionary of all the recipients (to, cc, bcc) and not just to.

While providing all the recipients in the functional call, you also need to send a list of same recipients in the msg as a comma separated string format for each types of recipients. (to,cc,bcc). But you can do this easily but maintaing either separate lists and combining into string or convert strings into lists.

Here are the examples

TO = "[email protected],[email protected]"
CC = "[email protected],[email protected]"
msg['To'] = TO
msg['CC'] = CC
s.sendmail(from_email, TO.split(',') + CC.split(','), msg.as_string())

or

TO = ['[email protected]','[email protected]']
CC = ['[email protected]','[email protected]']
msg['To'] = ",".join(To)
msg['CC'] = ",".join(CC)
s.sendmail(from_email, TO+CC, msg.as_string())
Share:
16,874
Francis Michels
Author by

Francis Michels

Updated on June 19, 2022

Comments

  • Francis Michels
    Francis Michels almost 2 years

    I try to send mails from python to multiple email-addresses, imported from a .txt file, I've tried differend syntaxes, but nothing would work...

    The code:

    s.sendmail('[email protected]', ['[email protected]', '[email protected]', '[email protected]'], msg.as_string())
    

    So I tried this to import the recipient-addresses from a .txt file:

    urlFile = open("mailList.txt", "r+")
    mailList = urlFile.read()
    s.sendmail('[email protected]', mailList, msg.as_string())
    

    The mainList.txt contains:

    ['[email protected]', '[email protected]', '[email protected]']
    

    But it doesn't work...

    I've also tried to do:

    ... [mailList] ... in the code, and '...','...','...' in the .txt file, but also no effect
    

    and

    ... [mailList] ... in the code, and ...','...','... in the .txt file, but also no effect...
    

    Does anyone knows what to do?

    Thanks a lot!