Canvas 2D Web Apps/E-mails
This section is a stub. You can help Wikibooks by expanding it. |
There are many reasons to send e-mails from a web app, e.g., to receive user feedback or usage data of the web app. Unfortunately, JavaScript does not directly support sending e-mails.
One solution is to use a PHP script (on a web server that supports PHP) and let that PHP script send the e-mail since PHP does support sending e-mails. In this case, all the web app has to do is to send the data to the PHP script.
Here is an example for a simple PHP script that sends an e-mail to a hard-coded e-mail address with a hard-coded subject line. The script puts the raw data (in plain text format) that has been "post"ed to it into the body of the e-mail:
<?php
if (isset($HTTP_RAW_POST_DATA)) {
mail("my.email@example.com",
"my subject",
filter_var($HTTP_RAW_POST_DATA, FILTER_SANITIZE_STRING),
"From: my.email@example.com\n");
}
?>
Of course, you should replace the e-mail address by your e-mail address to receive the e-mails. Note that this e-mail address will be publicly visible; thus, you should use an e-mail address that you are willing to abandon in case it is abused.
The name of the PHP script should have the extension ".php" such that the web server can identify it as a PHP script. If you don't have access to a web server that supports PHP, you might know someone who does and is willing to host your script (at the risk that it significantly increases network traffic).
The script itself checks whether any raw data (in plain text format) has been posted to it (see below for how this is done in JavaScript). If so, it sends an e-mail with the sanitized raw data. Sanitizing is necessary to avoid abuse of the script by others. The maximum size of the raw data depends on the configuration of the web server; typically it's more than a megabyte.
In the JavaScript code of the web app, you can then send some data (here the string "my\r\ndata\r\n"
) through the PHP script (here it is assumed to be at "http://example.com/url/of/php/script/emailme.php"
):
var httpRequest = new XMLHttpRequest();
httpRequest.open("post", "http://example.com/url/of/php/script/emailme.php", true);
httpRequest.setRequestHeader("Content-Type", "text/plain");
httpRequest.send("my\r\ndata\r\n");
Of course, you should replace the URL of the PHP script to wherever your script is located and you should replace the data that is sent by any string you want to send. (Note the recommended line breaks with a return and a newline character: "\r\n"
.)
For more information about different ways of using XMLHttpRequest
in JavaScript, see Using XMLHttpRequest in the Mozilla Developer Network.