Why is nodemailer sending duplicate emails? Why is nodemailer sending duplicate emails? express express

Why is nodemailer sending duplicate emails?


Your email is being sent on any request sent to your server so if you access it via a browser, the browser will send two requests, one for the path requested and one for the favicon.ico and you're also sending an email when /favicon.ico is requested.

This can happen because you're route handler is configured as:

app.get('*', ...);

That means you're attempting to send an email for every single incoming http request regardless of path.

So, if you go to your host with a browser at http://yourdomain/, it will first request / and then the browser will request /favicon.ico, causing you to then send a second email.

My suggestion is to change from this:

app.get('*', ...);

to this:

app.get('/', ...);

or, even more specific such as:

app.get('/sendemail', ...);

So, you are only sending the email on one specific path request and it will not send the email no other requests such as the favicon. You probably want to add a generic express 404 handler for any other routes.


Note: In a REST design, you would probably send an email with a POST request, not a GET request. A GET would retrieve a resource in a read-only kind of way that does not change any state so it wouldn't have a side effect of sending an email. Note: this isn't related to your problem at all, just a comment about a typical REST design.


After some time I have finally figured out the reason for this behavior. The issue is partially related to what jfriend00 had posted. I ended up making a separate route handler for the emails themselves so that it didn't interfere with the main route handler. The problem is that every request will still go through that route since it is looking for any request indicated by the * and if a person is on the http route making the request instead of https, then it creates a second request or in my case a second email.

You can see that happening in this line here:

if (proto) {        if (proto === 'http') response.redirect(301, "https://ourdomain.com".concat(request.url));    }

The actual fix for this was to create a separate route handler for the emails themselves and then configure my nginx server to reroute to https if a person was going to the http route of the application instead. After this, we have not experienced anymore duplicate emails.

Another way of doing it would be to remove the ```*```` route handler completely and setup the other routes separately. Hopefully this will help somebody in the near future.