简体   繁体   English

如何将 Excel 作为 email 中的附件发送 Python 3.6.8

[英]How to send Excel as an attachment in email Using mandrill with Python 3.6.8

Can anyone help on how to send an email with excel attachment using mandrill in python.任何人都可以帮助如何使用 python 中的山魈发送带有 excel 附件的 email。 I am using python 3.6.8 version as my project is old version and has dependencies which do not allow me to upgrade the python version.我正在使用 python 3.6.8 版本,因为我的项目是旧版本并且具有不允许我升级 python 版本的依赖项。 Here is the code I am using这是我正在使用的代码

 def _send_message(to, subject, htmlbody, add_header=True, cc=None, 
    bcc=None, attachment=None, attachment_content=None):
   if os.getenv('MGC_ENV') != 'prod':
       subject = '[{0}] '.format(os.getenv('MGC_ENV')) + subject

   if add_header:
       subject = 'MAP {0}'.format(subject)
    
    recipients = _generate_recipients(to, cc, bcc)

    if len(recipients) == 0:
       return

    bundle = {
       'to': recipients,
       'from_email': os.getenv('FROM_EMAIL'),
       'subject': subject,
       'html': htmlbody,
       'tags': _MANDRILL_TAGS,
       'preserve_recipients': True
     }

    if attachment and attachment_content:
        attachment = [{
          "type": 'application/xlsx',
          "name": 'OrderConfirmation.xlsx',
          "content": attachment_content.toString('base64')
        }]
        bundle["attachments"] = attachment

    if os.getenv('ENABLE_NOTIFICATIONS') == 'false':
       return

    _mandrill_client.messages.send(bundle)

The issue in the above code is the attachment is expecting the content as string encoded with base64 and when tried to set bytes array it wont work.上面代码中的问题是附件期望内容为用 base64 编码的字符串,当尝试设置字节数组时它不会工作。

When we try to convert the excel into the type string it is not able to read and is breaking.当我们尝试将 excel 转换为类型字符串时,它无法读取并且正在中断。

def export(licenses, plain_str=True): workbook = xlwt.Workbook()

    products_sheet = _create_product_sheet(workbook)

    product_row_offset = 1

    cell_style = xlwt.easyxf('font: underline single; font: color 
    blue')

    if licenses and len(licenses) > 0:
      for lic in licenses:
          row = products_sheet.row(product_row_offset)
          _write_product_row(row, lic, cell_style=cell_style)
          product_row_offset += 1

    if plain_str:

        content = utils.workbook_to_str(workbook)
     else:
        content = utils.workbook_to_bytes(workbook)
        return content



   def workbook_to_str(workbook):
       io_buffer = io.StringIO()
       workbook.save(io_buffer)

       return io_buffer.read()



   def workbook_to_bytes(workbook):
       io_buffer = io.BytesIO()
       workbook.save(io_buffer)

       return io_buffer.getvalue()

Thanks in advance for your answer.提前感谢您的回答。

I'm no Python wizard (yet) but I've got the MailChimp integration working (pretty much the same as Mandril) using the below.我不是 Python 向导(还),但我已经使用下面的方法使 MailChimp 集成正常工作(与 Mandril 几乎相同)。

The parts that I struggled with were encoding the xlsx - base64_encoded = base64.b64encode(df_xlsx).decode('UTF-8') and finding the correct attachment type 'type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'我挣扎的部分是编码 xlsx - base64_encoded = base64.b64encode(df_xlsx).decode('UTF-8')并找到正确的附件类型'type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'

import mailchimp_transactional as MailchimpTransactional
from mailchimp_transactional.api_client import ApiClientError
import base64
from io import BytesIO
import pandas as pd

def send_email_notification():
    MANDRILL_API_KEY = Secret.load("mandrill-api-key")
    MAILCHIMP_API_KEY = MANDRILL_API_KEY.get()

    try:
        mailchimp = MailchimpTransactional.Client(MAILCHIMP_API_KEY)
        response = mailchimp.users.ping()
        print('API called successfully: {}'.format(response))
    except ApiClientError as error:
        print('An exception occurred: {}'.format(error.text))

    df = pd.DataFrame([['a', 'b'], ['c', 'd']],
                       index=['row 1', 'row 2'],
                       columns=['col 1', 'col 2'])

    def to_excel(df):
        output = BytesIO()
        writer = pd.ExcelWriter(output, engine='xlsxwriter')
        df.to_excel(writer, sheet_name='Sheet1')
        writer.save()
        processed_data = output.getvalue()
        return processed_data

    df_xlsx = to_excel(df)

    base64_encoded = base64.b64encode(df_xlsx).decode('UTF-8')



    message = {
        "from_email": "noreply@emailtest.com",
        "from_name": "Test",
        "subject": "The model has run successfully",
        'attachments': [{'name': 'test.xlsx',
                         'type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                         'content': base64_encoded
                         }],
        "to": [
            {
                "email": emailaddress,
                "name": "",
                "type": "to"
            }
        ]
    }


    try:
        mailchimp = MailchimpTransactional.Client(MAILCHIMP_API_KEY)
        response = mailchimp.messages.send({"message": message})
        print('API called successfully: {}'.format(response))
    except ApiClientError as error:
        print('An exception occurred: {}'.format(error.text))


if __name__ == "__main__":
    send_email_notification()

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

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