I'm trying to send an ejs template with email-templates but I'm not having much joy.
The email sends fine, however it doesn't contain any template data.
const email = new Email ({
template: 'activateAccount',
message: {
from: "noreply#domain.com",
subject: "Activate your account!",
to: data.email
},
locals: {
name: data.name,
url: data.url
},
send: true,
transport: {
host: "domain.com",
port: 2525,
auth: {
user: "abc",
pass: "123"
}
},
views: {
options: {
extension: 'ejs'
}
}
});
return await email.send();
Does anyone know why the templates aren't being populated?
Use the locals when .sending the email,
const email = new Email({
message: {
from: "noreply#domain.com",
subject: "Activate your account!",
to: data.email
},
send: true,
transport: {
host: "domain.com",
port: 2525,
auth: {
user: "abc",
pass: "123"
}
},
views: {
options: {
extension: 'ejs'
}
}
});
await email.send({
template: 'activateAccount',
locals: {
name: data.name,
url: data.url
}
});
Basically, you can use all the options is .send function itself.
Related
I have a javascript file on my NodeJS server that runs at 00:00:00 and updates some fields in the database, if that happens I want to send out a push notification to some users. I've set this up in my Javascript file:
https://dev.to/devsmranjan/web-push-notification-with-web-push-angular-node-js-36de
const subscription = {
endpoint: '',
expirationTime: null,
keys: {
auth: '',
p256dh: '',
},
};
const payload = {
notification: {
title: 'Title',
body: 'This is my body',
icon: 'assets/icons/icon-384x384.png',
actions: [
{action: 'bar', title: 'Focus last'},
{action: 'baz', title: 'Navigate last'},
],
data: {
onActionClick: {
default: {operation: 'openWindow'},
bar: {
operation: 'focusLastFocusedOrOpen',
url: '/signin',
},
baz: {
operation: 'navigateLastFocusedOrOpen',
url: '/signin',
},
},
},
},
};
const options = {
vapidDetails: {
subject: 'mailto:example_email#example.com',
publicKey: process.env.REACT_APP_PUBLIC_VAPID_KEY,
privateKey: process.env.REACT_APP_PRIVATE_VAPID_KEY,
},
TTL: 60,
};
webpush.sendNotification(subscription, JSON.stringify(payload), options)
.then((_) => {
console.log(subscription);
console.log('SENT!!!');
console.log(_);
})
.catch((_) => {
console.log(subscription);
console.log(_);
});
But when I run the file I get the message:
{ endpoint: '', expirationTime: null, keys: { auth: '', p256dh: '' } } Error: You must pass in a subscription with at least an endpoint.
Which makes sense since the server has no idea about service workers etc. Any suggestions on how to proceed?
In the console I can see:
Sending message <c188880-8889928-1149-89243441014#example.com> to <example#gmail.com>
This is how I'm configuring the transport:
nodemailer.createTransport({
name: "mail.example.com",
host: "mail.example.com",
port: 587,
secure: false,
auth: {
user: "reminders#example.com",
pass: PASSWORD, //
},
logger: true,
tls: {
rejectUnauthorized: false,
},
});
transporter.sendMail() function gives me this data:
{
accepted: [ 'example#gmail.com' ],
rejected: [],
envelopeTime: 2111,
messageTime: 842,
messageSize: 28925,
response: '250 OK id=198wlQ-exatqE-Lz',
envelope: {
from: 'reminders#example.com',
to: [ 'example#gmail.com' ]
},
messageId: '<ccddd9-8311-795e-00c1-7a43f27b6b70#example.com>'
}
It used to work, I don't know what's changed.
I've checked the spam/junk folders in the receiver's account.
Try this instead:
let transporter = nodemailer.createTransport(({
service: "Outlook365",
host: "smtp.office365.com",
port: "587",
tls: {
ciphers: "SSLv3",
rejectUnauthorized: false,
},
auth: {
user: "reminders#example.com",
pass: PASSWORD, //
}
}));
let info = {
from: 'reminders#example.com',
to: `${email}`,
subject: "Subject text",
html: `text`
};
transporter.sendMail(info, function (err) {
if (err) {
console.log(err);
} else {
res.json({ message: "Message sent" });
};
});
I want to use handle bars template in my nest js application:
<!--confirmation.hbs-->
<p>Hello template</p>
This file is located in src/mail/templates/confirmation.hbs. Also i try to send this template as email:
//mail service
#Injectable()
export class EmailService {
constructor(private readonly mailerService: MailerService) {}
public example(): void {
this.mailerService
.sendMail({
to: 'mail', // list of receivers
from: 'test#nestjs.com', // sender address
subject: 'Testing Nest MailerModule ✔', // Subject line
template: './confirmation',
})
.then((r) => {
console.log(r, 'email is sent');
})
.catch((e) => {
console.log(e, 'error sending email');
});
}
}
My app.module.ts looks:
#Module({
imports: [
MailerModule.forRoot({
transport: {
service: 'Gmail',
auth: {
user: '---secret',
pass: '---secret',
},
},
defaults: {
from: '"No Reply" <no-reply#localhost>',
},
template: {
dir: __dirname + '/templates',
adapter: new HandlebarsAdapter(),
options: {
strict: true,
},
},
}),
TypeOrmModule.forRoot({
type: 'postgres',
host: 'localhost',
port: 5433,
username: '-',
password: '-',
database: '-',
entities: [RegisterEntity],
synchronize: true,
}),
AuthenticationModule,
],
controllers: [AppController, AuthenticationController],
providers: [AppService, AuthenticationService],
})
This is my main.ts
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.setGlobalPrefix(CONSTANTS.GLOBAL_PREFIX);
await app.listen(3000);
}
bootstrap();
This is my nest-cli.hbs
{
"collection": "#nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"assets": [
"mail/templates/**/*.hbs"
],
"watchAssets": true
}
}
The email is sent if don't send a template, so the code is working. Trying to send an email template like is my code above i get this error: TypeError: Cannot destructure property 'templateName' of 'precompile(...)' as it is undefined. Question: Why i get this issue and how to get rid of it?
Your files are located inside src/mail/templates/.
But in your module you have dir: __dirname + '/templates',.
Here __dirname returns app.module.ts folder location path which is src/.
change
dir: __dirname + '/templates',
to
dir: __dirname + '/mail/templates',
Since this bug is not yet released #743 (to this date), I rolled back to previous version:
npm i --save #nestjs-modules/mailer#1.6.0 --force
For me,this is a template file path issue.
Review your template.dir in your MailerModule config, and compare it to your project "dist" directory.
if your template file path is "dist/templates/template.hbs"
then your template.dir should be ${process.cwd()}/templates
else if your dist directory is "dist/src/templates/template.hbs" ,which is depend on your compile configs.
then your template.dir config should be join(__dirname, 'templates')
I'm using NestJs Mailer Module, the latest stable version. You can find the documentation here.
I've search a solution for this error but I found nothing:
Error: self signed certificate in certificate chain
app.module.ts:
#Module({
imports: [
MailerModule.forRoot({
transport: 'smtps://user#domain.com:pass#smtp.domain.com',
defaults: {
from:'"nest-modules" <modules#nestjs.com>',
},
template: {
dir: __dirname + '/templates',
adapter: new HandlebarsAdapter(),
options: {
strict: true,
},
},
}),
],
})
export class AppModule {}
sending the email:
this.mailerService.sendMail({
to: 'example#domain.com',
subject: 'subject'
text: 'blahblahblah'
html: 'blahblahblah'
}).then(() => {
this.logger.log('Error email sent!', 'HttpExceptionFilter');
}).catch(err => {
this.logger.error('Error while sending error email.', err, 'HttpExceptionFilter');
});
As a solution, you can use tls: { rejectUnauthorized: false } in your transport options.
I am trying to load some documents in my "Documents" database, but am getting this error on running node load.js(filename):
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:201:27) {
errno: -4077,
code: 'ECONNRESET',
syscall: 'read'
}
load.js
// Load documents into the database.
const marklogic = require('marklogic');
const my = require('./my-connection.js');
const db = marklogic.createDatabaseClient(my.connInfo);
// Document descriptors to pass to write().
const documents = [
{ uri: '/gs/aardvark.json',
content: {
name: 'aardvark',
kind: 'mammal',
desc: 'The aardvark is a medium-sized burrowing, nocturnal mammal.'
}
},
{ uri: '/gs/bluebird.json',
content: {
name: 'bluebird',
kind: 'bird',
desc: 'The bluebird is a medium-sized, mostly insectivorous bird.'
}
},
{ uri: '/gs/cobra.json',
content: {
name: 'cobra',
kind: 'mammal',
desc: 'The cobra is a venomous, hooded snake of the family Elapidae.'
}
},
];
// Load the example documents into the database
db.documents.write(documents).result(
function(response) {
console.log('Loaded the following documents:');
response.documents.forEach( function(document) {
console.log(' ' + document.uri);
});
},
function(error) {
console.log(JSON.stringify(error, null, 2));
}
);
my-connection.js
module.exports = {
connInfo: {
host: 'localhost',
port: 8000,
user: 'user',
password: 'password'
}
};