Email Bridge

The Apps Engine Email Bridge expands your app’s communication capabilities by enabling email interactions without requiring external integrations. With this feature, your Rocket.Chat app can send emails directly to users, simplifying the process of managing notifications and updates.

In this guide, we will create a slash command in our Hello World app that sends an email to a user. Before starting, ensure that a Rocket.Chat server is available for app deployment.

Step 1: Register the slash command

The following code registers the slash command in the app’s main class, located at the root of the project:

import { IAppAccessors, IConfigurationExtend, ILogger } from '@rocket.chat/apps-engine/definition/accessors';
import { App } from '@rocket.chat/apps-engine/definition/App';
import { IAppInfo } from '@rocket.chat/apps-engine/definition/metadata';
import { EmailCommand } from './commands/EmailCommand'; 

export class HelloWorldApp extends App {
    constructor(info: IAppInfo, logger: ILogger, accessors: IAppAccessors) {
        super(info, logger, accessors);
    }

    public async extendConfiguration(configuration: IConfigurationExtend) {
        configuration.slashCommands.provideSlashCommand(new EmailCommand()); // [2]
    }
}

Here, we import our new slash command class and then register it in the app's configuration.

Step 2: Create the slash command

  1. If you haven't created a separate directory for slash commands, it is recommended to create a commands directory at the root of the project.

  2. Create the EmailCommand.ts file in this directory.

  3. Then enter the code shown below:

import {
    IHttp,
    IModify,
    IRead,
} from '@rocket.chat/apps-engine/definition/accessors';
import {
    ISlashCommand,
    SlashCommandContext,
} from '@rocket.chat/apps-engine/definition/slashcommands';

export class EmailCommand implements ISlashCommand {
    public command = 'email';
    public i18nParamsExample = '';
    public i18nDescription = '';
    public providesPreview = false;

    public async executor(context: SlashCommandContext, read: IRead, modify: IModify, http: IHttp): Promise<void> {
        const [email] = context.getArguments();

        if (!email) {
            throw new Error('Error!');
        }
        const fromEmail = await read.getEnvironmentReader().getServerSettings().getValueById('From_Email');

        await modify
            .getCreator()
            .getEmailCreator()
            .send({
                to: email,
                from: fromEmail,
                subject: 'Sending an email from Apps Engine',
                replyTo: undefined,
                headers: undefined,
                text: `This email was sent from apps engine, cool right?`,
                html: `<p>This email was sent from apps engine, cool right?</p>`,
            });

        console.log('Email Sent!');

    }
   
}

This code implements the following:

  1. The slash command is registered with the name email.

  2. When the command is executed, it expects an email address as an argument. If no argument is provided, the command throws an error.

  3. The fromEmail address is retrieved from the Rocket.Chat server’s environment settings (From_Email).

  4. The send() function builds the email, setting the to, from, subject, text, and html fields. The email is then sent to the specified user.

  5. A confirmation message ("Email Sent!") is logged to the console upon successful execution.

Step 3: Print the request to a conversation

Instead of logging the output to the instance's console, you can send a message directly to the chat room. To do this, add the following private method to the EmailCommand class:

private async sendMessage(context: SlashCommandContext, modify: IModify, message: string): Promise<void> {
    const messageStructure = modify.getCreator().startMessage();
    const sender = context.getSender(); // [1]
    const room = context.getRoom(); // [2]

    messageStructure
        .setSender(sender)
        .setRoom(room)
        .setText(message); // [3]

    await modify.getCreator().finish(messageStructure); // [4]
}

This function implements the following:

  1. Gets the user who invoked the command (in this case, you).

  2. Identifies the room where the command was executed.

  3. Sets the provided string (message) as the content of the message to be sent.

  4. Sends the constructed message to the specified room

Next, append the following line to the end of the executor method:

 await this.sendMessage(context, modify, 'Email Sent');

Once the email is successfully sent, a confirmation message (Email Sent) is sent back to the chat room where the command was invoked.

Note: To learn more about messaging, see the IMessageBuilder documentation.

Step 4: Add the required permission

To send emails successfully using the Email Bridge, your app must have the email.send permission. Add this permission to your app’s manifest file (app.json), alongside any other permissions required for your app. For example:

 "permissions": [
        {
            "name": "email.send"
        },
        {
            "name": "api"
        },
        {
            "name": "persistence"
        },
        {
            "name": "slashcommand"
        },
        {
            "name": "networking"
        },
        {
            "name": "ui.registerButtons"
        },
        {
            "name": "ui.interact"
        },
        {
            "name": "user.read"
        },
        {
            "name": "user.write"
        },
        {
            "name": "message.write"
        },
        {
            "name": "room.read"
        },
        {
            "name": "room.write"
        },
        {
            "name": "server-setting.read"
        }
    ]

Note: To learn more about permissions, see the App Permission System documentation.

Step 5: Deploy the app

To deploy the app, run:

rc-apps deploy --url <server_url> -u <user> -p <pwd>
  • The <server_url> parameter is the URL of your Rocket.Chat server.

  • Replace the placeholders with the URL, username, and password for your server, respectively.

After executing this command, your application will be deployed to the server.

Packaging your app

Alternatively, you can execute the rc-apps package command. This gives you a compressed zip file of your app that you can upload as a private app to your Rocket.Chat server.

Step 6: Test the app

Before testing the app, ensure that SMTP is enabled and functional in your Rocket.Chat workspace. Once the app is deployed, follow these steps to test the email functionality:

  1. Open any room and input the following slash command: /email <email-address>.
    Replace <email-address> with the recipient's email address.

  2. Press Enter.

If successful, the message "Email Sent" will appear in the channel, confirming that the email has been sent.

The email sent to the user will look like this:

Similarly, you can customize this concept to send different kinds of emails from your app.