Mechanic Get Mechanic
Task library

Email a CSV export of products

This task demonstrates Mechanic's ability to compile a CSV export, and send it as an email attachment. In this example, we bundle up a simple export of product titles and IDs, and email it as a CSV attachment.

Try this task

When it runs

Occurs when a user manually triggers the task

What you choose

Email recipient

Task code and subscriptions

You can edit the Liquid code after installing this task. View on GitHub or ask a question in the Mechanic Slack community.

Subscriptions

mechanic/user/trigger
How task subscriptions work

Option types and flags

Task code


{% comment %}
  -- create the initial array of arrays expected by the csv filter, and add the header row with column titles to it
{% endcomment %}

{% assign header_row = array | push: "Product ID", "Product Title" %}
{% assign rows = array | push: header_row %}

{% assign cursor = nil %}
{% assign products = array %}

{% for n in (1..100) %}
  {% capture query %}
    query {
      products(
        first: 250
        after: {{ cursor | json }}
      ) {
        pageInfo {
          hasNextPage
          endCursor
        }
        nodes {
          legacyResourceId
          title
        }
      }
    }
  {% endcapture %}

  {% assign result = query | shopify %}

  {% if event.preview %}
    {% capture result_json %}
      {
        "data": {
          "products": {
            "nodes": [
              {
                "legacyResourceId": "1234567890",
                "title": "Short sleeve t-shirt"
              }
            ]
          }
        }
      }
    {% endcapture %}

    {% assign result = result_json | parse_json %}
  {% endif %}

  {% for product in result.data.products.nodes %}
    {% assign row = array | push: product.legacyResourceId, product.title %}
    {% assign rows = rows | push: row %}    
  {% endfor %}

  {% if result.data.products.pageInfo.hasNextPage %}
    {% assign cursor = result.data.products.pageInfo.endCursor %}
  {% else %}
    {% break %}
  {% endif %}
{% endfor %}

{% assign csv = rows | csv %}

{% action "email" %}
  {
    "to": {{ options.email_recipient__email_required | json }},
    "subject": {{ "Product ID export for " | append: shop.name | json }},
    "body": "Please see attached. :)",
    "reply_to": {{ shop.customer_email | json }},
    "from_display_name": {{ shop.name | json }},
    "attachments": {
      "export.csv": {{ csv | json }}
    }
  }
{% endaction %}

{% log csv %}
Mechanic Liquid reference