【问题标题】:'str' object has no attribute 'mime' error?“str”对象没有属性“mime”错误?
【发布时间】:2021-07-19 17:17:57
【问题描述】:

下面是我的代码。 Email.xlsx 具有列名称和电子邮件。 Name 列的值与同一文件夹中的一些 Excel 文件名匹配。想法是将带有附件(Excel 工作簿)的电子邮件发送到 Email.xlsx 中匹配的电子邮件地址。例如:-

电子邮件.xlsx

Name Email 
1001 xxx@gmail.com
1002 yyy@gmail.com
1003 xxx@xxx.com

文件夹中的文件:

1001.xlsx
1002.xlsx
1004.xlsx
1005.xlsx

期望是发送电子邮件至 xxx@gmail.com 和 yyy@gmail.com 仅分别以 1001.xlsx 和 1002.xlsx 作为附件。它们是唯一匹配的名称。我的代码如下,它给了我这个错误:-

AttributeError: 'str' object has no attribute 'mime'

任何指向我做错的地方?

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

email_list = pd.read_excel(r'Email.xlsx')
folder_path="." #Same  folder as above 
my_files=[{each_file.split(".")[0]:each_file} for each_file in os.listdir(folder_path) if each_file.endswith(".xlsx")]
my_files_dict = dict(ChainMap(*my_files))

names = email_list['Name']
emails = email_list['Email']
 
for i in range(len(emails)): # iterate through the records
    # for every record get the name and the email addresses
    
    name = str(names[i])
    email = emails[i]
 
    if my_files_dict.get(name):
        smtp_ssl_host = 'smtp.gmail.com'
        smtp_ssl_port = 465
        email_from = "xxxxx@gmail.com"
        email_pass = "xxxx"
        email_to = email
        msg2 = MIMEMultipart()
        msg2['Subject'] = "Record(s)"
        msg2['From'] = email_from
        msg2['To'] = email
        filename = my_files_dict.get(name)
        print(filename)
        attach = email.mime.application.MIMEApplication(filename.read(),_subtype="xlsx")
        msg.attach(attach)
        s2 = smtplib.SMTP_SSL(smtp_ssl_host, smtp_ssl_port)
        s2.login(email_from, email_pass)  
        s2.send_message(msg)
        s2.quit()

【问题讨论】:

    标签: python excel pandas email


    【解决方案1】:

    那是因为你在这里重命名了 email 包:

    email = emails[i]
    

    您试图引用from email.mime.text import MIMEText,但您引用的是字符串email。只需更改字符串的名称就可以了

    【讨论】:

    • 那你介意接受这个答案吗?
    • 当然舒巴姆。搞定了。
    猜你喜欢
    • 2016-04-07
    • 1970-01-01
    • 2018-02-08
    • 2018-03-15
    • 2019-03-30
    • 2016-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多