# Emails

### Loops

{% hint style="info" %}
Loops is a great tool for collecting mails, sending transactional mails (think user action like SIgnIn) and even more like marketing mails or newsletter handling.
{% endhint %}

### Setup

1. Create an account on [Loops](https://loops.so).
2. On your Dashboard go to `Settings` > `API` and *Generate Key*
3. Paste it to your `.env` file

{% code title=".env" %}

```bash
LOOPS_API_KEY=
```

{% endcode %}

4. Create a Transactional ID in `Transactional` > *New*, this will be the mail your users receive when  they SignIn.
5. Customize your email and *Publish* it, paste the `Publish` > `transactionalId` value into your `.env` file:

<figure><img src="https://865796172-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FntKe5sSLfvbHfpqI4xbm%2Fuploads%2F0nhemp7OLhFUkASM4Dsp%2FCapture%20d%E2%80%99%C3%A9cran%202024-06-14%20140523.png?alt=media&#x26;token=86a047a0-f680-4028-8512-05c4df70c7d8" alt=""><figcaption><p>API Details from Publish tab</p></figcaption></figure>

{% code title=".env" %}

```bash
LOOPS_TRANSACTION_ID=
```

{% endcode %}

6. Set your DNS Records on `Settings` > `Domain` > *View records* from your registrar (Cloudflare, NameCheap, Gandi...)

### Contacts

DirectoryFast automatically add all the signed up users to your contact list.

If you want to update or modify this behavior, go to the /api/mailing/signin/route.ts file:

{% code title="mailing/signin/route.ts" lineNumbers="true" %}

```typescript
export async function POST(request: Request) {
  const body = await request.json();
  const res = await fetch(`https://app.loops.so/api/v1/contacts/create`, {
    method: "POST",
    body: JSON.stringify({
      email: body.email,
      subscribed: false,
    }),
    headers: {
      Authorization: `Bearer ${process.env.LOOPS_API_KEY}`,
      "Content-Type": "application/json",
    },
  });
  return new Response(JSON.stringify(res), {
    status: 201,
    statusText: "Created",
    headers: { "content-type": "application/json" },
  });
}
```

{% endcode %}

### Newsletter

The newsletter feature let visitors subscribe to your newsletter with or without signing up.

It adds those visitors to the contact list with the "subscribed" value set to "true".

To modify this, go to the /api/mailing/subscribe/route.ts file:

{% code title="mailing/subscribe/route.ts" lineNumbers="true" %}

```typescript
export async function POST(request: Request) {
  const body = await request.json();
  const res = await fetch(`https://app.loops.so/api/v1/contacts/create`, {
    method: "POST",
    body: JSON.stringify({
      email: body.email,
      source: "newsletter",
    }),
    headers: {
      Authorization: `Bearer ${process.env.LOOPS_API_KEY}`,
      "Content-Type": "application/json",
    },
  });
  return new Response(JSON.stringify(res), {
    status: 201,
    statusText: "Created",
    headers: { "content-type": "application/json" },
  });
}
```

{% endcode %}
