我无法在现有问题上找到此错误的答案,因此可以解决。 我正在尝试将电子邮件发送到使用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可接受的输入
答案 0 :(得分:0)
您必须将for email in zip(emails)
更改为for email in emails
。