erst_dev
erst_dev

Reputation: 319

Can't send email with nestjs and nodemailer

I try to send email from server with nodemailer and nestjs.

Here is module configuration

import { Module } from "@nestjs/common";
import { MailService } from "./services/mail/mail.service";
import { MailController } from "./controllers/mail/mail.controller";
import { MailerModule } from "@nestjs-modules/mailer";

@Module({
    controllers: [MailController],
    providers: [MailService],
    imports: [
        MailerModule.forRoot({
            transport: {
                host: process.env.EMAIL_HOST,
                port: process.env.EMAIL_PORT,
                secure: true,
                auth: {
                    user: process.env.EMAIL_ID,
                    pass: process.env.EMAIL_PASS
                }
            }
        })
    ]
})
export class MailModule {
}

and the method

@import { MailerService } from "@nestjs-modules/mailer";

constructor(private mailer: MailerService) {
}

async sendConfirmationLetter(to: string): Promise<void> {
        try {
            await this.mailer.sendMail({
                to: 'to',
                from: 'from',
                subject: 'subject',
                text: 'some text'
            });
        } catch (e) {
            console.log(e);
        }
    }

but I have an exception

Error: connect ECONNREFUSED 127.0.0.1:465
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1139:16) {
  errno: -4078,
  code: 'ESOCKET',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 465,
  command: 'CONN'
}

What am I doing wrong? All information is taken from the documentation https://nest-modules.github.io/mailer/docs/mailer.html

Please, help!

If some information is not enough, I can provide it

Upvotes: 2

Views: 8860

Answers (1)

Yu Yenkan
Yu Yenkan

Reputation: 765

MailerModule.forRoot({
   transport: {
        host: process.env.EMAIL_HOST, // change to your email smtp server like www.example.com
        port: process.env.EMAIL_PORT, // change to configured tls port for smtp server
        secure: true,
        auth: {
            user: process.env.EMAIL_ID,
            pass: process.env.EMAIL_PASS
        }
    }
})

you are using your host and port for smtp server, if u had setup the smtp on the same instance it show be fine, but I don think it is same port and host should be domain also.

If u plan to use gmail smtp then the setting should be

MailerModule.forRoot({
   transport: {
        host: "smtp.gmail.com",
        port: "465",
        secure: true,
        auth: {
            user: "your_gmail_email",
            pass: "your_gmail_app_password"
        }
    }
})

Upvotes: 3

Related Questions