Within an HTML file I would like to use the library nodemailer
to send emails. To do this with nodejs I simply put var nodemailer = require('nodemailer')
at the top of the script component of my HTML file however require
is not a valid function in HTML. When I try to do this I get the error ReferenceError: require is not defined
. I would like to know how to use this library from HTML, or if this is not possible, what a good alternative is so that I can send emails from an HTML file.

- 1,116
- 5
- 27
- 59
-
You cannot send emails from inside a browser environment, no matter how many nodejs libraries you include. – Thomas Sep 23 '20 at 09:47
-
you can't use require on browser DOM. However, some libraries provide browser level packages also which can be included in browser with the tag – kavigun Sep 23 '20 at 09:50
3 Answers
You can't use Nodemailer from an HTML file.
Browsers can't connect to the SMTP servers required to send mail.

- 152,115
- 15
- 115
- 172
require
and nodemailer
are for "nodejs" (server side javascript), so you can't use nodejs functionality in the browser.

- 1,021
- 12
- 12
Some libraries designed for use with Node.js can be persuaded to work in a browser, although you’d usually need a tool like Webpack to replace the node module system. This can only work if the library doesn’t depend on any APIs provided by Node.js but not browsers.
Browsers provide no API for sending email (beyond the exceptionally limited mailto:
URI scheme which will create a new email for a user to send in their default email client (if they have a default email client)). Nor do they provide any API for direct socket creation which could be used to build such an API.
The library you have found will not run in the browser.
If you want to send an email you need to do it from a server. You can make an HTTP request (either by submitting a form of using XMLHttpRequest or fetch) to get the data from the browser to the server.
If you write your server using Node.js (likely with the Express.js framework) then you can use the library you found.

- 914,110
- 126
- 1,211
- 1,335