Mulesoft : SMTP : Transform, send file as email attachments

Naveen Raju
naveen’s-blog
Published in
2 min readApr 24, 2018

This article will showcase the capabilities of Mulesoft to send email with CSV / Excel as attachment after dataweave transformations.

SMTP Pre-config setting (GMail):

For this demonstration, we will be using gmail as SMTP server to send emails.

To achieve this, we need to setup GMail to allow the account to send emails. Follow the instructions in the following google support link.

Mulesoft project setup:

Create a new project : Below is the folder structure of the new project

The following shows the Mulesoft code related to transformation and sending email with attachment.

<smtp:gmail-connector name=”Gmail” validateConnections=”true” doc:name=”Gmail” contentType=”text/html”/>

<flow name=”SMTP-Flow”>

<! — Dataweave transformation to create CSV output→

<dw:transform-message doc:name=”Transform Message”>
<dw:set-payload><![CDATA[%dw 1.0
%output application/csv
— -
[
{
Id: 123,
Name: “George”
},
{
Id: 456,
Name: “Lucas”
}
]
]]></dw:set-payload>
</dw:transform-message>

<! — transform the payload to BYTE-ARRAY to attach the payload to file →

<object-to-byte-array-transformer doc:name=”Object to Byte Array”/>

<! —The following will set the message attachment using the payload (CSV output from DW ) →

<set-attachment attachmentName=”${mule.env} #[‘ — ‘ + flowVars.refId].csv” value=”#[payload]” contentType=”text/html” doc:name=”Attachment”/>

<! — The following will be the email body →

<set-payload value=”#[‘Please check the attached for details.’]” doc:name=”Set Payload”/>

<! — Now the message has the attachment, the SMTP will send the message as email →

<smtp:outbound-endpoint host=”smtp.gmail.com” port=”587" user=”some-gmail@gmail.com” password=”gmail-password" connector-ref=”Gmail” to=”to-emailid@gmail.com” from=”from-email@gmail.com” subject=”testng…” responseTimeout=”10000" doc:name=”SMTP”/>

</flow>

For transforming data into EXCEL, using the following Dataweave:

<! — Dataweave transformation to create Excel output→

<dw:transform-message doc:name=”Transform Message”>
<dw:set-payload><![CDATA[%dw 1.0
%output application/xlsx header=true
— -
{
Sheet1 :
[
{
Id: 123,
Name: “George”
},
{
Id: 456,
Name: “Lucas”
}
]
}
]]></dw:set-payload>
</dw:transform-message>

If you get any authentication issue using gmail as SMTP, make sure you turn on the following in goggle-account settings -> Sign-in & security.

This should do the trick.

In enterprise, this may not be accepted. So you need to work with your email exchange team to get the SMTP host, port and access to send email via the setup.

Thank you for reading! If you enjoyed it, please clap 👏 for it.

-Naveen

--

--