繁体   English   中英

使用 python 发送 csv 文件作为 email 附件

[英]Sending a csv file as email attachment using python

我想发送一个 csv 文件作为 email 附件。 但是,当我尝试发送带有附件的邮件时,我收到'list' object has no attribute 'encode'错误。 这是我正在使用的代码。 如果我删除附件,我就可以发送邮件。

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

'list' object has no attribute 'encode'表示需要一个字符串,但您提供的是一个列表。

除了print(e) ,您还可以使用以下内容来为我们提供更多信息:

import traceback

try:
   # some code
Except Exception as e:
   traceback.print_exc()

我设法通过使用不同的方法附加附件 ( add_attachment ) 使其工作。 这是对我有用的代码:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM