I am sending Emails via the aws-sdk for Nodejs like this:
const params = {
Destination: {
ToAddresses: [... ],
},
Message: {
Body: {
Html: {
Data: `...`,
Charset: 'utf-8'
},
},
Subject: {
Data: `...`,
Charset: 'utf-8'
}
},
Source: 'support#mydomain.com',
ReturnPath: 'support#mydomain.com',
};
awsConfig.ses.sendEmail(params, (err, data))
The received email looks like this in Gmail:
However, I want to know how to change this name:
Currently the from name is support, because the from email is support#mydomain.com. But I want it to be replaced by the company like GitHub below.
Thanks in advance for any help!
Here is what I ended up doing:
I set the Source attribute in the params to
'CompanyName <support#mydomain.com>'
Thanks to #Neil Lunn
You can use this syntax
// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({region: 'REGION'});
// Create sendEmail params
var params = {
Destination: { /* required */
CcAddresses: [
'EMAIL_ADDRESS',
/* more items */
],
ToAddresses: [
'EMAIL_ADDRESS',
/* more items */
]
},
Message: { /* required */
Body: { /* required */
Html: {
Charset: "UTF-8",
Data: "HTML_FORMAT_BODY"
},
Text: {
Charset: "UTF-8",
Data: "TEXT_FORMAT_BODY"
}
},
Subject: {
Charset: 'UTF-8',
Data: 'Test email'
}
},
Source: 'SENDER_EMAIL_ADDRESS', /* required */
ReplyToAddresses: [
'EMAIL_ADDRESS',
/* more items */
],
};
// Create the promise and SES service object
var sendPromise = new AWS.SES({apiVersion: '2010-12-01'}).sendEmail(params).promise();
// Handle promise's fulfilled/rejected states
sendPromise.then(
function(data) {
console.log(data.MessageId);
}).catch(
function(err) {
console.error(err, err.stack);
});
Related
I am trying to send a GMAIL message containing a PDF file (I am using nodemailer for this).
The error is generated when reading the PDF file with path (native dependency of node); The error that returns is a 500 Server Error.
module.exports.get_boletin = async (event) => {
const { wrapedSendMail } = require('./helpers/sendPromise');
const path = require('path');
const { email } = JSON.parse(event.body);
if(!email) {
return {
statusCode: 400,
body: JSON.stringify({
ok: false,
detail: 'Email is required'
})
};
}
const mailOptions = {
to: email,
from: "example#gmail.com",
subject: `any_msg`,
attachments: [
{
filename: `file.pdf`,
path: path.join(__dirname, `file.pdf`),
contentType: 'application/pdf',
},
],
}
const _send = await wrapedSendMail(mailOptions)
if(_send){
return {
statusCode: 200,
body: JSON.stringify({
ok: true,
detail: 'Mensaje enviado correctamente.',
event: JSON.parse(event.body)
})
}
} else {
return {
statusCode: 500,
body: JSON.stringify({
ok: false,
detail: 'Error al enviar el mensaje.',
event: JSON.parse(event.body)
})
}
}
};
This piece of code is the one that generates the error
attachments: [
{
filename: `file.pdf`,
path: path.join(__dirname, `file.pdf`),
contentType: 'application/pdf',
},
]
I tried locally and in an EC2 instance, this works normally the error is only generated in Lambda
I am using the nodejs environment to integrate PayTm payment gateway with Custom Checkout approach as mentioned in the link and on this process I need to use the Initiate Transaction API. Now the issue is, whenever I am calling the Initiate Transaction API from nodejs the paytm server server is responding as bellow-
{"head":{"requestId":null,"responseTimestamp":"1607066431489","version":"v1"},"body":{"extraParamsMap":null,"resultInfo":{"resultStatus":"U","resultCode":"00000900","resultMsg":"System error"}}}
So it has become hard to make out if I am missing out something on my code or the integration process mentioned in the document has missed something either. Please suggest. My code base is already mentioned below-
`
const https = require('https');
/* import checksum generation utility */
var PaytmChecksum = require("paytmchecksum");
//FOR TEST/STAGING OF APPLICATION
const MERCHANT_ID = 'XXXXXXXXXXXXXXXXXXX';
const MERCHANT_KEY = 'XXXXXXXXXXXXXXX';
function initPayProcess(orderId, payVal, custId, custMobile, custEmail) {
var paytmParams = {};
paytmParams.body = {
"requestType": "Payment",
"mid": MERCHANT_ID,
"websiteName": "WEBSTAGING",
"orderId": orderId,
"callbackUrl": "",
"txnAmount": {
"value": payVal,
"currency": "INR",
},
"userInfo": {
"custId": custId,
"mobile": custMobile,
"email": custEmail,
},
"enablePaymentMode": {
"mode": "BALANCE",
}
};
/*
* Generate checksum by parameters we have in body
* Find your Merchant Key in your Paytm Dashboard at https://dashboard.paytm.com/next/apikeys
*/
return PaytmChecksum.generateSignature(JSON.stringify(paytmParams.body), MERCHANT_KEY)
.then(function (checksum) {
paytmParams.head = {
"signature": checksum
};
var post_data = JSON.stringify(paytmParams);
var options = {
/* for Staging */
hostname: 'securegw-stage.paytm.in',
port: 443,
path: '/theia/api/v1/initiateTransaction?mid=' + MERCHANT_ID + '&orderId=' + orderId,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': post_data.length
}
};
var response = "";
var post_req = https.request(options, function (post_res) {
post_res.on('data', function (chunk) {
response += chunk;
});
post_res.on('end', function () {
console.log('Response: ', response);
//return response;
});
});
post_req.write(post_data);
post_req.end();
return post_data;
});
}
module.exports = { getCheckSum, initPayProcess };
`
I have also stumbled across this issue few months back and fortunately paytm devs replied to my email, had a few email discussions and found below code to be working for me.
Do remember to import Paytm from its node js library as shown in below code.
const Paytm = require("paytmchecksum");
var paytmParams = {};
paytmParams = {
body: {
requestType: "Payment",
mid: config.PaytmConfig.stag.mid,
orderId: "ORDS" + new Date().getTime(),
websiteName: config.PaytmConfig.stag.website,
txnAmount: {
value: paymentDetails.amount.toString(),
currency: "INR",
},
userInfo: {
custId: paymentDetails.customerId,
},
disablePaymentMode: [
{
mode: "CREDIT_CARD",
},
],
callbackUrl: process.env.HOST_URL + "/callbackfun",
},
};
/*
* Generate checksum by parameters we have in body
* Find your Merchant Key in your Paytm Dashboard at https://dashboard.paytm.com/next/apikeys
*/
const checksum = await Paytm.generateSignature(
JSON.stringify(paytmParams.body),
config.PaytmConfig.stag.key
);
// .then(function (checksum) {
paytmParams.head = {
channelId: "WAP",
signature: checksum,
};
var post_data = JSON.stringify(paytmParams);
var options = {
/* for Staging */
hostname: "securegw-stage.paytm.in",
/* for Production */ // hostname: 'securegw.paytm.in',
port: 443,
path: `/theia/api/v1/initiateTransaction?mid=${config.PaytmConfig.stag.mid}&orderId=${paytmParams.body.orderId}`,
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": post_data.length,
},
};
const responsePaytm = await doRequest(options, post_data);
const https = require("https");
/**
* Do a request with options provided.
*
* #param {Object} options
* #param {Object} data
* #return {Promise} a promise of request
*/
function doRequest(options, data) {
return new Promise((resolve, reject) => {
const req = https.request(options, (res) => {
res.setEncoding("utf8");
let responseBody = "";
res.on("data", (chunk) => {
responseBody += chunk;
});
res.on("end", () => {
resolve(JSON.parse(responseBody));
});
});
req.on("error", (err) => {
reject(err);
});
req.write(data);
req.end();
});
}
Im trying to get progress status values while uploading files to google Drive using nodeJs.
controller.js
exports.post = (req, res) => {
//file content is stored in req as a stream
// 1qP5tGUFibPNaOxPpMbCQNbVzrDdAgBD is the folder ID (in google drive)
googleDrive.makeFile("file.txt","1qP5tGUFibPNaOxPpMbCQNbVzrDdAgBD",req);
};
googleDrive.js
...
makeFile: function (fileName, root,req) {
var fileMetadata = {
'name': fileName,
'mimeType': 'text/plain',
'parents': [root]
};
var media = {
mimeType: 'text/plain',
body: req
};
var r = drive.files.create({
auth: jwToken,
resource: fileMetadata,
media: media,
fields: 'id'
}, function (err, file) {
if (err) {
// Handle error
console.error(err);
} else {
// r => undefined
console.log("Uploaded: " + r);
}
});
},
...
i followed this link but got always an undefined value
How about this modification?
Modification point:
It used onUploadProgress.
Modified script:
makeFile: function (fileName, root,req) {
var fileMetadata = {
'name': fileName,
'mimeType': 'text/plain',
'parents': [root]
};
var media = {
mimeType: 'text/plain',
body: req
};
var r = drive.files.create({
auth: jwToken,
resource: fileMetadata,
media: media,
fields: 'id'
}, {
onUploadProgress: function(e) {
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write(e.bytesRead.toString());
},
}, function (err, file) {
if (err) {
// Handle error
console.error(err);
} else {
console.log("Uploaded: " + file.data.id);
}
});
},
Note:
If you want to show the progression as "%", please use the file size.
It was confirmed that this script worked at googleapis#33.0.0.
References:
axios
test of google/google-api-nodejs-client
In my environment, I'm using the script like above. But if this didn't work in your environment and if I misunderstand your question, I'm sorry.
I'm using "aws-sdk": "^2.117.0", my code looks like this:
var AWS = require('aws-sdk');
exports.sendAWSMail = function(message, destination){
const ses = new AWS.SES();
// http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#sendEmail-property
const sendEmail = ses.sendEmail;
var data = {
Destination: {
ToAddresses: [
"blahblah#gmail.com"
]
},
Message: {
Body: {
Html: {
Charset: "UTF-8",
Data: "This message body contains HTML formatting. It can, for example, contain links like this one: <a class=\"ulink\" href=\"http://docs.aws.amazon.com/ses/latest/DeveloperGuide\" target=\"_blank\">Amazon SES Developer Guide</a>."
},
Text: {
Charset: "UTF-8",
Data: "This is the message body in text format."
}
},
Subject: {
Charset: "UTF-8",
Data: "Test email"
}
},
Source: "no-reply#frutacor.com.br",
}
sendEmail(data)
}
But I get this error:
TypeError: this.makeRequest is not a function
at svc.(anonymous function) (/Users/iagowp/Desktop/trampos/frutacor/node_modules/aws-sdk/lib/service.js:499:23)
I didn't find any Node examples at their website, but from what I've seen elsewhere (like here), it looks correct. What am I doing wrong?
The main problem is in line #5 and it's always a good idea to add the callback function for logging errors and successful requests.
var AWS = require('aws-sdk');
exports.sendAWSMail = function(message, destination){
const ses = new AWS.SES();
var data = {
Destination: {
ToAddresses: [
"blahblah#gmail.com"
]
},
Message: {
Body: {
Html: {
Charset: "UTF-8",
Data: "This message body contains HTML formatting. It can, for example, contain links like this one: <a class=\"ulink\" href=\"http://docs.aws.amazon.com/ses/latest/DeveloperGuide\" target=\"_blank\">Amazon SES Developer Guide</a>."
},
Text: {
Charset: "UTF-8",
Data: "This is the message body in text format."
}
},
Subject: {
Charset: "UTF-8",
Data: "Test email"
}
},
Source: "no-reply#frutacor.com.br",
}
ses.sendEmail(data, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
}
I have code that send email with nodemailer in nodejs but I want to attach file to an email but I can't find way to do that I search on net but I could't find something useful.Is there any way that I can attach files to with that or any resource that can help me to attach file with nodemailer?
var nodemailer = require('nodemailer');
var events = require('events');
var check =1;
var events = new events.EventEmitter();
var smtpTransport = nodemailer.createTransport("SMTP",{
service: "gmail",
auth: {
user: "example#gmail.com",
pass: "pass"
}
});
function inputmail(){
///////Email
const from = 'example<example#gmail.com>';
const to = 'example#yahoo.com';
const subject = 'example';
const text = 'example email';
const html = '<b>example email</b>';
var mailOption = {
from: from,
to: to,
subject: subject,
text: text,
html: html
}
return mailOption;
}
function send(){
smtpTransport.sendMail(inputmail(),function(err,success){
if(err){
events.emit('error', err);
}
if(success){
events.emit('success', success);
}
});
}
///////////////////////////////////
send();
events.on("error", function(err){
console.log("Mail not send");
if(check<10)
send();
check++;
});
events.on("success", function(success){
console.log("Mail send");
});
Include in the var mailOption the key attachments, as follow:
var mailOptions = {
...
attachments: [
{ // utf-8 string as an attachment
filename: 'text1.txt',
content: 'hello world!'
},
{ // binary buffer as an attachment
filename: 'text2.txt',
content: new Buffer('hello world!','utf-8')
},
{ // file on disk as an attachment
filename: 'text3.txt',
path: '/path/to/file.txt' // stream this file
},
{ // filename and content type is derived from path
path: '/path/to/file.txt'
},
{ // stream as an attachment
filename: 'text4.txt',
content: fs.createReadStream('file.txt')
},
{ // define custom content type for the attachment
filename: 'text.bin',
content: 'hello world!',
contentType: 'text/plain'
},
{ // use URL as an attachment
filename: 'license.txt',
path: 'https://raw.github.com/andris9/Nodemailer/master/LICENSE'
},
{ // encoded string as an attachment
filename: 'text1.txt',
content: 'aGVsbG8gd29ybGQh',
encoding: 'base64'
},
{ // data uri as an attachment
path: 'data:text/plain;base64,aGVsbG8gd29ybGQ='
}
]}
Choose the option that adjust to your needs.
Link:Nodemailer Repository GitHub
Good Luck!!
Your code is almost right, just need to add, "attachments" property for attaching the files in your mail,
YOUR mailOption:
var mailOption = {
from: from,
to: to,
subject: subject,
text: text,
html: html
}
Just add attachments like
var mailOption = {
from: from,
to: to,
subject: subject,
text: text,
html: html,
attachments: [{
filename: change with filename,
path: change with file path
}]
}
attachments also provide some other way to attach file for more information check nodemailer community's documentation HERE
If you are passing options object in mail composer constructor and attachment is on http server then it should look like:
const options = {
attachments = [
{ // use URL as an attachment
filename: 'xxx.jpg',
path: 'http:something.com/xxx.jpg'
}
]
}
var express = require('express');
var router = express(),
multer = require('multer'),
upload = multer(),
fs = require('fs'),
path = require('path');
nodemailer = require('nodemailer'),
directory = path.dirname("");
var parent = path.resolve(directory, '..');
// your path to store the files
var uploaddir = parent + (path.sep) + 'emailprj' + (path.sep) + 'public' + (path.sep) + 'images' + (path.sep);
/* GET home page. */
router.get('/', function(req, res) {
res.render('index.ejs', {
title: 'Express'
});
});
router.post('/sendemail', upload.any(), function(req, res) {
var file = req.files;
console.log(file[0].originalname)
fs.writeFile(uploaddir + file[0].originalname, file[0].buffer, function(err) {
//console.log("filewrited")
//console.log(err)
})
var filepath = path.join(uploaddir, file[0].originalname);
console.log(filepath)
//return false;
nodemailer.mail({
from: "yourgmail.com",
to: req.body.emailId, // list of receivers
subject: req.body.subject + " ✔", // Subject line
html: "<b>" + req.body.description + "</b>", // html body
attachments: [{
filename: file[0].originalname,
streamSource: fs.createReadStream(filepath)
}]
});
res.send("Email has been sent successfully");
})
module.exports = router;
attachments: [
{
filename: "inovices_1.pdf", // the file name
path: "https://*************************/invoice/10_9_RMKUns.pdf",// link your file
contentType: "application/pdf", //type of file
},
{
filename: "inovices_2.pdf",
path: "https://**************************/invoice/10_9_RMKUns.pdf",
contentType: "application/pdf",
},
];
var nodemailer = require("nodemailer");
var all_transporter = nodemailer.createTransport({
host: process.env.MAIL_SERVICE,
port: 587,
auth: {
user: process.env.MAIL_USER,
pass: process.env.MAIL_PASS,
},
maxConnections: 3,
pool: true,
});
exports.send_email = function (email, subject, html, extra_cc = [], attachments = []) {
return new Promise(async (resolve, reject) => {
var mailOptions = {
from: process.env.MAIL_FROM_ADDRESS,
to: email,
subject: subject,
html: html,
cc: [],
};
mailOptions["cc"] = mailOptions["cc"].concat(extra_cc);
if (attachments.length > 0) mailOptions["attachments"] = attachments;
all_transporter.sendMail(mailOptions, function (error, info) {
// console.log(error);
// console.log(info);
if (error) {
resolve({ failed: true, err: error });
} else {
resolve({ failed: false, data: info.response });
}
});
});
};
The alternative solution is to host your images online using a CDN and link to the online image source in your HTML, eg. <img src="list_image_url_here">.
(I had problems with nodemailer's image embedding using nodemailer version 2.6.0, which is why I figured out this workaround.)
An added benefit of this solution is that you're sending no attachments to nodemailer, so the sending process is more streamlined.
var mailer = require('nodemailer');
mailer.SMTP = {
host: 'host.com',
port:587,
use_authentication: true,
user: 'you#example.com',
pass: 'xxxxxx'
};
Then read a file and send an email :
fs.readFile("./attachment.txt", function (err, data) {
mailer.send_mail({
sender: 'sender#sender.com',
to: 'dest#dest.com',
subject: 'Attachment!',
body: 'mail content...',
attachments: [{'filename': 'attachment.txt', 'content': data}]
}), function(err, success) {
if (err) {
// Handle error
}
}
});
Just look at here. Nodemailer > Message configuration > Attachments
The code snippet is below (pdfkit gets the stream):
// in async func
pdf.end();
const stream = pdf;
const attachments = [{ filename: 'fromFile.pdf', path: './output.pdf',
contentType: 'application/pdf' }, { filename: 'fromStream.pdf', content: stream, contentType: 'application/pdf' }];
await sendMail('"Sender" <sender#test.com>', 'reciver#test.com', 'Test Send Files', '<h1>Hello</h1>', attachments);
Stream uses content not streamSource This bothered me before, share with everyone :)
Reference = https://nodemailer.com/message/attachments/
var mailOption = {
from: from,
to: to,
subject: subject,
text: text,
html: html,
attachments: [
{
filename: filename,
path: filePath
},
]
}