Search code examples
pythonemailattachmentsmtplib

Sending a csv file as email attachment using python


I wanna send a csv file as an email attachment. However, when I try to send the mail with an attachment I receieve 'list' object has no attribute 'encode' error. This is the code I'm using. If i remove the attachment I'm able to send the mail.

def send_csv():
    csv_file = check_consumable_status()
    if csv_file:
        mail_server = log_in_mail_server()
        recipients = read_managers_email()
        notification_email = create_notification_email(csv_file)
        if send_email(mail_server,notification_email,recipients):
            print("Mail sent")
    else:
        print("Unable to read subscription status")
        return
def create_notification_email(csv):
    notification_email = EmailMessage()
    notification_email['Subject'] = "consumable notification"
    notification_email['From'] = os.environ["EMAIL_USER"]

    with open('consumable_notification.csv', 'r') as file:
    # Attach the file with filename to the email
        notification_email.attach(MIMEApplication(file.read(), Name='consumable_notification.csv')) #This is where I attempt to attach the file.

    return notification_email

def send_email(server, email, to_address):
    try:
        email['To'] = to_address
        server.send_message(email)
        return True
    except Exception as e: #Here were I get the error
        print("Failed to send email")
        print(e)
        return False

def log_in_mail_server():
    SERVER = os.environ["EMAIL_SERVER"]
    PORT = os.environ["EMAIL_PORT"]
    try:
        server = smtplib.SMTP(SERVER, PORT)
        server.ehlo()
        server.starttls()
        server.ehlo()
        user = os.environ["EMAIL_USER"]
        password = os.environ["EMAIL_PASSWORD"]
        server.login(user, password)
        print("Successfully log in to server")
        return server
    except:
        print("Failed to log in to server")
        return False


Solution

  • I managed to make it work by using a different method to attach the attachment (add_attachment). Here is the code that worked for me:

    def create_notification_email(csv):
        notification_email = EmailMessage()
        notification_email['Subject'] = "consumable notification"
        notification_email['From'] = os.environ["EMAIL_USER"]
        notification_email.set_content("asd")
        with open(csv.name) as file:
        # Attach the file with filename to the email
            notification_email.add_attachment(file.read(), filename=file.name)
        os.remove(csv.name)
        return notification_email