How to send mail using node js without nodemailer - node.js

I tried to send mail in node js using nodemailer.
Question is: is it possible to use another framework - without nodemailer using send mail. If so - can you provide some example code?

You can use sendgrid to send an email. It is more reliable in my opinion. You will need to create a sendgrid account to get the API key. Then you can do something like this:
const sgMail = require('#sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
to: 'test#example.com',
from: 'test#example.com',
subject: 'Sending with SendGrid is Fun',
text: 'and easy to do anywhere, even with Node.js',
html: '<strong>and easy to do anywhere, even with Node.js</strong>',
};
sgMail.send(msg);

Related

Having issues sending "base64" email "attachments" using "#sendgrid/mail" in "nodejs"

So, basically I want to send a base64 encoded .zip file as email attachment in #sendgrid/mail. The file is saved in MongoDB like this,
I am fetching the data and converting the "file.buffer" which is a binary data to base64 using .toString("base64") something like this,
console.log('Converting to base64')
plugin.file.buffer = plugin.file.buffer.toString('base64')
and it gets perfectly converted into base64 (I know it is working because I am also using that "plugin.file" in .ejs file as a download button something like this,
<a class="btn btn-success btn-sm" download="plugin.zip" href="data:application/zip;base64,<%- plugin %>" role="button">Download</a>
So, now I will be using that "plugin" to send a email to the user, so I am doing something like this just before rendering the ejs page,
if (req.session.email) await sendMail(req.session.email , "Thanks for purchasing" , "Here is your delivery!" , plugin)
res.render('success' , {payment , type: "Payment" , discord , plugin: plugin.file.buffer})
It basically checks if the email of the user is stored in "sessions" i.e. logged in, if yes it sends a email and then renders the success page!
So, the issue is in the email.js file sendMail() function. It is neither sending me the email nor the attachment.
Before showing the code inside that function(), my api keys etc are correct as I am also sending a mail whenever the user creates an account and in that case, everything is working fine and the mail is being sent. But whenever I include the attachment logic, neither the mail nor the attachment is being sent! So, here is my code:-
const { MAILER_API_KEY } = require('../config.json')
const mailer = require('#sendgrid/mail')
mailer.setApiKey(MAILER_API_KEY)
async function sendMail(email , subject , text , plugin) {
mailOptions = {
to: email,
from: 'zoomdev.code#gmail.com',
subject: subject,
text: text
}
// if this if statement is false i.e. plugin is undefined(whenever the user is signing up, he/she doesnt need attachment or stuff. The attachment email is being sent whenever the payment is completed and the file is being sent to the user) it works fine. But sending an attachment doesn't work. The email and attachment doesn't get sent!
if (plugin) mailOptions.attachments = [{
content: plugin.file.buffer,
filename: plugin.file.originalname,
type: 'application/zip', // Here, I have also tried using "application/x-zip-compressed", the type saved in the database and it is the same! :(
disposition: 'attachment'
}]
await mailer.send(mailOptions).then(res => {
console.log(JSON.stringify(res))
return true
}).catch(err => {
console.log(JSON.stringify(err))
return false
})
console.log('Mail sent to ' + email)
}
module.exports = { sendMail }
Whenever sending the attachment email, I am getting this in console,
Executing Payment
Converting to base64
Updating user
// ^ these are something else. Ignore them
// this is the JSON.stringify(... console.log in sendMail function last lines
[{"statusCode":202,"body":"","headers":{"server":"nginx","date":"Fri, 22 Oct 2021 06:57:18 GMT","content-length":"0","connection":"close","x-message-id":"QpxSudqkRGytDU7YFleVgA","access-control-allow-origin":"https://sendgrid.api-docs.io","access-control-allow-methods":"POST","access-control-allow-headers":"Authorization, Content-Type, On-behalf-of, x-sg-elas-acl","access-control-max-age":"600","x-no-cors-reason":"https://sendgrid.com/docs/Classroom/Basics/API/cors.html","strict-transport-security":"max-age=600; includeSubDomains"}},""]
Mail sent to <my email , I have edited this part for privacy, but it correctly logs the email>
Note:-
I am using express#^4.17.1
#sendgrid/mail#^7.4.7
I have checked spam folder and everything
Twilio SendGrid developer evangelist here.
Using a Gmail address as your from address is not a good way to get your emails delivered. Doing so means you are spoofing an email address, even if it is your email address.
When you are spoofing an email address like that, the email server is unable to prove that it has permission to send emails for that address. SPF and DKIM are methods you can use to prove that you control the domain the email is coming from, but when you use a Gmail address (or any other mailbox provider) then you will appear to be spoofing and receiving mailboxes may choose to discard your emails or land them in the spam inbox.
You may have managed to send and receive your account creation emails with this method, but mailbox providers will be a lot more restrictive when it comes to receiving emails with attached zip files. The whole thing appears suspicious and the mailbox will likely reject it, send it spam, or silently delete it.
The advice here is just don't send emails from a domain that you don't control. What you should do is get a domain that you want to send emails from, set up domain authentication for that domain and you will have a much better chance of landing your emails in your users' inboxes than by spoofing Gmail.

Accessing Proxy Server address from my nodejs?

i'm using nodemailer to send a confirmation email on my project,
like so:
var mailOptions = {
from: "alex#account",
to: req.body.email,
subject: "Account Verification Token",
html: `<p>Hello,<br/> Please verify your account by clicking the link <br/> <a href=http://${req.headers.host}/confirmation/${token}>Click here to verify</a></p>\n`
};
Im sending an href link which contains req.headers.host which is my node adress localhost:6000, but I wish it to be my react adress localhost:4000, since its going to change later, I wish to have a variable jst like req.headers.host which will contain my react client's adress, is it possible? or I need to set it manually?
If the app is not server-side rendered, you can pass the React client's address from the frontend and include it to your request object which you can then retrieve after it gets to the server.
I found the answer I can use the variable :
const addr = `req.headers.referer`

Email is not receiving in recipient's email box while using sendgrid in protractor

I am using protractor-cucumber framework.I am tryig to implement sendgrid method for email sending.For that i have used api from https://sendgrid.com/free/. I am using sendgrid/mail version 5.2.3 and used below code.
const sgMail = require('#sendgrid/mail');
var env=require('../support/sendgrid.js');
sgMail.setApiKey(env.SENDGRID_API_KEY);
console.log(env.SENDGRID_API_KEY);
const msg = {
to: 'xx#gmail.com',
from: 'xxx#gmail.com',
subject: 'Sending with SendGrid is Fun',
text: 'and easy to do anywhere, even with Node.js',
html: '<strong>and easy to do anywhere, even with Node.js</strong>',
};
sgMail.send(msg);
I am exporting the api from sendgrid.js(i am able to successfully launch the api to the code).When i ran the above code initially, the email not received, then i directly hardcoded the api in the code, then it worked.So i again try to export it from the sendgrid.js file.That time also it worked.But after running the code 2,3 times then again the email was not receiving in the recipient list.I am not understanding why this behave inconsistently.Also i am not able to console whether there is a success or failure.How can we catch/print the error here.Can anyone help me.Thanks in advance

Azure SendGrid connected to create-react-app for UI

So I have my app created using create-react-app in Azure, but need to add ability to send mail once a Form is submitted. I know this cannot be done in my react app, but being away from backend work for a bit, I was trying to search for a tutorial or something online that could guide me and setting up some sort of node.js with sendgrid so that this UI can now process sending emails with my forms. Can any of you recommend some direction, tutorials, etc... to assist with this as I am not seeing things on the Sendgrid website for this.
Thanks for the help.
Check the library sendgrid-nodejs repo, which includes detailed examples for Node.js:
const sgMail = require('#sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
to: 'test#example.com',
from: 'test#example.com',
subject: 'Sending with SendGrid is Fun',
text: 'and easy to do anywhere, even with Node.js',
html: '<strong>and easy to do anywhere, even with Node.js</strong>',
};
sgMail.send(msg);
For more complex use cases, please see USE_CASES.md.

View order schema does not appear using nodemailer but google app script

I have been trying to create an Google order Schema markup for our orders. However, the html template that I generate works when I run it using the google App Script Test
Code.gs file in Google App script
function testSchemas() {
var htmlBody = HtmlService.createHtmlOutputFromFile('template_html').getContent();
MailApp.sendEmail({
// to: Session.getActiveUser().getEmail(),
to:'MY GMAIL EMAIL',
subject: 'Test Actions in the Inbox - ' + new Date(),
htmlBody: htmlBody,
});
}
But when I use the same html template in nodemailer and run the nodemailer with the same gmail credentials using the Gmail Service, I do not find the
"View order" section.
I am aware that to: and from: addresses need to be same for testing schemas and I have the same to and from address.
My nodemailer config looks something like:
var smtpTransport = nodemailer.createTransport("SMTP",{
service: "Gmail",
auth: {
user: "GMAIL EMAIL",
pass: "PASSWORD"
}
});
smtpTransport.sendMail(mailOptions,function(err,response){console.log('Done');});
Google says your email must be SPF/DKIM enabled in order to stop phishing attacks but when I am using the Gmail service, it must not be the case.
Can anybody tell me what might be the reason for this and the workaround of how could I test it using node mailer before I raise a request to whitelist my IpP to Google.
Also, can we make Google orders to appear as Google card in Google Now.

Resources