Pucho
Pucho

Reputation: 380

properly format string of emails using python

I have a piece of code that extracts the email addresses from a list and adds them to the 'To' field in the MIME service. Only the very first recipient gets the email due to a misconstrued email list.

The 'list.csv' file looks like this

[email protected]
[email protected]

The code I'm using to format the addresses is this:

with open('list.csv') as allusers:
        concat_out =', '.join(email for (email,) in csv.reader(allusers))
receiver = [concat_out]

MIME part:

msg = MIMEMultipart()
msg['Subject'] = 'Notification'
msg['From'] = sender
msg['To'] = '; '.join(receiver)

Output:

['[email protected], [email protected]'] #notice the missing quotes and a comma
                                               #instead of a semi-colon

How can I get the list properly formatted to look like this?:

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

Any help is appreciated.

Upvotes: 0

Views: 200

Answers (3)

Vikas Sharma
Vikas Sharma

Reputation: 461

email_list = []
with open('list.csv', 'r') as file:
   for line in file.readlines():
       email_list.append(line.strip('\n'))

print(email_list)

Output: ['[email protected]', '[email protected]']

Upvotes: 0

Fsoc
Fsoc

Reputation: 182

This will solve your issue without touching the old code

with open('list.csv') as allusers:
        concat_out =', '.join(email for (email,) in csv.reader(allusers))
reciever=concat_out.split(',')
print(reciever)

output: ['[email protected]', ' [email protected]']

Upvotes: 1

D Dhaliwal
D Dhaliwal

Reputation: 552

Why not just create a list and then make a string from the list.

with open('list.csv') as allusers:
        concat_out = [email for (email,) in csv.reader(allusers)]
receiver = str(concat_out)

This will give you an output like:

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

Upvotes: 0

Related Questions