Template - API
WelcomePrerequisitesNodeJS
  • Welcome!
    • About me
  • Prerequisites
    • Installation and Database Setup
    • Installing Node.js on the Server
  • NodeJS
    • 🆓Getting Started with the Free Template
    • 🎗️Premium Template - REST API
      • Structure
      • Middlewares and Guards
      • Core Modules
        • Prisma with NestJS
        • Swagger with NestJS
      • Dynamic Module
        • Create or Import Module
  • Modules
    • 🎗️Websockets
    • 🎗️Mailer
    • 🎗️Upload
Powered by GitBook
On this page
  • Placement in the Project
  • Installation
  • Available Mailer Routes (Example)
  • Testing Mailer Integration in Unity with C#
  • Extending the Mailer Module
  1. Modules

Mailer

This module integrates email functionality into your Node.js application, providing a flexible and secure mailing system. It simplifies sending transactional or marketing emails through various servic

Warning: This module must be attached to an existing Node.js server, either the template we provide or a custom project from the user. However, it can only be attached to the Premium template due to the use of NestJS and TypeScript. If you already own the HTTPS Premium module, you can refer to the README to include only the necessary files and be guided on how to make calls to the WebSocket module.

Key Features and Details

The Mailer module offers a simple and robust way to handle email functionality within your Node.js application. Below are the main features of the module:

  • Email Sending: Provides methods to send structured emails, including support for attachments, making it ideal for notifications, alerts, and other automated emails.

  • CAPTCHA Validation: Ensures secure email sending by using a CAPTCHA guard to validate requests. This helps prevent abuse and spam by requiring a valid CAPTCHA token before an email can be sent.

  • HTML Templating: Includes customizable HTML templates for the email header, body, and footer, allowing for a consistent and branded email layout across your application.

  • Attachment Support: Supports attachments in emails, allowing you to send files such as PDFs, images, and documents directly through the Mailer module.

  • SMTP Configuration: Configurable via environment variables (MAILER_HOST, MAILER_PORT, MAILER_USER, MAILER_PASS) for easy integration with different SMTP providers, including Gmail and custom SMTP servers.

  • Error Handling: Comprehensive error handling with informative logging and HTTP status responses in case of failure, ensuring robust communication with clients.

Placement in the Project

This module should be placed in the following directory within the premium template project:

src/modules/mailer

Installation

To get started, ensure you have the necessary dependencies installed:

npm install

If you haven't already, install nodemailer:

npm install nodemailer

Environment Configuration

In the .env file, add the following configurations for SMTP:

MAILER_HOST=smtp.example.com         # Your SMTP server (e.g., smtp.gmail.com for Gmail)
MAILER_PORT=587                      # Port for the SMTP server, 587 for STARTTLS, 465 for SSL
MAILER_USER=your_email@example.com    # Your SMTP account username
MAILER_PASS=your_password             # Your SMTP account password

Available Mailer Routes (Example)

The Mailer module includes predefined routes for sending emails, protected by CAPTCHA validation. These routes demonstrate the functionality and can be modified or extended to suit your needs.

Send

  1. Description: Sends an email to a specified recipient with an optional subject, body content, and attachments.

  2. Method: POST

  3. Method: POST

  4. Payload Example:

    {
        "to": "recipient@example.com",
        "subject": "Email Subject",
        "bodyContent": "Here is the content of the email.",
        "attachments": [
            {
                "filename": "example.pdf",
                "path": "/path/to/example.pdf"
            },
            {
                "filename": "image.png",
                "content": "<binary_content>"
            }
        ],
        "captchaToken": "<CAPTCHA_token>"
    }

Testing Mailer Integration in Unity with C#

You can easily test the Mailer module by making HTTP requests from any client, including C# applications in Unity. Below is an example of how to call the Mailer endpoint from Unity using HttpClient.

Example Client Integration (using C# with HttpClient)

using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

public class MailerClient
{
    private static readonly HttpClient client = new HttpClient();

    public async Task SendEmailAsync()
    {
        var url = "https://your-backend-url.com/mailer/send";

        var formData = new MultipartFormDataContent();
        formData.Add(new StringContent("recipient@example.com"), "to");
        formData.Add(new StringContent("Test Email"), "subject");
        formData.Add(new StringContent("Hello, this is a test email from Unity."), "bodyContent");

        // Attach a file
        var filePath = "path/to/your/file.txt";
        if (File.Exists(filePath))
        {
            var fileContent = new StreamContent(File.OpenRead(filePath));
            fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
            formData.Add(fileContent, "attachments", Path.GetFileName(filePath));
        }

        // Send the request
        var response = await client.PostAsync(url, formData);
        if (response.IsSuccessStatusCode)
        {
            Console.WriteLine("Email sent successfully.");
        }
        else
        {
            Console.WriteLine($"Failed to send email. Status code: {response.StatusCode}");
        }
    }
}

Extending the Mailer Module

The Mailer module is designed to be modular and can be extended to add new features as required by your project. It currently includes the following components:

  • MailerService: Handles the core logic for sending emails, managing attachments, and applying HTML templates for the header and footer.

  • CaptchaGuard: Validates CAPTCHA tokens before allowing email sending, ensuring that only verified requests can send emails.

  • MailerConfig: Provides configurable options for SMTP, which can be adjusted by setting environment variables.

  • MailerController: Exposes the /mailer/send endpoint for client requests to send emails, applying CAPTCHA validation.

With these components, the module can be customized and expanded to suit the specific requirements of your project, such as adding email scheduling or integrating with third-party APIs for email analytics.

PreviousWebsocketsNextUpload

Last updated 7 months ago

🎗️