Nodemailer attachment not working in nodemailer 0.7.1 - npm

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');
}
})
});

Related

Next js Strapi forgot password email

I'm trying to send reset password email to the email provided by user in the forgot password form but get an error "Internal Server Error" ..
this is the function called when submit the form:
`
const onFinish = async (values) => {
setIsLoading(true);
axios
.post(getStrapiURL('/api/auth/forgot-password'), {
email:values.email,
})
.then(response => {
message.success('Reset password email was sent successfully !',4);
})
.catch(error => {
console.log('An error occurred:', error);
message.error(error.response.data.error.message,3);
});
};
`
Next , based on strapi docs , I have installed sendgrid provider package and add its config in /config/plugins.js
`
module.exports = ({ env }) => ({
// ...
email: {
config: {
provider: 'sendgrid', // For community providers pass the full package name (e.g. provider: 'strapi-provider-email-mandrill')
providerOptions: {
apiKey: process.env.SENDGRID_API_KEY,
},
settings: {
defaultFrom: 'no-reply#strapi.io',
defaultReplyTo: 'no-reply#strapi.io',
},
},
},
'users-permissions': {
config: {
jwt: {
expiresIn: '7d',
},
},
},
});
`
Now when i submit the forgot password form with Recipient email ,the error says "Internal Server error"
also its failed when i test it from strapi dashboard .. any help please!
(Next js with Strapi project)
In Addition to those configurations, please make sure to define template for
Reset Password
Email address confirmation (if needed).
Provide same email with which you have registered to sandgrid.
Make sure sandgrid is installed in your app.
Use original email to send and receive emails. Google may not allow to send SMTP emails
from your account, which you may have to look for.
Thanks

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.

graphql server email verify example

I'm starting to work on an express API using graphql with apollo-server-express and graphql-tools. My register user process steps are:
User submit user name, email and password.
Server send an email to user by Mailgun with unique link generated by uuid.
User follow the link to verify the registration.
But I'm in struggle at how to bind the mutation in the resolver. See snippets:
server.js
const buildOptions = async (req, res, done) => {
const user = await authenticate(req, mongo.Users)
return {
schema,
context: {
dataloaders: buildDataloaders(mongo),
mongo,
user
},
}
done()
}
// JWT setting
app.use('/graphAPI',
jwt({
secret: JWT_SECRET,
credentialsRequired: false,
}),
graphqlExpress(buildOptions),
res => data => res.send(JSON.stringify(data))
)
Mutation on resolver
signupUser: async (root, data, {mongo: { Users }}) => {
// Check existed accounts,
// if account is not exist, assign new account
const existed = await Users.findOne({email: data.email})
if (!existed) {
// create a token for sending email
const registrationToken = {
token: uuid.v4(),
created_at: new Date(),
expireAfterSeconds: 3600000 * 6 // half day
}
const newUser = {
name: data.name,
email: data.email,
password: await bcrypt.hash(data.password, 10),
created_at: new Date(),
verification_token: registrationToken,
is_verified: false,
}
const response = await Users.insert(newUser)
// send and email to user
await verifyEmail(newUser)
return Object.assign({id: response.insertedIds[0]}, newUser)
}
// Throw error when account existed
const error = new Error('Email existed')
error.status = 409
throw error
},
// VERIFY USER
// Set verify to true (after user click on the link)
// Add user to mailist
verifiedUser: async (root, data, {mongo: { Users }}) => {
await Users.updateOne(
{ email: data.email },
{
set: {is_verified: true},
unset: {verification_token: {token: ''}}
}
)
},
route config
routes.get('/verify?:token', (req, res, next) => {
res.render('verified', {title: 'Success'})
})
the route config is where I stuck, because the object is passed to all resolvers via the context inside graphqlExpress
Any one help me out or suggest for me any articles related. Thanks so much.
You will need 3 graphql endpoints and 1 apollo http endpoint for proper workflow.
Optionally you can combine 3 graphql endpoints in one, but then it will be a one big function with a lot of different responsibilities.
1# graphql endpoint: changepass-request
expects email param
check if user with such email found in db:
generate code
save it in the local account node
send code to the user email with http link to confirm code:
http://yoursite.com/auth/verify?code=1234
return redirect_uri: http://yoursite.com/auth/confirm-code
for UI page with prompt for confirmation code
2# graphql endpoint: changepass-confirm
expects code param:
if user with such code found in db, return redirect_uri to UI page with prompt for new pass with confirmation code in params: http://yoursite.com/auth/change-pass?code=1234
3# graphql endpoint: changepass-complete
expects code and new pass:
hash new password
search in db for local account with such code
3a. if not found:
return error with redirect_uri to login page:
http://yoursite.com/auth?success=false&message="Confirmation code is not correct, try again."
3b. if found:
change password for new, return success status with redirect_uri to login page:
http://yoursite.com/auth?success=true&message="ok"
4# apollo HTTP endpoint: http://yoursite.com/auth/verify?code=1234
if no code provided:
redirect to UI registration page with error message in params:
http://yoursite.com/auth?success=false&message="Confirmation code is not correct, try again."
if code provided: search in db for local account with such code
1a. if user not found:
redirect to reg ui with err mess in params:
http://yoursite.com/auth?success=false&message="Confirmation code is not correct, try again."
1.b if user found:
redirect to ui page with new password prompt and attach new code to params
I didn't put any code above, so you can use this workflow in other auth scenarios.
It seems like rather than utilizing the verifiedUser endpoint, it would be simpler to just keep that logic inside the controller for the /verify route. Something like:
routes.get('/verify?:token', (req, res) => {
Users.updateOne(
{ verification_token: { token } },
{
$set: {is_verified: true},
$unset: {verification_token: {token: ''}}
},
(err, data) => {
const status = err ? 'Failure' : 'Success'
res.render('verified', {title: status})
}
)
})

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.

Sending Templated emails with node.js, node mailer and nodemailer-mailgun-transport

I have the following basic nodejs app:
var nodemailer = require('nodemailer');
var hbs = require('nodemailer-express-handlebars');
var options = {
viewEngine: {
extname: '.hbs',
layoutsDir: 'views/email/',
defaultLayout : 'template',
partialsDir : 'views/partials/'
},
viewPath: 'views/email/',
extName: '.hbs'
};
var mg = require('nodemailer-mailgun-transport');
var auth = {
auth: {
api_key: ' mailgun api key ',
domain: ' mailgun email domain '
}
}
var mailer = nodemailer.createTransport(mg(auth));
mailer.use('compile', hbs(options));
mailer.sendMail({
from: 'test#inventori.io',
to: 'test#test.com',
subject: 'Any Subject',
template: 'email.body',
context: {
variable1 : 'value1',
variable2 : 'value2'
}
}, function (error, response) {
// console.error(error);
if (error) {
throw error;
};
console.log('mail sent to ',response);
mailer.close();
});
views/email/template.hbs
{{>email/head}}
<body>
{{>email/header}}
{{{body}}}
{{>email/footer}}
</body>
</html>
views/email/email.body.hbs
<h4>Main Body Here</h4>
{{variable1}} <br/>
{{variable2}}
views/partials/email/header.hbs
<h4>Header Content</h4>
views/partials/email/footer.hbs
<h4>Footer Content</h4>
The handlebars template engine gives zero errors but the mailgun transport throws the following error:
Error: Sorry: template parameter is not supported yet. Check back soon!
at IncomingMessage.<anonymous> (~/test/node_modules/nodemailer-mailgun-transport/node_modules/mailgun-js/lib/request.js:228:15)
at IncomingMessage.emit (events.js:129:20)
at _stream_readable.js:908:16
at process._tickCallback (node.js:355:11)
This example uses the gmail node mailer transport:
http://excellencenodejsblog.com/express-nodemailer-sending-mails/
I would like to be able to send templated emails using mailgun.
Any help would be greatly appreciated.
Thank you.
Change your template parameter to html.
If you look at the source code here, the error correct- there is no such thing as a template parameter.
For me, templates weren't rendering properly because I was following an example using extName when the key was actually extname (all lowercase). Perhaps it was renamed overtime and the guide I was looking at is now somewhat out of date.
Full working example below as of 30 May 2020.
Directory Structure:
root/
src/
email-templates/
layouts/
blank.hbs
partials/
hello.hbs
services/
email.service.ts
email.service.ts (Haven't updated this to use proper types yet. Just a poc.)
export async function sendTestEmail() {
try {
// Generate test SMTP service account from ethereal.email
// Only needed if you don't have a real mail account for testing
const testAccount = await nodemailer.createTestAccount()
// create reusable transporter object using the default SMTP transport
const transporter = nodemailer.createTransport({
host: 'smtp.ethereal.email',
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: testAccount.user, // generated ethereal user
pass: testAccount.pass, // generated ethereal password
},
})
transporter.use('compile', hbs({
viewEngine: {
extname: '.hbs', // handlebars extension
partialsDir: 'src/email-templates',
layoutsDir: 'src/email-templates/layouts',
defaultLayout: 'blank',
},
viewPath: 'src/email-templates',
extName: '.hbs'
}))
// send mail with defined transport object
const mailOptions = {
from: 'test#gmail.com', // sender address
to: 'test#gmail.com', // list of receivers
subject: 'Hello ✔', // Subject line
text: 'Hello world?', // plain text body
template: 'hello',
context: {
firstName: 'Clem'
}
}
const info = await transporter.sendMail(mailOptions)
console.log('Message sent: %s', info.messageId)
// Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321#example.com>
// Preview only available when sending through an Ethereal account
console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info))
// Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
} catch (error) {
console.log(error)
}
}