image

Acesse bootcamps ilimitados e +650 cursos pra sempre

60
%OFF
ALEXANDRE MIRANDA
ALEXANDRE MIRANDA29/08/2023 14:35
Compartilhe

Servidor de e-mail em NodeJS

  • #JavaScript

Nodemailer é uma ferramenta contruida em TypeScript que roda com o NodeJS e permite o envio de e-mail com facilidade, uma solução simples e fácil.

Para iniciar, crie uma conta válida para envio dos e-mails, neste exemplo criei no Outlook.com: noreplaymessage@outlook.com.br.

Bom, agora é cógigo.

/package.json

{

 "name": "nodemailer",

 "version": "1.0.0",

 "description": "E-mail Server",

 "main": "server.ts",

 "engines": {

  "node": ">=16"

 },

 "scripts": {

  "start:dev": "tsx watch src/server.ts",

  "start": "node build/server.js",

  "build": "tsc"

 },

 "author": "Alexandre Jr",

 "license": "ISC",

 "dependencies": {

  "body-parser": "^1.20.2",

  "dotenv": "16.3.1",

  "express": "^4.18.2",

  "ip": "^1.1.8",

  "nodemailer": "^6.9.3",

  "zod": "^3.21.4"

 },

 "devDependencies": {

  "@types/express": "^4.17.17",

  "@types/ip": "^1.1.0",

  "@types/node": "20.3.3",

  "@types/nodemailer": "^6.4.9",

  "tsx": "3.12.7",

  "typescript": "^5.1.6"

 }

}

/tsconfig.json

{

 "compilerOptions": {

  "target": "es2016",

  "module": "commonjs",

  "declaration": true,

  "outDir": "./build",

  "esModuleInterop": true,

  "forceConsistentCasingInFileNames": true,

  "strict": true,

  "skipLibCheck": true

 },

 "include": ["src/**/*"]

}

/.env

SMTP_MAIL="smtp-mail.outlook.com"

SMTP_MAIL_HOST="smtp-mail.outlook.com"

SMTP_MAIL_PORT=587

SMTP_MAIL_USER="noreplaymessage@outlook.com.br"

SMTP_MAIL_PASSWORD="*************"

HTTP_SERVER_PORT=3030

/src/server.ts

import ip from "ip";

import express from "express";

import nodemailer from "nodemailer";

import bodyParser from "body-parser";

import { env } from "./env/index";

import { z } from "zod";

import { badRequest, internalServerError } from "./messages/errors";

import { success } from "./messages/success";

const emailServer = express();

const jsonParser = bodyParser.json();

emailServer.post("/send-email", jsonParser, async (req, res) => {

 const createEmailBodySchema = z.object({

  to: z.string().email(),

  subject: z.string(),

  text: z.string(),

  html: z.string(),

 });

 const validateBody = createEmailBodySchema.safeParse(req.body);

 const { to, subject, text, html } = req.body;

 if (validateBody.success) {

  const transport = nodemailer.createTransport({

   host: env.SMTP_MAIL_HOST,

   port: env.SMTP_MAIL_PORT,

   auth: {

    user: env.SMTP_MAIL_USER,

    pass: env.SMTP_MAIL_PASSWORD,

   },

  });

  const message = {

   from: env.SMTP_MAIL_USER,

   to,

   subject,

   text,

   html,

  };

  transport.sendMail(message, (err) => {

   if (err) {

    return res.status(500).send(internalServerError());

   }

   return res.status(200).send(success("Email successfully sent."));

  });

 } else {

  return res.status(400).send(badRequest("Invalid or missing parameter."));

 }

});

emailServer.listen(env.HTTP_SERVER_PORT, () => {

 console.log(

  `\nE-mail Server \nHttp Server is running on IP Address = ${ip.address()} : ${

   env.HTTP_SERVER_PORT

  } \nTo stop use control + C\n`

 );

});

/src/env/index.ts

import "dotenv/config";

import { z } from "zod";

const envSchema = z.object({

 SMTP_MAIL: z.string(),

 SMTP_MAIL_HOST: z.string(),

 SMTP_MAIL_PORT: z.coerce.number().default(587),

 SMTP_MAIL_USER: z.string(),

 SMTP_MAIL_PASSWORD: z.string(),

 HTTP_SERVER_PORT: z.coerce.number().default(3030),

});

const _env = envSchema.safeParse(process.env);

if (_env.success === false) {

 console.error("Invalid environment variable", _env.error.format());

 throw new Error("Invalid environment variable");

}

export const env = _env.data;

/src/messages/errors.ts

export function badRequest(message?: string) {

 return {

  success: false,

  statusCode: 400,

  message: [],

  error: [{ error: message ? message : "Invalid or missing parameter." }],

 };

}

export function notFound(message?: string) {

 return {

  success: false,

  statusCode: 404,

  message: [],

  error: [{ error: message ? message : "Not found, is not registered." }],

 };

}

export function internalServerError() {

 return {

  success: false,

  statusCode: 500,

  message: [],

  error: [

   {

    error: "Server problems, please try again later.",

   },

  ],

 };

}

/src/messages/success.ts

export function success(message?: string) {

 return {

  success: true,

  statusCode: 200,

  message: [message],

  error: [],

 };

}

Este foi o último arquivo. Crie o projeto com tudo na sua devida pasta e tudo funcionará.

Espero ter ajudado.

Abraço.

Compartilhe
Comentários (1)
Andreza Cristina
Andreza Cristina - 29/08/2023 17:08

Obrigada por compartilhar