Send email to multiple recipients from a .txt file using Python smtplib

I am trying to send letters from python to several email addresses imported from a TXT file, I tried different syntaxes, but nothing worked ...

The code:

s.sendmail('sender@mail.com', ['recipient@mail.com', 'recipient2@mail.com', 'recipient3@mail.com'], msg.as_string())

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

urlFile = open("mailList.txt", "r+")
mailList = urlFile.read()
s.sendmail('sender@mail.com', mailList, msg.as_string())

The mainList.txt file contains:

['recipient@mail.com', 'recipient2@mail.com', 'recipient3@mail.com']

But this does not work ...

I also tried:

... [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 know what to do?

Thank you so much!

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

and put each recipient on its own line (i.e. split by line break).

+3
source

, . , ":" , , sendmail .

# list of emails
emails = ["banjer@example.com", "slingblade@example.com", "dude@example.com"]

# 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() )
+34

sendmail , .

, , eval(), .

+2

. , :

recipient@mail.com,recipient2@mail.com,recipient3@mail.com

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

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

Providing all recipients with a functional call, you also need to send a list of identical recipients in msg as a comma-separated text format for each type of recipient. (K, cc, bcc). But you can do it easily, but you support either separate lists, or concatenate or convert strings to lists.

Here are some examples

TO = "1@to.com,2@to.com"
CC = "1@cc.com,2@cc.com"
msg['To'] = TO
msg['CC'] = CC
s.sendmail(from_email, TO.split(',') + CC.split(','), msg.as_string())

or

TO = ['1@to.com','2@to.com']
CC = ['1@cc.com','2@cc.com']
msg['To'] = ",".join(To)
msg['CC'] = ",".join(CC)
s.sendmail(from_email, TO+CC, msg.as_string())
0
source

All Articles