尝试使用 SMTP 发送电子邮件时 python 出错

Error in python while trying to send emails using SMTP

我无法在现有问题上找到此错误的答案,所以就这样吧。 我正在尝试向使用 Python、gmail 和 smtplib 库从 CSV 文件导入的电子邮件地址列表发送电子邮件。 这是代码:

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()

我收到以下错误:

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

在我看来,错误似乎是在尝试从电子邮件列表中读取电子邮件时发生的,但老实说我无法理解。 欢迎任何帮助或指向相关答案的链接。

更新:我使用 zip 是因为原始脚本就是这样做的 (https://medium.freecodecamp.org/send-emails-using-code-4fcea9df63f)。删除它后,错误消失了,但又出现了一个新错误:TypeError: sequence item 0: expected str instance, list found 我现在唯一的问题是如何将我的电子邮件列表更改为 smtplib

可接受的输入

您必须将 for email in zip(emails) 更改为 for email in emails