How to send zip file using #sendgrid/mail - javascript

This is the code I have written to send email with attachment using #sendgrid
const mailOptions = {}
if(mailOptions){
mailOptions.from = 'APP NAME'
mailOptions.to = 'emailId'
mailOptions.subject = 'Subject' // Subject line
//mailOptions.attachments = attachments
mailOptions.text = 'attachments'
}
const sendEmail = await sgMail.send(mailOptions)
But it only sends the mail with subject "no attachment"
The error I am getting when I uncomment the attachment line
{ Error: Bad Request
at Request.http [as _callback] (node_modules/#sendgrid/client/src/classes/client.js:124:25)
Why this is happening can someone please help me.

It's been a while since this question has been asked, but answering for future reference.
In order to fix the error, the attachment must have Base64 encoding - and its filetype should be set to 'application/zip'. The .js code to be input has also been vastly updated. An example today would look as follows
const sgMail = require('#sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const fs = require("fs");
pathToAttachment = `${__dirname}/attachment.zip`;
attachment = fs.readFileSync(pathToAttachment).toString("base64");
const msg = {
to: 'test#example.com',
from: 'test#example.com',
subject: 'Subject',
text: 'Sent using Node.js',
attachments: [{
content: data.toString('base64'),
filename: filename,
type: fileType,
disposition: 'attachment',
}, ],
};
sgMail.send(msg).catch(err => {
console.log(err);
});
Happy coding!

Related

react-native-mail: app crashing with attachment for Android v11

I'm using react-native-mail in my React Native app. This is my code:
const path = RNFetchBlob.fs.dirs.CacheDir + '/' + SHA1(this.fileSource.uri) + '.pdf'
const self = this;
let data = this.fileSource.uri.replace(/data:application\/pdf;base64\,/i, '');
RNFetchBlob.fs
.writeFile(path, data, 'base64')
.then(() => {
Mailer.mail({
subject: "Subject",
body: "",
recipients: [this.props.emailAddress],
attachment: {
path: path,
type: 'pdf',
name: `attachment.pdf`,
}
}, (error) => {
...
});
})
.catch(() => {
...
})
The value of path is "/data/user/0/com.<my-app-name>/cache/5cae2ea1e235873729dd158e19f3d122a1b46c73.pdf"
The value of data is TIAoxIDAgb2JqIAo8PCAKL1R5cGUgL0NhdGFsb2cgCi9QYWdlcyAyIDAgUiAKL1BhZ2VNb... (very long)
The mail() method throws the error Failed to find configured root that contains /data/user/0/com.<my-app-name>/cache/5cae2ea1e235873729dd158e19f3d122a1b46c73.pdf
Android version: 11
react-native: 0.63.4
rn-fetch-blob: 0.12.0
react-native-mail: git+https://github.com/marcinolek/react-native-mail.git
Does anyone know how I can approach this?
Try changing the file location on an external path.

How to fix error 50035 number type coerce when registering commands

I am trying to make a discord bot and I haven't used slash commands before as I haven't made a bot in a while, and I am getting this error when trying to register my commands:
DiscordAPIError[50035]: Invalid Form Body
application_id[NUMBER_TYPE_COERCE]: Value "undefined" is not snowflake.
guild_id[NUMBER_TYPE_COERCE]: Value "undefined" is not snowflake.
at SequentialHandler.runRequest (/home/runner/blkt/node_modules/#discordjs/rest/dist/index.js:708:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async SequentialHandler.queueRequest (/home/runner/blkt/node_modules/#discordjs/rest/dist/index.js:511:14) {
rawError: {
code: 50035,
errors: { application_id: [Object], guild_id: [Object] },
message: 'Invalid Form Body'
},
code: 50035,
status: 400,
method: 'put',
url: 'https://discord.com/api/v9/applications/undefined/guilds/undefined/commands',
requestBody: { files: undefined, json: [ [Object] ] }
}
I am following the discordjs.guide tutorial and my deploy-commands.js code is this:
const token = process.env['token'];
const clientId = process.env['clientid'];
const guildId = process.env['testguildid']
const fs = require('node:fs');
const path = require('node:path');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const commands = [];
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
commands.push(command.data.toJSON());
}
const rest = new REST({ version: '9' }).setToken(token);
rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands })
.then(() => console.log('Successfully registered application commands.'))
.catch(console.error);
application_id[NUMBER_TYPE_COERCE]: Value "undefined" is not snowflake.
guild_id[NUMBER_TYPE_COERCE]: Value "undefined" is not snowflake.
Please make sure you are inputting right IDs as String
const clientId = process.env['clientid'];
const guildId = process.env['testguildid']
go to your .env file and make sure
clientid=ID
testguildid=ID
and make sure you are initializing config of the .env file with library like dotenv
url: 'https://discord.com/api/v9/applications/undefined/guilds/undefined/commands',
As you see here both have values of undefined

Can't figure out why I am getting this error in my terminal while creating a webpage with the help of API

This is my javascript code . while I am running it using nodemon I am getting error in my terminal . The error is mentioned at the bottom of the code
const express=require("express");
const bodypraser=require("body-parser");
const request =require("request");
const https=require("https");
const app=express();
app.use(express.static("public"));
app.use(bodypraser.urlencoded({extended:true}))
posting from route
app.post("/",function(req,res)
{
const firstname=req.body.fname;
const lastname=req.body.lname;
const email=req.body.email;
const data={
members:[
{
email_address:email,
status:"suscribed",
merge_fields:{
FNAME:firstname,
LNAME:lastname
}
}
]};
const jsondata=JSON.stringify(data);
const url= "https://us1.api.mailchimp.com/3.0/lists/a6b99f4c3c";
creating option object
const options={
method:"POST",
auth:"deco:d6550609e1d79db44b409d81841d74bf-us1"
}
const request=https.request(url,options,function(response){
response.on("data",function(data){
console.log(JSON.parse(data));
})
})
request.write(jsondata);
request.end();
});
app.get("/" ,function(req ,res){
res.sendFile(__dirname+"/signup.html");
});
app.listen(3000,function(req,res){
console.log("ok ");
});
End of code
This is the error which I am facing in my terminal
{
type: 'https://mailchimp.com/developer/marketing/docs/errors/',
title: 'Invalid Resource',
This is the error status
status: 400,
detail: "The resource submitted could not be validated. For field-specific
details, see the 'errors' array.",
instance: '26cacd7a-d1b6-4195-9407-9eb39a9ec224',
errors: [
{
field: 'members.item:0.status',
message: 'Data presented is not one of the accepted values: subscribed,
unsubscribed, cleaned, pending.'
}
]
}
Read the error message. Mailchimp requires status to be one of the four values mentioned in the error. Your status has two typos (status:"Suscribed") instead of subscribed (note the case sensitivity).
Next time you post a question please use proper code indentation.

SendGrid No response from send function if attachment exists

Issue Summary
If I try to send an email with attachment added, I get no Promise resolve and no response, However, if I comment out the attachment logic, I receive an error (I entered invalid token to get an error), like I expected. The path to the doc file is real, but for this piece of code I changed it.
Code not working:
const fs = require('fs');
const sgMail = require('#sendgrid/mail');
(async () => {
sgMail.setApiKey('SG.XXXXXXXXXX-XXXXXXXXXX-XXXXXXXXXX-XXXXXXXXXX-XXXXXXXXXXX');
const pathToAttachment = 'Path\\To\\doc\\file.doc';
const attachment = fs.readFileSync(pathToAttachment).toString('base64');
const msg = {
to: 'myemail#gmail.com',
from: 'youremail#gmail.com',
subject: 'test',
text: 'test',
attachments: [
{
content: attachment,
filename: 'file.doc',
type: 'application/doc',
disposition: 'attachment'
}
]
};
let result = null;
try {
result = await sgMail.send(msg);
console.log('sent!');
} catch (err) {
console.error(err.toString());
}
console.log(`result: ${result}`);
})();
Not getting any response, the code ignores the rest of any code that goes after the 'send' function.
Code working:
const fs = require('fs');
const sgMail = require('#sendgrid/mail');
(async () => {
sgMail.setApiKey('SG.XXXXXXXXXX-XXXXXXXXXX-XXXXXXXXXX-XXXXXXXXXX-XXXXXXXXXXX');
const pathToAttachment = 'Path\\To\\doc\\file.doc';
const attachment = fs.readFileSync(pathToAttachment).toString('base64');
const msg = {
to: 'myemail#gmail.com',
from: 'youremail#gmail.com',
subject: 'test',
text: 'test',
/* attachments: [
{
content: attachment,
filename: 'file.doc',
type: 'application/doc',
disposition: 'attachment'
}
] */
};
let result = null;
try {
result = await sgMail.send(msg);
console.log('sent!');
} catch (err) {
console.error(err.toString());
}
console.log(`result: ${result}`);
})();
Code works as I expected, getting:
Unauthorized (401)
The provided authorization grant is invalid, expired, or revoked
null
null
result: null
Technical details:
"#sendgrid/mail": "^7.4.0"
node version: v14.15.1
I posted an issue on this on the their GitHub page:
https://github.com/sendgrid/sendgrid-nodejs/issues/1220
But they seem not to be able to produce the bug.Has anyone else faced this issue before?
As I write to SendGrid developers, they admit it's a bug on their package and it will be fixed:
"#orassayag Thanks for providing more information. I was able to
recreate this issue and it looks like a bug on our end. We will add it
to our internal backlog to be prioritized. Pull requests and +1s on
the issue summary will help it move up the backlog. In the meantime I
would suggest using node version 12.20.0 and Sendgrid/mail: 7.4.0 as a
work around solution for now. Using these versions, I was able to get
the error logs to show up when attaching the same file."
Question close.
here

Why can't I send to more than one address using AWS SDK sendEmail?

I started implementing the AWS SDK into our application to send emails. I increased our limit through AWS to get out of the sandbox so that I could start sending emails to other people. The problem I'm noticing is that if I have more than one address in my recipient variable that I get this error: Illegal Address. Both email addresses are in the form name#domain.com. I've tested sending to each email individually and both work just fine, but as soon as I put both addresses into the recipient variable I get the Illegal Address error. My only assumption is that having more than one recipient is causing the issue, but if this is the problem then why does their documentation say that there can be multiple addresses included?
Here is my code
if ((request.url).substring(0, 5) == "/send") {
var mailOptions = {
to: request.query.to,
bcc: request.query.bcc,
subject: request.query.subject,
text: request.query.text
}
console.log(mailOptions.to);
AWS.config.update({
accessKeyId: env.AWS.ACCESS_KEY,
secretAccessKey: env.AWS.SECRET_ACCESS_KEY,
region: 'someregion'
});
const sender = "noreply#domain.com";
const recipient = mailOptions.to; // this includes "name#domain.com, name2#domain.com"
const subject = mailOptions.subject;
const body_html = mailOptions.text;
const charset = "UTF-8";
const ses = new AWS.SES();
var params = {
Source: sender,
Destination: {
ToAddresses: [
recipient
],
BccAddresses: [
sender
],
},
Message: {
Subject: {
Data: subject,
Charset: charset
},
Body: {
Html: {
Data: body_html,
Charset: charset
}
}
}
};
ses.sendEmail(params, function(err, data) {
// If something goes wrong, print an error message.
if(err) {
console.log(err.message);
} else {
console.log("Email sent! Message ID: ", data.MessageId);
}
});
If anyone knows why this is happening and knows what I need to do to fix it, I would greatly appreciate it! Thanks.

Categories