Search code examples
pythonexcelpandasemailemail-attachments

Excel email attachment using python


Need to attach excel file in outlook email. I need to use the user name and password as well.

Getting the error

excel_file=r'D:\\vvvv\\bbbb\\aaaa\\xxxx\\abc.xlsx'

def send_mail_with_excel(recipient_email, subject, content, excel_file):
    msg = EmailMessage()
    msg['Subject'] = subject
    msg['From'] = SENDER_EMAIL
    msg['To'] = recipient_email
    msg.set_content(content)

    with open(excel_file, 'rb') as f:
        file_data = f.read()
    msg.add_attachment(file_data, maintype="application", subtype="xlsx", filename=excel_file)

    with smtplib.SMTP_SSL('smtp-mail.outlook.com', 587) as smtp:
        smtp.login(SENDER_EMAIL, APP_PASSWORD)
        smtp.send_message(msg)
   
send_mail_with_excel(recipient_email, subject, content, excel_file)        

Error:

Input In [78] in send_mail_with_excel
    with open(excel_file, 'rb') as f:

TypeError: an integer is required (got type str)

Solution

  • The error message shows that the open function accept an integer and not a string so it's not the signature of the builtin function.

    You probably have an import that overrides the open function like from xxx import open or worst from xxx import *

    Why is "import *" bad?

    Note: filename=excel_file as parameter of add_attachment method should preferably be a filename and not a path.