(intermediate value).sendEmail(...).promise is not a function - email

I'm using aws-sdk in my service to send emails. I'm getting below exception to a code which was working fine before.
const aws = require('aws-sdk');
var params = {
Destination: {
ToAddresses: [
'checkMail#gmail.com'
]
},
Message: {
Body: {
Html: {
Charset: "UTF-8",
Data: "HTML_FORMAT_BODY"
},
Text: {
Charset: "UTF-8",
Data: "this is sample"
}
},
Subject: {
Charset: 'UTF-8',
Data: 'Test email'
}
},
Source: 'AWS Services<awsEmails#awsService.com>'
ReplyToAddresses: [
'AwsServices<noreply#awsServices.com>'
],
};
// Create the promise and SES service object
var emailPromise = new aws.SES({apiVersion: '2010-12-01'}).sendEmail(params).promise();
// Handle promise's fulfilled/rejected states
emailPromise.then(
function(data) {
//my logic on success goes here
}).catch(
function(err) {
//my logic on error goes here
});
I have tried using different API calls for email from AWS but all returns the same error.

Avoid require ALL aws-sdk if it's just to use a single service. For using SES, you can yarn add #aws-sdk/client-ses and then use it const { SESClient, SendEmailCommand } = require("#aws-sdk/client-ses");
I show you here a full exemple of sending email with SES in a nodeJS lambda function:
const {
SESClient,
SendEmailCommand,
} = require("#aws-sdk/client-ses");
const REGION = "eu-west-3"; // Use you AWS region
const ses = new SESClient({ region: REGION });
exports.handler = async function (event) {
const path = event.path;
if (path === "/send-email") {
const peopleAmount = 12;
const params = {
Source: "John Wick <john.wick#killer.com>",
Destination: {
ToAddresses: ["adresse1#test.com"],
},
Message: {
Body: {
Html: {
Data: `<span>This email is about <b>${peopleAmount}</b> people.</span>`,
},
},
Subject: {
Data: "Email Title",
},
},
};
try {
const data = await ses.send(new SendEmailCommand(params));
return {
statusCode: 200,
body: peopleAmount,
};
} catch (e) {
console.error(e, e.stack);
return {
statusCode: 400,
body: "Sending failed",
};
}
}
}
I hope it helps, here is documentation to use SES email template.

Related

Can't access Pinia changed state in Prisma API call in a Nuxt 3 app

Somehow I when I make an API call using Prisma I can access only the default state:
import dbClient from '~/server/utils';
import { useTextStore } from '~/pinia/text'
export default defineEventHandler(async (event) => {
const { id } = event.context.params
const text = useTextStore()
const updatedText = await dbClient.opus.update({
where: {
id: parseInt(id),
},
data: {
content: text.content
},
});
return {
statusCode: 200,
body: text.content
}
})
Here's the Pinia store code:
import { defineStore } from 'pinia'
export const useTextStore = defineStore({
id: 'text',
state: () => {
return {
editor:'Введите текст',
}
},
actions: {
updateText(newContent) {
this.editor = newContent
}
},
getters: {
content: state => state.editor,
},
})
The state changes are shared across components and pages but can't get through to the eventHandler. Is it Nuxt 3 or some other mistake I should look into?

how to add channel id to push Notification payload

i am using push notification with local notification.. i have to set channel id in my payload..
here is my payload
i am not sure if this is payload for both andriod and ios. please help me out with correct payload.
thanks
exports.chatFunctions = functions.firestore.document("chat/{chatId}/Messages/{messagesId}").onCreate(async (snapshot, context) => {
if (!snapshot.exists) {
console.log('No Device');
}
const chatDatas = snapshot.data();
const messageTo = chatDatas['idTo'];
const deviceTokenuUser1 = await admin.firestore().collection('users').doc(messageTo).get();
const user1name = deviceTokenuUser1.data()['name'];
const user1Url = deviceTokenuUser1.data()['profilePictureUrl'];
let payload = {
notification: {
title: `${user1name}`,
body: `${chatDatas['content']}`,
},
data: {
key: 'chat',
id: `${messageTo}`,
click_action: "FLUTTER_NOTIFICATION_CLICK"
},
android: {
priority: "high",
},
apns: {
payload: {
aps: {
contentAvailable: true,
},
},
headers: {
"apns-push-type": "background",
"apns-priority": "5", // Must be `5` when `contentAvailable` is set to true.
"apns-topic": "io.flutter.plugins.firebase.messaging", // bundle identifier
},
},
token: deviceTokenuUser1.data()['tokens'],
};
try {
await admin.messaging().send(payload);
console.log("Firebase chat Messaging Successfully");
} catch (err) {
console.log("error from chat messaging " + err);
}
You can add channel id like this:
let payload = {
// ...
android: {
priority: "high",
notification: {
channelId: "yourchannelid"
}
}
// ...
}

How to use Custom HTTP request and paginations, sort, search in Vue 2.x

I am an engineer who makes web systems in Tokyo.
I'm making a search system using Grid.js, but I faced a problem.
I don't know the solution because it's not in the documentation.
Since this system uses Vue 2.x, it uses axios.post with Custom HTTP Requset.
I was able to get the list, but I'm having trouble implementing sorting, pagination, and keyword search.
I want to send parameters by Post request.
Please tell me how to implement this.
The code is below
data() {
return {
columns: [
{name: 'user name', id: 'user_name'},
{name: 'email', id: 'email'},
],
page: {
enabled: true,
limit: 100,
server: {
body: (prev, page) => {
console.log(page) // OK, show page number 0,1,2...
return {
page: page
}
}
},
},
sort: {
},
search: {
server: {
// url: (prev, keyword) => `${prev}?q=${keyword}`
// what's this.
}
},
server: {
url: '/api/v2/users/list',
method: 'POST',
async data (opt) {
let response = await axios.post(opt.url)
return {
data: response.data.results.map(item => {
return {
username: item.username,
email: item.email,
}
}),
total: response.data.count,
}
}
},
};
OK.
Set POST payload this.
data() {
return {
columns: [
{name: 'user name', id: 'user_name'},
{name: 'email', id: 'email'},
],
page: {
enabled: true,
limit: 100,
server: {
body: (prev, page) => {
console.log(page) // OK, show page number 0,1,2...
return {
page: page
}
}
},
},
sort: {
},
search: {
server: {
// url: (prev, keyword) => `${prev}?q=${keyword}`
// what's this.
}
},
server: {
url: '/api/v2/users/list',
method: 'POST',
body: {},
async data (opt) {
let response = await axios.post(opt.url)
return {
data: response.data.results.map(item => {
return {
username: item.username,
email: item.email,
}
}),
total: response.data.count,
}
}
},
};

How to implement a PUT request in Vue 3

I am trying to implement a PUT request to the https://crudcrud.com/ REST API.
I have a list of users and when I click an update button, I would like to show a modal and allow the user to update any of the fields (name, email, image URL). The main concern is that I am struggling with how to format the PUT request.
This is my current solution
// template (UserCrud.vue)
<button #click="update(user._id)">Update</button>
// script
components: { Create },
setup() {
const state = reactive({
users: [],
})
onMounted(async () => {
const { data } = await axios.get(`/users`)
state.users = data
})
async function update(id) {
await axios.put(`/users/${id}`)
state.users = ???
}
return { state, destroy, addUser }
Here is some sample data:
[
{
"_id": "6012303e37711c03e87363b7",
"name": "Tyler Morales",
"email": "moratyle#gmail.com",
"avatar": "HTTP://linkURL.com
},
]
For reference, this is how I create a new user using the POST method:
export default {
components: { Modal },
emits: ['new-user-added'],
setup(_, { emit }) {
const isModalOpen = ref(false)
const state = reactive({
form: {
name: '',
email: '',
avatar: '',
},
})
async function submit() {
const { data } = await axios.post('/users', state.form)
emit('new-user-added', data)
state.form.email = ''
state.form.name = ''
state.form.avatar = ''
isModalOpen.value = false
}
return { isModalOpen, submit, state }
},
}
Check this repo for the complete repo: the files are UserCrud.vue & Create.vue
You should pass the user object as parameter then send it as body for the put request by setting the id as param :
<button #click="update(user)">Update</button>
...
async function update(user) {
let _user={...user,name:'Malik'};//example
await axios.put(`/users/${user._id}`,_user);
const { data } = await axios.get(`/users`)
state.users = data
}
You could use the same code of adding new user for the update by defining a property called editMode which has true in update mode and based on this property you could perform the right request
export default {
components: { Modal },
emits: ['new-user-added','user-edited'],
props:['editMode','user'],
setup(props, { emit }) {
const isModalOpen = ref(false)
const state = reactive({
form: {
name: '',
email: '',
avatar: '',
},
})
onMounted(()=>{
state.form=props.user;//user to edit
})
async function submit() {
if(props.editMode){
const { data } = await axios.put('/users/'+props.user._id, state.form)
emit('user-edited', data)
}else{
const { data } = await axios.post('/users', state.form)
emit('new-user-added', data)
state.form.email = ''
state.form.name = ''
state.form.avatar = ''
}
isModalOpen.value = false
}
return { isModalOpen, submit, state }
},
}

Sengrid template substitution tags not replaced when sending email in Meteor app

In Meteor application that incorporates Sendgrid transaction email templates for user invitations and notifications, I can't manage to replace substitution tags. Templated email is received, but without any difference.
Email.send({
from: "hello#domain.com",
to:email,
subject: "Subject",
sub: {
"{name}":post.createdBy,
"{title}":post.title,
},
headers: {
"X-SMTPAPI": {
"filters": {
"templates": {
"settings": {
"enable": 1,
"template_id": "xxxx"
}
}
}
},
"Content-Type" : "text/html"
}
});
I'm not using API directly, but rather Meteor Email package, but don't see that possible issue:
Meteor.startup(function () {
process.env.MAIL_URL = 'smtp://username:password#smtp.sendgrid.net:587';
});
This is my shortened email template:
Hey {name},
your post {title} has a new comment.
You need to put the subs in the X-SMTPAPI header as well. The X-SMTPAPI header itself should also contain valid JSON in a string.
Try this:
var xsmtpapi = {
"filters": {
"templates": {
"settings": {
"enable": 1,
"template_id": "xxxx"
}
}
},
"sub": {
"{name}": post.createdBy,
"{title}": post.title
}
}
Email.send({
from: "hello#domain.com",
to:email,
subject: "Subject",
sub: {
"{name}":post.createdBy,
"{title}":post.title,
},
headers: {
"X-SMTPAPI": JSON.stringify(xsmtpapi),
"Content-Type" : "text/html"
}
});
What I ended up doing was using smtpapi-nodejs NPM package.
The simple example would be:
var nodemailer = require('nodemailer');
var smtpapi = require('smtpapi');
var header = new smtpapi();
header.setFilters({
"templates": {
"settings": {
"enable": 1,
"template_id": xxx-template-id-xxx
}
}
});
header.addSubstitution('-name-', post.createdBy);
header.addSubstitution(-title-', post.title);
var headers = { 'x-smtpapi': header.jsonString() };
// Use nodemailer to send the email
var settings = {
host: "smtp.sendgrid.net",
port: parseInt(587, 10),
requiresAuth: true,
auth: {
user: "sendgrid_username",
pass: "sendgrid_password"
}
};
var smtpTransport = nodemailer.createTransport(settings);
var mailOptions = {
from: "Fred Foo <foo#blurdybloop.com>",
to: "bar#blurdybloop.com",
subject: "Hello",
text: "Hello world",
html: "<b>Hello world</b>",
headers: headers
}
smtpTransport.sendMail(mailOptions, function(error, response) {
smtpTransport.close();
if (error) {
console.log(error);
} else {
console.log("Message sent: " + response.message);
}
});