Error in python while trying to send emails using SMTP












0















I was unable to find an answer to this error on the existing questions so here it goes.
I'm trying to send an email to a list of email addresses imported from an CSV file using Python, gmail and the smtplib library.
This is the code:



import smtplib
import csv

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

MY_ADDRESS = 'myemailaddress'
PASSWORD = 'mypassword'

def get_contacts(filename):
"""
Return email addresses read from a file specified by filename.
"""

emails =
with open(filename, newline='') as contacts_file:
emailreader = csv.reader(contacts_file, delimiter=' ', quotechar='|')
for a_contact in emailreader:
emails.append(a_contact)
return emails


def main():
emails = get_contacts('mycontacts.csv') # read contacts
message_template = """Test message goes here"""

# set up the SMTP server
s = smtplib.SMTP(host='smtp.gmail.com', port=587)
s.starttls()
s.login(MY_ADDRESS, PASSWORD)

# For each contact, send the email:
for email in zip(emails):
msg = MIMEMultipart() # create a message

# add in the actual person name to the message template
message = message_template

# Prints out the message body for our sake
print(message)

# setup the parameters of the message
msg['From']=MY_ADDRESS
msg['To']=email
msg['Subject']="This is TEST"

# add in the message body
msg.attach(MIMEText(message, 'plain'))

# send the message via the server set up earlier.
s.send_message(msg)
del msg

# Terminate the SMTP session and close the connection
s.quit()

if __name__ == '__main__':
main()


I get the following error:



Traceback (most recent call last):
File "py_mail.py", line 58, in <module>
main()
File "py_mail.py", line 51, in main
s.send_message(msg)
File "/home/hugo/anaconda3/lib/python3.7/smtplib.py", line 942, in send_message
to_addrs = [a[1] for a in email.utils.getaddresses(addr_fields)]
File "/home/hugo/anaconda3/lib/python3.7/email/utils.py", line 112, in getaddresses
all = COMMASPACE.join(fieldvalues)
TypeError: sequence item 0: expected str instance, tuple found


It looks to me like the error occurs while trying to read an email from the email list but I can't figure it out to be honest.
Any help or links to a related answer is welcome.



UPDATE: I was using zip because that's what the original script did (https://medium.freecodecamp.org/send-emails-using-code-4fcea9df63f). After removing it the error went away but a new one appeared: TypeError: sequence item 0: expected str instance, list found My only problem now is how to change my emails list to an acceptable input for smtplib










share|improve this question

























  • Your problem seems to be here for email in zip(emails):. The zip function takes an iterable and return a list of tuples.

    – yorodm
    Nov 5 '18 at 18:06













  • Thanks yorodm that fixed that error! Now however I'm getting the "expected str, list found" error.

    – Hugo Moran
    Nov 5 '18 at 18:18











  • Edit your Question and explain why you use ` zip(emails)` at all.

    – stovfl
    Nov 5 '18 at 18:45











  • Done, I was using it because that's what the original script did. I changed mine to accept a csv file with the emails and a string as a message but still having troubles.

    – Hugo Moran
    Nov 5 '18 at 18:54
















0















I was unable to find an answer to this error on the existing questions so here it goes.
I'm trying to send an email to a list of email addresses imported from an CSV file using Python, gmail and the smtplib library.
This is the code:



import smtplib
import csv

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

MY_ADDRESS = 'myemailaddress'
PASSWORD = 'mypassword'

def get_contacts(filename):
"""
Return email addresses read from a file specified by filename.
"""

emails =
with open(filename, newline='') as contacts_file:
emailreader = csv.reader(contacts_file, delimiter=' ', quotechar='|')
for a_contact in emailreader:
emails.append(a_contact)
return emails


def main():
emails = get_contacts('mycontacts.csv') # read contacts
message_template = """Test message goes here"""

# set up the SMTP server
s = smtplib.SMTP(host='smtp.gmail.com', port=587)
s.starttls()
s.login(MY_ADDRESS, PASSWORD)

# For each contact, send the email:
for email in zip(emails):
msg = MIMEMultipart() # create a message

# add in the actual person name to the message template
message = message_template

# Prints out the message body for our sake
print(message)

# setup the parameters of the message
msg['From']=MY_ADDRESS
msg['To']=email
msg['Subject']="This is TEST"

# add in the message body
msg.attach(MIMEText(message, 'plain'))

# send the message via the server set up earlier.
s.send_message(msg)
del msg

# Terminate the SMTP session and close the connection
s.quit()

if __name__ == '__main__':
main()


I get the following error:



Traceback (most recent call last):
File "py_mail.py", line 58, in <module>
main()
File "py_mail.py", line 51, in main
s.send_message(msg)
File "/home/hugo/anaconda3/lib/python3.7/smtplib.py", line 942, in send_message
to_addrs = [a[1] for a in email.utils.getaddresses(addr_fields)]
File "/home/hugo/anaconda3/lib/python3.7/email/utils.py", line 112, in getaddresses
all = COMMASPACE.join(fieldvalues)
TypeError: sequence item 0: expected str instance, tuple found


It looks to me like the error occurs while trying to read an email from the email list but I can't figure it out to be honest.
Any help or links to a related answer is welcome.



UPDATE: I was using zip because that's what the original script did (https://medium.freecodecamp.org/send-emails-using-code-4fcea9df63f). After removing it the error went away but a new one appeared: TypeError: sequence item 0: expected str instance, list found My only problem now is how to change my emails list to an acceptable input for smtplib










share|improve this question

























  • Your problem seems to be here for email in zip(emails):. The zip function takes an iterable and return a list of tuples.

    – yorodm
    Nov 5 '18 at 18:06













  • Thanks yorodm that fixed that error! Now however I'm getting the "expected str, list found" error.

    – Hugo Moran
    Nov 5 '18 at 18:18











  • Edit your Question and explain why you use ` zip(emails)` at all.

    – stovfl
    Nov 5 '18 at 18:45











  • Done, I was using it because that's what the original script did. I changed mine to accept a csv file with the emails and a string as a message but still having troubles.

    – Hugo Moran
    Nov 5 '18 at 18:54














0












0








0








I was unable to find an answer to this error on the existing questions so here it goes.
I'm trying to send an email to a list of email addresses imported from an CSV file using Python, gmail and the smtplib library.
This is the code:



import smtplib
import csv

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

MY_ADDRESS = 'myemailaddress'
PASSWORD = 'mypassword'

def get_contacts(filename):
"""
Return email addresses read from a file specified by filename.
"""

emails =
with open(filename, newline='') as contacts_file:
emailreader = csv.reader(contacts_file, delimiter=' ', quotechar='|')
for a_contact in emailreader:
emails.append(a_contact)
return emails


def main():
emails = get_contacts('mycontacts.csv') # read contacts
message_template = """Test message goes here"""

# set up the SMTP server
s = smtplib.SMTP(host='smtp.gmail.com', port=587)
s.starttls()
s.login(MY_ADDRESS, PASSWORD)

# For each contact, send the email:
for email in zip(emails):
msg = MIMEMultipart() # create a message

# add in the actual person name to the message template
message = message_template

# Prints out the message body for our sake
print(message)

# setup the parameters of the message
msg['From']=MY_ADDRESS
msg['To']=email
msg['Subject']="This is TEST"

# add in the message body
msg.attach(MIMEText(message, 'plain'))

# send the message via the server set up earlier.
s.send_message(msg)
del msg

# Terminate the SMTP session and close the connection
s.quit()

if __name__ == '__main__':
main()


I get the following error:



Traceback (most recent call last):
File "py_mail.py", line 58, in <module>
main()
File "py_mail.py", line 51, in main
s.send_message(msg)
File "/home/hugo/anaconda3/lib/python3.7/smtplib.py", line 942, in send_message
to_addrs = [a[1] for a in email.utils.getaddresses(addr_fields)]
File "/home/hugo/anaconda3/lib/python3.7/email/utils.py", line 112, in getaddresses
all = COMMASPACE.join(fieldvalues)
TypeError: sequence item 0: expected str instance, tuple found


It looks to me like the error occurs while trying to read an email from the email list but I can't figure it out to be honest.
Any help or links to a related answer is welcome.



UPDATE: I was using zip because that's what the original script did (https://medium.freecodecamp.org/send-emails-using-code-4fcea9df63f). After removing it the error went away but a new one appeared: TypeError: sequence item 0: expected str instance, list found My only problem now is how to change my emails list to an acceptable input for smtplib










share|improve this question
















I was unable to find an answer to this error on the existing questions so here it goes.
I'm trying to send an email to a list of email addresses imported from an CSV file using Python, gmail and the smtplib library.
This is the code:



import smtplib
import csv

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

MY_ADDRESS = 'myemailaddress'
PASSWORD = 'mypassword'

def get_contacts(filename):
"""
Return email addresses read from a file specified by filename.
"""

emails =
with open(filename, newline='') as contacts_file:
emailreader = csv.reader(contacts_file, delimiter=' ', quotechar='|')
for a_contact in emailreader:
emails.append(a_contact)
return emails


def main():
emails = get_contacts('mycontacts.csv') # read contacts
message_template = """Test message goes here"""

# set up the SMTP server
s = smtplib.SMTP(host='smtp.gmail.com', port=587)
s.starttls()
s.login(MY_ADDRESS, PASSWORD)

# For each contact, send the email:
for email in zip(emails):
msg = MIMEMultipart() # create a message

# add in the actual person name to the message template
message = message_template

# Prints out the message body for our sake
print(message)

# setup the parameters of the message
msg['From']=MY_ADDRESS
msg['To']=email
msg['Subject']="This is TEST"

# add in the message body
msg.attach(MIMEText(message, 'plain'))

# send the message via the server set up earlier.
s.send_message(msg)
del msg

# Terminate the SMTP session and close the connection
s.quit()

if __name__ == '__main__':
main()


I get the following error:



Traceback (most recent call last):
File "py_mail.py", line 58, in <module>
main()
File "py_mail.py", line 51, in main
s.send_message(msg)
File "/home/hugo/anaconda3/lib/python3.7/smtplib.py", line 942, in send_message
to_addrs = [a[1] for a in email.utils.getaddresses(addr_fields)]
File "/home/hugo/anaconda3/lib/python3.7/email/utils.py", line 112, in getaddresses
all = COMMASPACE.join(fieldvalues)
TypeError: sequence item 0: expected str instance, tuple found


It looks to me like the error occurs while trying to read an email from the email list but I can't figure it out to be honest.
Any help or links to a related answer is welcome.



UPDATE: I was using zip because that's what the original script did (https://medium.freecodecamp.org/send-emails-using-code-4fcea9df63f). After removing it the error went away but a new one appeared: TypeError: sequence item 0: expected str instance, list found My only problem now is how to change my emails list to an acceptable input for smtplib







python python-3.x automation






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 5 '18 at 18:53







Hugo Moran

















asked Nov 5 '18 at 17:59









Hugo MoranHugo Moran

34




34













  • Your problem seems to be here for email in zip(emails):. The zip function takes an iterable and return a list of tuples.

    – yorodm
    Nov 5 '18 at 18:06













  • Thanks yorodm that fixed that error! Now however I'm getting the "expected str, list found" error.

    – Hugo Moran
    Nov 5 '18 at 18:18











  • Edit your Question and explain why you use ` zip(emails)` at all.

    – stovfl
    Nov 5 '18 at 18:45











  • Done, I was using it because that's what the original script did. I changed mine to accept a csv file with the emails and a string as a message but still having troubles.

    – Hugo Moran
    Nov 5 '18 at 18:54



















  • Your problem seems to be here for email in zip(emails):. The zip function takes an iterable and return a list of tuples.

    – yorodm
    Nov 5 '18 at 18:06













  • Thanks yorodm that fixed that error! Now however I'm getting the "expected str, list found" error.

    – Hugo Moran
    Nov 5 '18 at 18:18











  • Edit your Question and explain why you use ` zip(emails)` at all.

    – stovfl
    Nov 5 '18 at 18:45











  • Done, I was using it because that's what the original script did. I changed mine to accept a csv file with the emails and a string as a message but still having troubles.

    – Hugo Moran
    Nov 5 '18 at 18:54

















Your problem seems to be here for email in zip(emails):. The zip function takes an iterable and return a list of tuples.

– yorodm
Nov 5 '18 at 18:06







Your problem seems to be here for email in zip(emails):. The zip function takes an iterable and return a list of tuples.

– yorodm
Nov 5 '18 at 18:06















Thanks yorodm that fixed that error! Now however I'm getting the "expected str, list found" error.

– Hugo Moran
Nov 5 '18 at 18:18





Thanks yorodm that fixed that error! Now however I'm getting the "expected str, list found" error.

– Hugo Moran
Nov 5 '18 at 18:18













Edit your Question and explain why you use ` zip(emails)` at all.

– stovfl
Nov 5 '18 at 18:45





Edit your Question and explain why you use ` zip(emails)` at all.

– stovfl
Nov 5 '18 at 18:45













Done, I was using it because that's what the original script did. I changed mine to accept a csv file with the emails and a string as a message but still having troubles.

– Hugo Moran
Nov 5 '18 at 18:54





Done, I was using it because that's what the original script did. I changed mine to accept a csv file with the emails and a string as a message but still having troubles.

– Hugo Moran
Nov 5 '18 at 18:54












1 Answer
1






active

oldest

votes


















0














You have to change for email in zip(emails) to for email in emails.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53159765%2ferror-in-python-while-trying-to-send-emails-using-smtp%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    You have to change for email in zip(emails) to for email in emails.






    share|improve this answer




























      0














      You have to change for email in zip(emails) to for email in emails.






      share|improve this answer


























        0












        0








        0







        You have to change for email in zip(emails) to for email in emails.






        share|improve this answer













        You have to change for email in zip(emails) to for email in emails.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 14 '18 at 16:38









        Tabin1000Tabin1000

        938




        938
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53159765%2ferror-in-python-while-trying-to-send-emails-using-smtp%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Bressuire

            Vorschmack

            Quarantine