Sending emails with attachments using Azure Logic Apps
Tags: azure, node, email, logicapps
Published: 2021-07-16 15:23:51

Hi, 
If you are someone using azure functions and looking for a way to trigger email notifications through your application. You might wanna stick around…

If you haven't come across logic apps, you must wonder -

>Why can’t I use sendgrid, nodemailer, or any third party library? I could certainly get email notifications to work with just a bit of code snippet and avoid the complete hustle of creating a new cloud service. no?

I’d say, _Don’t._

> While you are using azure functions and security is the utmost priority to you. You should avoid integrating a third party library for emails.

_WHYYYYY!!!???_

  Well, for a start -
1. you are most likely to get caught up with domain and sender 
  authentication. 
2. Emails can potentially end up in your spam and you will have to 
   follow the steps to set up SPF, DKIM and DMARC for your domain 
   and it is not exactly a piece of cake. Furthermore, if not set 
   up correctly; you can expect more problems, dear.
 
(I will discuss spf, dkim, and dmarc in another article)

So, here is when logic app will come to the rescue. It will internally validate users as we integrate connectors such as Outlook, Gmail etc. to our application for triggering emails. Therefore, any email sent via logic app will not end up in a spam box for sender/receiver sharing a common connector. for cases where we require multiple connectors, we can create parallel branches to our logic app workflow. 

Logic apps are basically used to design automated workflows which integrate your apps, data, services, and systems.
For example :
◾ Fetching data from blob storage and sending them as attachments 
  for email notification.
◾ Move uploaded files from an SFTP or FTP server to Azure Storage.

While using logic apps, you usually won't have to write any code. However, if you do need to write code, you can create code snippets using Azure Functions and run that code from your workflow. Let’s follow these steps to get started -

Add a consumption model and proceed with details of assigning resource group, name, subscription to your logic app. Click on **Create and review**.

![consumption model](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sxvjj17xznqx7ow876xg.png)

Click on Go to resource and select **When a HTTP request is received**.

![HTTP request](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zmdfw38ujud99x4oa7ha.png)

Paste the following schema, and copy the URL -

```
{ "type": "object", 
        "properties": {
            "from": { "type": "string" },
            "cc": { "type": "string" },
            "Attachments": { "type": "array" },
            "to": { "type": "string" },
            "subject": { "type": "string" },
            "html": { "type": "string" },
 },
   }

```
![schema](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8apv7uv6lugg8lyegtje.png)

At the bottom of the designer, click New step, type Outlook (you can use any connector eg. Gmail) in the actions search box. Find and select **Send email (V2)**.

![Outlook Connector](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j0do5wzf3ggaehv6aaby.png)

Once signed in, click in the **To** textbox, and the dynamic content dialog appears with properties from JSON schema. Choose accordingly.

![dynamic content dialog box](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r2gsfu6ne34zuvkz9dt7.png)

Click on **add new parameter** for additional fields and select the following

![new parameters](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yekwxzc3xsi36nvyb81i.png)

switching to input array for multiple attachments -

![input array](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kbmbes8xzzq7e7ue5w40.png)

In your code, add the following -
   ```
   const axios = require('axios');
  
      var msg = {
            "from": "validemail1@domain.com",
            "cc": "testemail1@domain.com;testemail2@domain.com",
            "Attachments": [{
                              ContentBytes: blob.data,
                              Name: "sample-attachment"             
                           }],
            "to": "validemail2@domain.com",
            "subject": "wow!",
            "html": "<!DOCTYPE html><html><body><h1>this is soo 
                     coool</h1></body></html>" };

    try {
        const response = await 
        axios.post(process.env.LOGIC_APP_URL, msg);
        console.log(response.status);
    } catch (error) {
        console.log(error);
    }
}
```

   
**NOTE**
 1. the 'from' address needs to be from one of the connections you 
    have verified through outlook signin in the logic apps 
    designer. if any other address, it will throw the error - 
    user is not "Authorised" to send the email.
 2. the ContentBytes property for an Attachment object should be 
    base64 encoded. I have fetched the 'blob' in code from a 
    storage container through internal API; you can directly fetch 
    from storage container by calling it through logic apps 
    designer as well.

Now as per the code snippet, Let's include the LOGIC_APP_URL in our environment variables.
Open App Service on azure portal,
create a LOGIC_APP_URL key/value pair in configuration

![configuration](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/se0pbrdto1ex3tkablzu.png)

thats it! you're all set with a simple logic app email trigger service.