Tuesday, September 22, 2020

Mulesoft Send Email With CSV Attachment

Introduction

This blog explain the tricks to convert csv data to plain text for the purpuse of send csv as attachment. The Mulesoft document can be found at here
  
  
      
          
      
      
          Hello this is an important message"]]>
      
      
        #[{
          'csv-attachment' : payload
        }]
      
  

Code Details

As shown in the follow snapshot, we need to perform two transformations:
  • from csv to base64 binary
  • from base64 binary to plain text>
The challenge is that we cannot direct convert to "application/csv" to "text/plain".
The details are shown below:

Step 1: Initial code JSON to CSV

%dw 2.0
output application/csv separator=","
---
[
	{
		name: "Gary Liu",
		ssn: "1234"
	},
	{
		name: "John Smith",
		ssN: "4567"
	}
]

Step 2: CSV to Base64 Binary

%dw 2.0
import * from dw::core::Binaries
output text/plain
---
toBase64(write (payload, 'application/csv'))

Step 3: Base64 Binary to CSV Plain Text

%dw 2.0
import fromBase64 from dw::core::Binaries
output text/plain
---
fromBase64(payload)

Take Aways

The line of thinking is that Mule runtime engine internally keeps that data as array of records. This java object cannot direct convert to plain text. The code is really mimic the way we store the data to file and then read the data from file to plain text.

Anypoint Studio Error: The project is missing Munit lIbrary to run tests

Anypoint Studio 7.9 has a bug. Even if we following the article: https://help.mulesoft.com/s/article/The-project-is-missing-MUnit-libraries-...