Earlier this week I created my own personal email service as the initial step towards building my own bookmarks service for my personal site.

This service receives an email and then categorises it into a selection of folders, from which I plan to build additional services to parse data from these folders and then action on that data according to the category, today we are building the first of those additional services, my bookmarks service.

You can find out more about the categorisation Lambda here: https://nicholasgriffin.dev/blog/cf3c4661-f676-4028-879b-f2686852b82b

Starting off our Serverless service

To kick things off, we need to initialise our new Serverless service that will become a Lambda and API Gateway once we deploy it.

For me, this starts with the basic Serverless configuration, which is:

1service: serverless-bookmarks-service
2
3provider:
4  name: aws
5  runtime: nodejs12.x
6  stage: prod
7  region: eu-west-1
8  stackName: serverless-bookmarks-service-stack
9  apiName: serverless-bookmarks-service-api
10  iamRoleStatements:
11    - Effect: 'Allow'
12      Action:
13        - 's3:*'
14      Resource: 'arn:aws:s3:::email.nicholasgriffin.dev/*'
15

I have also set up a function for processing the emails that have been stored in order processed bookmarks folder like so:

1functions:
2  process:
3    handler: handler.process
4    description: Process Bookmark emails to DynamoDB
5    timeout: 15
6    events:
7      - s3:
8          bucket: email.nicholasgriffin.dev
9          event: s3:ObjectCreated:*
10          rules:
11            - prefix: processed/bookmarks/
12            - suffix: .json
13          existing: true
14

I’ll add some API functions here later as well, but for now, this is the first step.

Creating a function to process our stored Bookmark emails

For our process function, we need to start by creating a couple of variables for the event data that AWS sends when the function is triggered via the rules we set above.

These are:

1const bucket = event.Records[0].s3.bucket;
2      const object = event.Records[0].s3.object;
3

The bucket variable will contain data about the bucket that the file is stored in, including the name, ownerIdentity and the arn for the bucket.

The object variable contains all the data for the file itself, including the key, size, eTag, and sequencer.

Take not that this will not provide the actual file data, so we need to grab that separately, which we will do like so:

1      const bookmarkBucket = event.Records[0].s3.bucket.name;
2      const bookmarkKey = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
3
4      console.info(
5        `Fetching email at s3://${bookmarkBucket}/${bookmarkKey}`
6      );
7
8      const data = await s3
9        .getObject({
10          Bucket: bookmarkBucket,
11          Key: bookmarkKey,
12        })
13        .promise();
14

The data object should now contain all of the data for the bookmark email that we previously stored.

From here, we’ll need to process the contents into a DynamoDB table.

We are pushing it to a DynamoDB table so that we can ensure that all data that end up accessible to the API has been processed correctly and validated.

Setting up my Bookmarks DynamoDB table

To get started with storing on DynamoDB, I’ll need to create a table first. This is very simple, just head on over to the DynamoDB section within AWS here:

https://eu-west-1.console.aws.amazon.com/dynamodbv2/home?region=eu-west-1#dashboard

And click the Tables option on the left-hand side. From this page hit the “Create table” button to create a new table!

I’m naming mine “Bookmarks-Service” and setting the partition key as “id” with the type string, as each of our Bookmarks will have its own unique ID.

For the sort key, I will add a new string value named ‘status’, this will be for sorting the bookmarks by verified and unverified statuses.

Leave everything as default and click the “Create table button” at the bottom as these are all sensible settings, no further configuration is required unless you really want to.

Once the creation has finished, grab a note of your ARN for the DB as you’ll need that later.

Parsing my bookmarks email

So now it’s time for the fun part, parsing my bookmarks email.

In my inbox service, I am storing the data as JSON and it comes out to be similar to this (with the headers and attachments removed to make it smaller):

1{
2    "id": "1o7micppvf093nffskmek05ts00kcml2d92tbqo1",
3    "received": "2021-08-29T18:37:27.000Z",
4    "to": {
5        "value": [
6            {
7                "address": "bookmarks@nicholasgriffin.dev",
8                "name": ""
9            }
10        ],
11        "html": "<span class=\"mp_address_group\"><a href=\"mailto:bookmarks@nicholasgriffin.dev\" class=\"mp_address_email\">bookmarks@nicholasgriffin.dev</a></span>",
12        "text": "bookmarks@nicholasgriffin.dev"
13    },
14    "from": {
15        "value": [
16            {
17                "address": "me@nicholasgriffin.co.uk",
18                "name": "Nicholas Griffin"
19            }
20        ],
21        "html": "<span class=\"mp_address_group\"><span class=\"mp_address_name\">Nicholas Griffin</span> &lt;<a href=\"mailto:me@nicholasgriffin.co.uk\" class=\"mp_address_email\">me@nicholasgriffin.co.uk</a>&gt;</span>",
22        "text": "Nicholas Griffin <me@nicholasgriffin.co.uk>"
23    },
24    "subject": "Test with new roles",
25    "headers": [
26    ],
27    "attachments": [
28    ],
29    "html": "<html><head></head><body><div><br></div><div><br></div><div id=\"protonmail_signature_block\" class=\"protonmail_signature_block\"><div><div>Thanks,<br></div><div><br></div><div>Nicholas Griffin</div></div></div> </body></html>\n\n\n"
30}
31

For id, received and subject, we can already consider that processed and good to go.

For the to and from, we’ll just want to trim that down so that we just have the name and address, which is done quite easily:

1from.value[0].address
and
1from.value[0].name
.

The tricky part will be the HTML, as here what I’ll need to do is go through the contents of the email in order to find the attribute that I need for my bookmark.

I’m going to do this by using indexOf and substring, probably not the best way to do it, but it works and I don’t want to commit too much time to this just yet, so that’s what I’m using :), feel free to pop a pull request in if you can think of something better xD.

Anyway, so with that, we end up with the following code to process our data into an object that we can send to DynamoDB:

1const { id, received, subject, from, to, html } = json;
2
3          const fromAddress = from.value[0].address;
4          const fromName = from.value[0].name;
5
6          const toAddress = to.value[0].address;
7          const toName = to.value[0].name;
8
9          // TODO: parse the html for bookmark data
10          const bookmark = {};
11
12          function extractData(data, startStr, endStr) {
13            subStrStart = data.indexOf(startStr) + startStr.length;
14            return data.substring(
15              subStrStart,
16              subStrStart + data.substring(subStrStart).indexOf(endStr)
17            );
18          }
19
20          bookmark.title = extractData(html, '<div>Title: ', '</div>');
21          bookmark.description = extractData(
22            html,
23            '<div>Description: ',
24            '</div>'
25          );
26          bookmark.url = extractData(html, '<div>URL:&nbsp;', '</div>');
27

We then create another object in the format thatwill dynamoDB will accept this data and then we store it:

1const dataOutput = {
2              Item: {
3                id: {
4                  S: id,
5                },
6                status: {
7                  S: 'unverified',
8                },
9                recieved: {
10                  S: recieved,
11                },
12                bookmark: {
13                  S: JSON.stringify(bookmark),
14                },
15                subject: {
16                  S: subject,
17                },
18                fromAddress: {
19                  S: fromAddress,
20                },
21                fromName: {
22                  S: fromName,
23                },
24                toAddress: {
25                  S: toAddress,
26                },
27                toName: {
28                  S: toName,
29                },
30              },
31            };
32
33            var params = {
34              Item: dataOutput.Item,
35              TableName: config.tableName,
36            };
37
38            const result = await dynamodb.putItem(params).promise();
39

And now that has been done, we can delete the original object and return the result:

1              await s3
2                .deleteObject({
3                  Bucket: bookmarkBucket,
4                  Key: bookmarkKey,
5                })
6                .promise();
7
8              return {
9                statusCode: 200,
10                body: JSON.stringify({
11                  message: result,
12                  event,
13                }),
14              };
15

And that’s it, now we have a service that will process our bookmarks emails and then store that processed data in DynamoDB.

Next up, we need to create our GraphQL service that will allow us to interact with this stored data, but before then it’s time to have quick break.

While you are on your break you can check out the code here (spoilers: this may include the API by the time you look at it): https://github.com/nicholasgriffintn/Bookmarks-Service

Update: You can check out part 2 here

Success