使用smtplib的sendmail发送邮件时触发list indices类型错误
问题:发送邮件时出现
list indices must be integers or slices, not str错误 运行以下Python代码时,登录操作成功,且已成功从info.xlsx文件中获取邮箱数据,但发送邮件时出现错误,异常信息为:
list indices must be integers or slices, not str
原代码
from asyncio import constants import pandas as pd import smtplib as smt from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from getpass import getpass print("Reading mails from Excel") data = pd.read_excel("info.xlsx") emailData = data.get("Email") emailList = list(emailData) try: # SMTP Object print("In process...") mailServer = smt.SMTP("smtp.gmail.com", 587) mailServer.starttls() # Inputting email and password senderMail = input("Enter your Email address: ") senderPass = getpass("Input your password: ") # Setting up the email subject, to, from, and message fromEmail = senderMail toEmail = emailList Emailmessage = MIMEMultipart("alternative") Emailmessage['Subject'] = "Testing for Python Project" Emailmessage['from'] = senderMail # Creating the text via HTML messageHTML = ''' <html> <head> <style> .btn{ background:red; } </style> </head> <body> <h1>HEading 1</h1> <button id="btn">Test</button> </body> </html> ''' # login via email mailServer.login(senderMail, senderPass) print("Login Successful") # Attach the message and Multipart textMsg = MIMEText(messageHTML, "html") Emailmessage.attach(textMsg) # Sending the email mailServer.sendmail(fromEmail, toEmail, Emailmessage.as_string()) for email in emailList: print("Message has been sent to ", emailList[email]) mailServer.quit() except Exception as error: print(error)
错误原因及修复方法
错误并非来自sendmail的第三个参数,而是出在循环打印的代码段:
for email in emailList: print("Message has been sent to ", emailList[email])
这里email是emailList中的字符串元素(比如xxx@example.com),但列表只能用整数或切片作为索引,用字符串索引自然会抛出list indices must be integers or slices, not str的错误。
修复步骤:
- 修改循环打印代码,直接使用遍历到的
email变量:
for email in emailList: print("Message has been sent to ", email)
- 可选优化:给邮件对象添加
to字段,让邮件头部信息更完整:
Emailmessage['to'] = ', '.join(emailList)
额外注意事项
如果后续使用Gmail登录失败,需要注意:
- Gmail默认禁用普通密码登录SMTP,需开启两步验证后生成应用专用密码,用该密码替代普通密码登录。
内容的提问来源于stack exchange,提问作者Abhi
相关产品推荐
相关产品推荐

