Dynamic sendgrid templates being sent as plain text - javascript

I'm sending email through sendgrid, but when I receive the email, the email is in plain text format, and I would like to send it in html format.
The variable data is the data I pass to sgMail.send.
module.exports = {
data: {
to: '',
from: '',
subject: '',
text: '',
templateId: '',
dynamic_template_data: {
value_precip: undefined,
value_humidity: undefined,
value_windSpeed: undefined,
value_condition: undefined,
value_activiti: undefined
}
},
set: function(to, from, subject, text, templateId, params) {
this.data.to = to
this.data.from = from
this.data.subject = subject
this.data.text = text
this.data.templateId = templateId,
this.data.dynamic_template_data.value_precipitation = params.value_precipitation
this.data.dynamic_template_data.value_humidity = params.value_humidity
this.data.dynamic_template_data.value_windSpeed = params.value_windy
this.data.dynamic_template_data.value_condition = params.value_condition
this.data.dynamic_template_data.value_activiti = params.value_activiti
},
send: function() {
try {
sgMail.send(this.data)
} catch (error) {
console.log(error)
}
}
}
I don't know what may be causing this problem, if anyone can help me I would be grateful!

It's simple, just remove the text.
As mentioned by a contributor of SendGrid. Read more
Given that dynamic templates contain both HTML and plain text content, text should not be passed when using a dynamic template.

It looks like SendGrid uses html attribute to decide if the content type should be html even though they ignore the content. So, just include that attribute in the payload. Seems weird, but it worked for me.
P.S.: I didn't try it with JavaScript, I'm using Python.

Related

sending value of my textarea with graphql

I hope you all have a great day. I am coding my own personal website and I have a section called to contact me. The problem I have with this section is that I am trying to send my client email to my email and when I am trying to send their message to my server through Graphql I get this error
[
{
"message": "Syntax Error: Unterminated string.",
"locations": [
{
"line": 3,
"column": 123
}
]
}
]
the request I sent to my server is
'\n mutation{\n sendEmail(EmailInput: {name: "Test name", email: "Test#email.com",
subject: "this is test subject", message: "\n
this is the first line \nthis is the second line\nwhen I have multiple lines I have these problem\n
"}) {\n success\n message\n }\n }\n '
I don't know how to fix it I don't know why I get this error.
I used fetch to send my code backend :
const emailMutationQuery = `
mutation{
sendEmail(EmailInput: {name: "${senderName.value}", email: "${senderEmail.value}", subject: "${senderSubject.value}", message: "
${senderMessage.value}
"}) {
success
message
}
}
`;
const result = await fetch("http://localhost:2882/graphql", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
query: emailMutationQuery,
}),
});
const convertedResult = await result.json();
GraphQL supports variables, which can be used to supply input data separately from the query. The variables are just a separate JSON-encoded object. This avoids syntactic difficulties (and potential security risks!) from trying to embed the inputs directly in the query.
For this you'd write a fixed query, that declares and uses the variable, but doesn't depend on the per-request inputs
const emailMutationQuery = `
mutation SendEmail($emailInput: SendEmailInput!) {
sendEmail(EmailInput: $emailInput) {
success
message
}
}
`;
You'd then create a second object containing the variable(s). The top-level keys match what you declare in the GraphQL operation line, and their content matches the corresponding GraphQL input types.
const variables = {
emailInput: {
name: senderName.value,
email: senderEmail.value,
subject: senderSubject.value,
message: senderMessage.value
}
};
Note that this is an ordinary Javascript object, and we haven't quoted or escaped anything here.
Now when we make the request, we send the query and variables together
const result = await fetch("http://localhost:2882/graphql", {
...,
body: JSON.stringify({
query: emailMutationQuery,
variables: variables
})
});
Things like newlines in the message content will be escaped in the variables block, and get passed through correctly to the underlying GraphQL engine.
I actually find a solution for it but feel free to share your answers here. The solution I found for this problem was that you have to use JSON.stringify() for the textarea. you have to pass your textarea value to this function and js will take care of the rest. my code now looks like this
const emailMutationQuery = `
mutation{
sendEmail(EmailInput: {name: "${senderName.value}", email: "${senderEmail.value}", subject: "${senderSubject.value}",
message:${JSON.stringify(senderMessage.value)}}) {
success
message
}
}
`;
I hope this help you guys.

sendgrid mail sending error upon placing multiple receiver

I'm using const sgMail = require('#sendgrid/mail'); and utilizing sendgrid version 7.6.2.
When I'm adding two email addresses in array and passing that into send() or sendMultiple() it's throwing me error like this.
status: 'failed',
> Error: Error: String expected for `email`
here's the section where I'm putting the multiple emails,
mailsTo = {
email: ["demo#email.com", "demo1#email.com"],
name: "demo",
type: 'to'
}
here if I pass one email as in form of string the mail is getting triggered. Can anyone please suggest what am I doing wrong.
Thanks in advance
According to the documentation the addresses are to be passed as an array of EmailData (string or object with email and name).
Please try the following:
mailsTo = [
{
email: "demo#email.com",
name: "demo"
},
{
email: "demo1#email.com",
name: "demo"
}
]
Assuming mailsTo is being pass as the to parameter for

Is it possible to store a user id as the key of a field in a Firestore document?

So I saw this in the "Get to know Firestore" youtube series from the official Firebase channel, where they used a userId as the key of a field. However, I can't seem to recreate this in my project using "firebase": "^9.6.6", and angular 13.0.4.
private async addMemberToGroupDetail(groupId: string) {
const groupRef = doc(this.firestore, 'groupDetail', groupId);
const userId = this.authService.userId;
updateDoc(groupRef, {
roles: {
`${userId}`: 'member',
},
});
}
Error: Property assignment expected.
Give this syntax a shot:
updateDoc(groupRef, {
roles: {
[`${userId}`]: 'member',
},
});
Might just need those square brackets as assigning the key dynamically.
As #Frank added in comments, if you don't need to convert to string, you can just do:
[userId]: 'member'

SUPABASE/JavsScript: how to DELETE user metadata?

Is there a way to delete user metadata in Supabase? They offer update() option, but it seems it works as patch request, so I can't find a way to delete it.
Here's their code:
```const { user, error } = await supabase.auth.update({
data: { hello: 'world' }
});```
I tried to do this:
```const { user, error } = await supabase.auth.update({
data: {}
});```
But is doesn't do anything.
Can metadata be deleted?
Thanks
It is possible to set the metadata field to an empty JSON object (i.e. {}) but, currently, there is no way to set it to NULL. Also, you would need to know all the fields that are already stored in the metadata because you need to remove each one explicitly.
If this works for your scenario, the way to do it is to send a data object where each field that you want removed has a value of null.
For example, if you have the following JSON in your metadata: { 'field1': 2, 'field2': 'something' }, you can set the metadata to an empty JSON object like this:
supabase.auth.update({ 'data': { 'field1': null, 'field2': null } });

pg-promise ColumnSet use Postgres functions with def property

I am using a ColumnSet and the helper.insert function for a multi row insert.
I have a table column where I want to use the Postgres Date/Time now() function.
const cs = new helpers.ColumnSet([
'lastname',
{
name: 'rental_date',
def: 'now()'
}
], { table: { table: 'book_rental', schema: 'public' } })
let rentals = [
{
lastname: 'Mueller'
},
{
lastname: 'Johnson'
}
]
let insert = helpers.insert(rentals, cs)
db.result(insert)
.then(data => res.json({ message: 'Ok!' }))
.catch(err => res.json({ message: 'Not ok!' }))
It seems to be working by using def: 'now()', but I want to make sure that I am using it the right way.
Edit:
Regarding the answer in the comment. I tried to do the insert manually and it looks like Postgres is converting the 'now()' string into the now() function.
INSERT INTO book_rental (lastname, rental_date) VALUES ('Mueller', 'now()');
To involve your answer, am I right that this should be the correct code then?
const cs = new helpers.ColumnSet([
'lastname',
{
name: 'rental_date',
mod: ':raw',
def: 'now()'
}
], { table: { table: 'book_rental', schema: 'public' } })
Your code doesn't look right, for the following reasons:
You want to use now() without any condition, but the def value is only used when the property doesn't exist in the source object (see Column). The init callback is what should be used instead to guarantee the right value override.
You return now() as an escaped string, while the query needs it as a raw-text string.
First, let's declare a reusable Raw Text string, as per Custom Type Formatting:
const rawText = text => ({toPostgres: () => text, rawType: true});
Then you can define the column like this:
{
name: 'rental_date',
init: () => rawText('now()')
}
And make sure you are using the latest version of pg-promise (v7.2.1 as of this writing).
Or alternatively, you can declare it like this:
{
name: 'rental_date',
mod: ':raw', // same as mode: '^'
init: () => 'now()'
}
This syntax however will work in all versions of the library, and perhaps is even simpler to use ;)

Categories