Reputation: 53
Below is my code. Email.xlsx has columns Name and Email. Values of the column Name, match some Excel file names in the same folder. Idea is to send an email with attachments(Excel Workbooks) to a matching email address in Email.xlsx. For example:-
Email.xlsx
Name Email
1001 [email protected]
1002 [email protected]
1003 [email protected]
Files in the folder:
1001.xlsx
1002.xlsx
1004.xlsx
1005.xlsx
Expectation is to send emails to [email protected] and [email protected] only with 1001.xlsx and 1002.xlsx as attachments respectively. They are the only matching names. My code is below and it gives me this error: -
AttributeError: 'str' object has no attribute 'mime'
Any pointers to where I'm not doing things right?
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 = "[email protected]"
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()
Upvotes: 1
Views: 417
Reputation: 2248
That's because you have renamed the email
package over here:
email = emails[i]
You're trying to refer to from email.mime.text import MIMEText
but you're referring to the string email
instead. Just change the name of the string and you're good
Upvotes: 2