how to send email through amazon ses - amazon-ses

I'm using nodemailer and nodemailer-ses-transport.
everytime I run my test code for send mail, I get an error message like this.
but I specified 'From' field in test I don't know why it won't recognize the field.
{ [InvalidParameterValue: Missing required header 'From'.]
message: 'Missing required header \'From\'.',
code: 'InvalidParameterValue',
time: Fri Apr 10 2015 01:34:36 GMT+0000 (UTC),
statusCode: 400,
retryable: false,
retryDelay: 30 }
the test code is here.
please let me know wrong code.
var nodemailer = require('nodemailer');
var ses = require('nodemailer-ses-transport');
var sendAuthCode = function(gmail, message, callback) {
var transporter = nodemailer.createTransport(ses({
accessKeyId : MY_ACCESS_KEY_ID,
secretAccessKey : MY_SECRET_ACEESS_KEY,
region : "us-west-2",
rateLimit : 1
}));
transporter.sendMail({
from: 'mail bot',
to: gmail,
subject: 'TEST',
text: message
}, function(err, resStatus) {
if (err) {
callback(err);
} else {
callback('success');
}
});
}
sendAuthCode("some#gmail.com", "hello", function (result) {
console.log(result);
});
UPDATED
I solved the problem!!
problem was that amazon ses can only send mail between verified email address.
if you want send an email to user who not verified,
you should request to increase ses limit on ses dashboard.
anyway thanks for reply

You cannot use "mail bot" as sender. Use legitimate email.

Related

How can I send multiple emails (around 100) with different email body using amazon ses in NodeJS?

I am trying to send emails to multiple users with email body like
dear {{username}},
/.
....
Your email is {{email}}
...
.
/
how can I do those any ideas, I saw the custom templates for amazon ses but I have 100+ users so how will it be done ?
You can use SES bulk templated emails.
Create a template for your emails.
const AWS = require("aws-sdk");
const ses = new AWS.SES({
accessKeyId: <<YOUR_ACCESS_KEY>>,
secretAccessKey: <<YOUR_ACCESS_KEY>>,
region: <<YOUR_ACCESS_KEY>>
});
const params = {
Template: {
TemplateName: "MyTemplate",
SubjectPart: "Test mail for {{username}}!",
HtmlPart: "<p>Dear {{username}}</p>, <p>Your email is {{email}}.</p>"
}
}
ses.createTemplate(params, (err, data) => {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
Once it is done you would see the MyTemplate under Email templates of SES console. We no longer needed template creating part of the code.
Now we can send the email using the following.
const users = [{username:"max", email: "max#m.com"},{username: "mosh", email:"mosh#h.com"}] // sample array of users
let destinations = []
for (const user of users) {
destinations.push({
Destination: {
ToAddresses: [user.email]
},
ReplacementTemplateData: JSON.stringify({
username: user.username, // This will provide the value for username in template
email: user.email // This will provide the value for email in template
})
});
}
const params = {
Source: "sender#xyz.com", // sender email
Template: "MyTemplate", // Template name we have created
Destinations: destinations,
DefaultTemplateData: JSON.stringify({
username: '', // default value for username
email: '' // default value for email
})
}
ses.sendBulkTemplatedEmail(params, (err, data) => {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
Make sure you have given the ses:createTemplate and ses:sendBulkTemplatedEmail permissions for the IAM user before running this.
For more info see here.

Duplicate blank email nodemailer

I'm sending emails using my express app using Nodemailer. When sending the email I get two emails sent, one with everything correct and the other as a blank mail with the to field not filled out. Any tips on how to fix?
From the console log, it shows that it is only called once...
console.log('called')
let transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true, // true for 465, false for other ports
auth: {
user: process.env.MAIL,
pass: process.env.MAIL_PASSWORD,
},
})
let message = ''
switch (format) {
case 'resetPassword':
message = `There was recently a request to change the password for your account. If you requested this password change, click the link below to reset your password:
<br><br>${passwordKey}<br><br>
If you did not make this request, you can ignore this message and your password will remain the same.`
break
default:
break
}
let mail = await transporter.sendMail({
from: `<${process.env.MAIL}>`,
to: email,
bcc: process.env.MAIL,
subject: subject,
html: message,
})
transporter.sendMail(mail).then((e) => {
console.log(e)
})
}```

Cant send a message using Gmail API in browser

I am trying to send email using Gmail API in my browser app. My function looks like:
function sendMessage(recepient, message, done) {
var base64EncodedEmail = '';
var request = gmail.users.messages.send({
to: recepient,
userId: 'me',
resource: {
raw: base64EncodedEmail
}
});
request.execute(done);
}
I am getting the following:
'raw' RFC822 payload message string or uploading message via /upload/* URL required
What am I doing wrong here?
Figured out ... thanks to Google REST API - message in an RFC 2822 formatted and base64url encoded string. The new function is
function sendMessage(recepient, subject, message, done) {
var base64EncodedEmail = btoa(`From: me\r\nTo: ${recepient}\r\nSubject: ${subject}\r\n\r\n${message}`)
.replace(/[\/\+]/g, '_')
.replace(/=+$/, '');
var request = gmail.users.messages.send({
userId: 'me',
resource: { raw: base64EncodedEmail }
});
request.execute(done);
}

Send email using Nodemailer with GoDaddy hosted email

I am trying to send an email using nodemailer and a custom email address configured through GoDaddy. Here is a screen shot of the "custom configurations" page in c-panel:
and my code:
const nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'Godaddy',
secureConnection: false,
auth: {
user: 'info#mywebsite.com',
pass: 'mypassword'
}
});
var mailOptions = {
from: 'info#mywebsite.com',
to: 'otheremail#gmail.com',
subject: 'Sending Email using Node.js',
text: 'That was easy!',
html: '<h1>Welcome</h1><p>That was easy!</p>'
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
and my error log:
{ Error: connect EHOSTUNREACH 173.201.192.101:25
at Object.exports._errnoException (util.js:1012:11)
at exports._exceptionWithHostPort (util.js:1035:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1080:14)
code: 'ECONNECTION',
errno: 'EHOSTUNREACH',
syscall: 'connect',
address: '173.201.192.101',
port: 25,
command: 'CONN' }
I've tried changing the port number, making it secure vs non-ssl, using my website address as the host, and pretty much everything else I can think of. I have successfully sent an email from the godaddy email using one of the webmail clients. Has anyone else ever encountered this or have recommendations on things to try?
I am trying to send emails using nodemailer from Google Cloud Function using GoDaddy SMTP settings. I do not have Office365 enabled on my GoDaddy hosting. None of the above options worked for me today (12 November 2019). TLS need to be enabled.
I had to use the following configuration:
const mailTransport = nodemailer.createTransport({
host: "smtpout.secureserver.net",
secure: true,
secureConnection: false, // TLS requires secureConnection to be false
tls: {
ciphers:'SSLv3'
},
requireTLS:true,
port: 465,
debug: true,
auth: {
user: "put your godaddy hosted email here",
pass: "put your email password here"
}
});
Then, I could send a test email as follows:
const mailOptions = {
from: `put your godaddy hosted email here`,
to: `bharat.biswal#gmail.com`,
subject: `This is a Test Subject`,
text: `Hi Bharat
Happy Halloween!
If you need any help, please contact us.
Thank You. And Welcome!
Support Team
`,
};
mailTransport.sendMail(mailOptions).then(() => {
console.log('Email sent successfully');
}).catch((err) => {
console.log('Failed to send email');
console.error(err);
});
you should make some changes in your transporter:
var smtpTrans = nodeMailer.createTransport({
service: 'Godaddy',
host: "smtpout.secureserver.net",
secureConnection: true,
port: 465,
auth: {
user: "username",
pass: "password"
}
});
I realize this is an old post, but just wanted to add to this since the GoDaddy SMTP server has changed, just in case someone else comes across this and has the same problem I had. The answer by #tirmey did not work for me, but this did.
let nodemailer = require('nodemailer');
let mailerConfig = {
host: "smtp.office365.com",
secureConnection: true,
port: 587,
auth: {
user: "username#email.com",
pass: "password"
}
};
let transporter = nodemailer.createTransport(mailerConfig);
let mailOptions = {
from: mailerConfig.auth.user,
to: 'SomePerson#email.com',
subject: 'Some Subject',
html: `<body>` +
`<p>Hey Dude</p>` +
`</body>`
};
transporter.sendMail(mailOptions, function (error) {
if (error) {
console.log('error:', error);
} else {
console.log('good');
}
});
Solutions proposed above seem no longer valid, none of them worked for me. Following solution works for me:
const nodemailer = require('nodemailer');
const os = require('os');
let mailerConfig = {
host: os.hostname(),
port: 25,
};
let transporter = nodemailer.createTransport(mailerConfig);
transporter.sendMail({
from: '<from>',
to: '<to>',
subject: '<subject>',
text: '<text>'
}, (err, info) => {
console.log(info);
console.log(err);
});
I could solve the problem by using this code and some points that I brought them after codes:
const smtpTransport = nodemailer.createTransport({
host: "smtp.office365.com",
secure: false,
port: 587,
auth : {
user : 'info#my-domain.com',
pass : 'Password'
}
});
const mailOptions = {
to: 'target-mail#',
subject: 'Test 01',
html: 'Body',
from : 'info#resoluship.com'
};
await smtpTransport.sendMail(mailOptions);
Don't forget to use 'from' attribute in mailOptions
Don't use ',' in your 'from' attribute
For me, the solution for production shared hosting server was completely different than for testing.
It seems no authentication or credentials are required for it to work.
I created this code from this document describing how to use an SMTP relay server. You can use this with nodemailer. GoDaddy support told me I couldn't but I don't think they know about third party tools.
https://au.godaddy.com/help/send-form-mail-using-an-smtp-relay-server-953
async function main() {
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
host: 'localhost', //use localhost for linux cPanel hosting
port: 25,
secure: false,
// no need for authentication
tls: {
rejectUnauthorized: false
}
});
// send mail with defined transport object
let info = await transporter.sendMail({
to: "you#youremail.com", // list of receivers
subject: `New Message from ${name}`, // Subject line
text: `yourtext`, // plain text body
html: `your text in html`, // html body
headers: {
priority: 'high'
},
from: "you#youremail.com" // sender address
});
// send success page if successful
if (res.statusCode === 200) {
res.sendFile(path.join(__dirname, 'views/success.ejs'))
}
console.log("Message sent: %s", info.messageId, res.statusCode);
}
main().catch(console.error);
The most common problem with this error is the antivirus. So disable it for 10 minutes if you are testing it locally.

Nodemailer attachment not working in nodemailer 0.7.1

I am trying to send an attachment using nodemailer 0.7.1. The attachment is sent fine but when I try to open it, the shows ERROR OPENING FILE.
Here is my code:
var nodemailer = require("nodemailer");
var transport = nodemailer.createTransport("SMTP", {
host: "smtp.gmail.com", // hostname
secureConnection: true, // use SSL
port: <port>, // port for secure SMTP
auth: {
user: "example.example#gmail.com",
pass: "password"
}
});
console.log("SMTP Configured");
var mailOptions = {
from: 'example.sender#gmail.com', // sender address
to: 'example.receiver#gmail.com', // list of receivers
subject: 'Report for Test Result', // Subject line
text: 'Contains the test result for the test run in html file', // plaintext body
attachments: [
{
'filename': 'results.txt',
'filePath': './result/results.txt',
}
]
};
transport.sendMail(mailOptions, function (error, response) {
if (error) {
console.log(error);
} else {
console.log("Message sent: " + response.message);
}
});
Any suggestion on how to resolve this would be of great help.
Replace the filename and filePath lines with path: './result/results.txt' and try.
Try this code.First you have to create an app in Google Cloud Console and Enable Gmail API from library.Get the credentials of your app.For that click on Credentials and in the place of Authorized redirect URIskeep this link https://developers.google.com/oauthplayground and save it.Next in another tab open this link https://developers.google.com/oauthplayground/ click on settings symbol on right side.And make a tick on check box(i.e,Use your own OAuth credentials) after this You have to give your clientId and clientSecret.And at the sametime on left side there is a text box with placeholder like Input Your Own Scopes there keep this link https://mail.google.com/ and click on Authorize APIs then click on Exchange authorization code for tokens then you will get your refreshToken and accessToken keep these two in your code.Hope thsi helps for you..
const nodemailer=require('nodemailer');
const xoauth2=require('xoauth2');
var fs=require('fs');
var transporter=nodemailer.createTransport({
service:'gmail',
auth:{
type: 'OAuth2',
user:'Sender Mail',
clientId:'Your_clientId',//get from Google Cloud Console
clientSecret:'Your clientSecret',//get from Google Cloud Console
refreshToken:'Your refreshToken',//get from https://developers.google.com/oauthplayground
accessToken:'Tor accessToken'//get from https://developers.google.com/oauthplayground
},
});
fs.readFile("filePath",function(err,data){
var mailOptions={
from:' <Sender mail>',
to:'receiver mail',
subject:'Sample mail',
text:'Hello!!!!!!!!!!!!!',
attachments:[
{
'filename':'filename.extension',//metion the filename with extension
'content': data,
'contentType':'application/type'//type indicates file type like pdf,jpg,...
}]
}
transporter.sendMail(mailOptions,function(err,res){
if(err){
console.log('Error');
}
else{
console.log('Email Sent');
}
})
});