通过Sendgrid使用csv中的数据发送电子邮件

bjp0bcyl  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(165)

我正在尝试使用Sendgrid发送电子邮件,并将csv中的数据添加到电子邮件的正文中。我可以使用smtplib来完成此过程,但现在我需要使用sendgrid来完成此过程。

import os
import pandas as pd
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail

db = pd.read_csv('changes.csv', delimiter = ",", skiprows=6)   
db["Email"] = "add@test.com"     

db = db.drop_duplicates(subset = ["Employee Name"], keep = "first")

field1 = db["Field Desc"] == "Status"
field2 = db["Field Desc"] == "Default Cost Center 10 (Job)"

message = Mail(
from_email='test@test.com',
to_emails='test@test.com',
subject='{Employee} -- Kronos Change',
html_content='''\

    We have received the change for {Employee}. 

    Title: {Title}

    Old: {Old}

    New: {New}

    Profit Center: {PC}

    Supervisor: {Supervisor}

    ''')

message.content = Content("text","changes.csv")

try:
sg=SendGridAPIClient(os.environ.get('API KEY'))
response = sg.send(message)
print(response.status_code)
print(response.body)
print(response.headers)
except Exception as e:
print(e.message)

我不确定调用message.content来读取csv文件是否正确。当我使用smtplib时,其中一些代码对我有效。

62lalag4

62lalag41#

使用以下两个函数:

def read_csv_for_email(final_path=None):
    """ send_csv_email
    Send final generated CSV file
    :return:
    """
    final_path = "sample/path/to.csv"
    df = pd.read_csv(final_path, dtype=str, na_filter=True, index_col=False)
    res = send_email_with_csv(
        subject="Sending CSV with SendGrid is Fun",
        content="<strong>CSV with Python</strong>",
        dataframe=df,
        filename=f"Any_Sample.csv",
        filetype="text/csv",
    )
    return res

def send_email_with_csv(subject, content, dataframe, filename, filetype):
    """ send_email_with_csv
    :param subject:
    :param content:
    :param dataframe:
    :param filename:
    :param filetype:
    :return:
    """
    csv_message = Mail(
        from_email=f"test+{MAIL_DOMAIN}",
        to_emails="sample.email@gmail.com",
        subject=subject,
        html_content=content,
    )

    # Create buffered csv
    buffer = BytesIO()
    dataframe.to_csv(buffer)
    buffer.seek(0)
    data = buffer.read()
    encoded = base64.b64encode(data).decode()
    # Set as csv attachement
    attachment = Attachment()
    attachment.file_content = FileContent(encoded)
    attachment.file_type = FileType(filetype)
    attachment.file_name = FileName(filename)
    attachment.disposition = Disposition("attachment")
    csv_message.attachment = attachment
    try:
        sendgrid_client = SendGridAPIClient(SENDGRID_API_KEY)
        response = sendgrid_client.send(csv_message)
        logger.info(response.status_code)
        logger.info(response.body)
        logger.info(response.headers)
        return "CSV sent successfully"
    except Exception as e:
        logger.error(str(e))

调用函数read_csv_email(csv_path)

相关问题