I'm trying to send emails inside next.js api functions. I have the following code:
import nodemailer, { SentMessageInfo } from "nodemailer";
export default async ({ to, subject, text, html }: Props) => {
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
host: "email-smtp.us-east-1.amazonaws.com",
port: 465,
secure: true,
auth: {
user: process.env.AWS_SES_USERNAME,
pass: process.env.AWS_SES_PASSWORD,
},
});
console.log("Sending email to", to);
// send mail with defined transport object
let info: SentMessageInfo = await transporter.sendMail({
from: '"Me" <help#myemail.io>', // sender address
to,
subject,
text,
html: html,
});
console.log("Message sent: %s", info.messageId);
return info.messageId;
};
Sometimes this can take minutes to send but I have no idea why. How would one go about debugging this? Is it possible that my Amazon SES SMTP server is throttling me? I'm not even sending emails that frequently.
Related
I want to send a email from my custom domain address office#mycompany.com but this mail address (that was set up using Shopify) is only forwarding the emails that come in. Is it possible to send a email from this mail address (like many applications do).
I googled around and found sth. that I have to add a DNS and a MX Record to my domain. Is that right and how can I send emails through those configurations?
let transporter = nodemailer.createTransport({
host: 'mycompany.com',
port: 465,
secure: true,
auth: {
user: 'office#mycompany.com',
pass: ?
}
});
let mailOptions = {
from: '"Mycompany" <office#mycompany.com>', // sender address
to: recipient, // list of receivers
subject: "Test", // Subject line
html: fileToSend // html body
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
} else {
console.log('Message %s sent: %s', info.messageId, info.response);
}
});
Warmly regards
I am trying to set up an emailing system for users on my website. I am using nextJS and have an api endpoint to send emails. To send the emails I am using emailJS and sending the email to myself with a custom body. Here is the code for my email.js file:
import { SMTPClient } from 'emailjs';
export default function handler(req, res) {
const {body, subject}=req.body;
// console.log(process.env)
const client = new SMTPClient({
user: "test#gmail.com",
password: "passward",
host: 'smtp.gmail.com',
ssl:true
});
try{
client.send(
{
text: `${body}`,
from: "test#gmail.com",
to: "test#gmail.com",
subject: `${subject}`,
}
)
}
catch (e) {
res.status(400).end(JSON.stringify({ message: e.message }))
return;
}
res.status(200).end(JSON.stringify({ message:'Mail sending' }))
}
The code works when I use it on localhost but it does not work when I deploy to amplify. When I try to make a post request on amplify I get status 200 with the {"message":"Mail sending"}. However, the gmail account never gets the email. I do not get an error message. I do not have 2 step verification on and have allowed less secure apps, but still no emails are being sent. I would really appreciate any help.
The emailjs library utilizes a queuing system for sending emails. This means that the send method adds the email to the queue and sends it at a later time. This can cause issues when using the send method within a lambda function, as the function may close before the email has been sent. To ensure that the email is sent before the lambda function closes, you can use the sendAsync method instead. This method returns a promise that will be resolved when the email has been successfully sent.
To send an email using the sendAsync method, you can do the following:
await client.sendAsync(
{
text: `${body}`,
from: "test#gmail.com",
to: "test#gmail.com",
subject: `${subject}`,
}
)
I'm build an API with feathersjs and I need to send an email with an attachment.
The email seems to be send but I receive nothing.
In my mail.service.js
const nodemailer = require('nodemailer');
const transporter = nodemailer.createTransport({
host: 'smtp.office365.com',
port: 587,
secure: false, // secure:true for port 465, secure:false for port 587
auth: {
user: 'gil.felot#myaccount.com',
pass: 'MyPassWord'
}
});
// Check the connection to the service.
transporter.verify(function(error, success) {
if (error) {
console.log(error);
} else {
console.log('Server is ready to take our messages');
}
});
Then in my hook
hook => {
const file = hook.params.file;
const email = {
from: 'gil.felot#myaccount.com', // sender address
to: 'mygmailaccount#gmail.com', // list of receivers
subject: 'Test Nodemailer', // Subject line
// text: req.body.text, // plaintext body
html: '<b>Hello world 🐴</b>', // html body
attachments: [
{
filename: file.originalname,
contents: new Buffer(file.buffer, 'base64'),
encoding: 'base64'
}
]
};
return hook.app.service('mail').create(email)
.then(function (result) {
console.log('Sent email', result);
}).catch(err => {
console.log(err);
});
}
then I got
Server is ready to take our messages
Sent email
Object {from: "gil.felot#myaccount.com", to: "mygmailaccount#gmail.com", subject: "Test Nodemailer", html: "Hello world 🐴"}
I have no idea how to check where the problem come from.
I was missing the from part while creating a mail while I was able to send mail via google smtp but my own smtp was failing with the above configuration
Was working with google
var mailOptions = { to: email, subject: 'Forgot Password', html: mailData };
Working with my smtp as well:
var mailOptions = { from: 'serverName.com', to: email, subject: 'Forgot Password', html: mailData };
Consider adding name while defining nodemailer configuration as well
let transporter = nodemailer.createTransport({
name: 'example.com' // <= Add this
host: 'smtp.example.email',
port: 587,
Ok I figure it out !
I needed to add the transporter.sendMail() inside the mail.class.js to trigger this action when I call hook.app.service('mail').create(email)
Working and the attachement file that is 0 byte in the mail but the good size inside my variable.
For me this was what I realized; if the html does not have the html tags, then the email is not sent. i.e.
This template will work
<html>
<body>
Hello and welcome
</body>
</html>
This template will not work:
<body>
Hello and welcome
</body>
This is especially when sending to office365, refer to this other question here:
Nodemailer doesn't send emails to outlook.office365 accounts
I'm a beginner in vuejs2 and I'm trying to make a simple contact form (using webpack and vuejs2).
I've created my form with the send button pointing to the following method:
<button #click.prevent="sendemail" class="btn btn-xl">Send</button>
And the method:
methods: {
sendemail () {
var mailgun = require('mailgun.js')
var mg = mailgun.client({username: 'MYUSERNAME', key: MYAPIKEY})
mg.messages.create('MYDOMAIN', {
from: 'FROMEMAIL',
to: ['TOEMAIL'],
subject: 'SUBJECT',
text: 'TEXT'
})
.then(msg => console.log(msg)) // logs response data
.catch(err => console.log(err)) // logs any error
}
}
When I press send button I get the following error:
XMLHttpRequest cannot load https://api.mailgun.net/v3/MYDOMAIN/messages. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
Any suggestions or any other way to do it?
The mailgun-js docs specify a way on how can we do this:
var api_key = 'key-XXXXXXXXXXXXXXXXXXXXXXX';
var domain = 'www.mydomain.com';
var mailgun = require('mailgun-js')({apiKey: api_key, domain: domain});
var data = {
from: 'Excited User <me#samples.mailgun.org>',
to: 'serobnic#mail.ru',
subject: 'Hello',
text: 'Testing some Mailgun awesomness!'
};
mailgun.messages().send(data, function (error, body) {
console.log(body);
});
Also a word of caution, I would not put the api_key in my frontend as anyone can use it and send emails. Instead, try opting for a backend which will send emails for you.
I'm trying to send the email gmail smtp but I'm getting the error:
My email and password is correct I'm using the nodemailer for sending the mail;
var nodemailer = require('nodemailer');
// create reusable transporter object using SMTP transport
var transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
admin: 'myuseremail.com',
pass: 'password'
}
});
var mailOptions = {
from: 'sender address', // sender address
to: to, // list of receivers
subject: 'Password Reset', // Subject line
html: 'Your one time password is : <b>' + temporaryPassword + ' </b>' // html body
};
transporter.sendMail(mailOptions, function (error, info) {
console.log(error,info);
}
in log i'm getting the error:
{
[Error: Invalid login]
code: 'EAUTH',
response: '535-5.7.8 Username and Password not accepted. Learn more at\n535 5.7.8 https://support.google.com/mail/answer/14257 k5sm20957041pdo.48 - gsmtp',
responseCode: 535
}
I try some link but that doesn't work:
https://laracasts.com/discuss/channels/general-discussion/help-email-doesnt-get-sent-with-gmail-smtp
var transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: 'user#gmail.com',
pass: 'password'
}
});
Try the above, and do the following which worked for me.
Login to https://www.google.com/settings/security/lesssecureapps and TURN ON Access for less secure apps.
I hope it will work for you too.
Thank you.
First of all, you have to enable the settings to allow less secure apps for the gmail account that you are using. Here is the link : https://myaccount.google.com/lesssecureapps
Secondly, Allow access for "Display Unlock captcha option" (Allow access to your Google account). Here is the link : https://accounts.google.com/DisplayUnlockCaptcha
https://myaccount.google.com/lesssecureapps
Click on this link, On your Less secure app access. so after that gmail will send email to your device , confirm that it is you. You are done happy coding
Google don't allow you to send direct e-mail to other's. First of all you have to create a app password .For that thing please follow below steps to get it done
Go to your manage account section.
Then click on the security link in left side.
In the signing in to the google click on app password and it will ask you to sign in again after sign in
It will ask "select app", for mail purpose "select mail" and after that select device from which you want to send mail.
After all these steps, it will generate password for that thing and insert that like this
var smtpTransport = nodemailer.createTransport({
service: "Gmail",
auth: {
user: "example#example.com",
pass: "password"
}
That's it.
In case you're using OAuth2 and you're facing the issue above, configuring my transporter as shown below resolved my issue.
const transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
type: 'OAuth2',
user: process.env.MAIL_USER,
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
refreshToken: process.env.GOOGLE_CLIENT_REFRESH_TOKEN
}
});
var transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: 'user#gmail.com',
pass: 'password'
}
});
Try this.
For me
secure:true was giving ssl errors.
I changed
secure:false as below and worked for me.
let transporter = nodeMailer.createTransport({
host: 'smtp.gmail.com',
port: 587,
secure: false, //<<here
auth: {
user: 'example#gmail.com',
pass:'your gmail pass'
}
});
let transporter = nodeMailer.createTransport({
host: 'smtp.gmail.com',
port: 587,
secure: true,
auth: {
user: 'example#gmail.com',
pass:'your gmail pass'
}
});