I would like to access a public google drive folder and get all the images from it. This works, but I would like to be able to enter without having to login in a popup. I read that you can actually do this by using the .json file from a service account. But I haven't seen any code for this approach. Where and what should I change in this code? (I'm including the whole code because I don't know exactly where to initiate this service account authentication.)
<html>
<head>
<title>My Google Drive Images</title>
</head>
<body>
<h1>My Google Drive Images</h1>
<div id="image-container"></div>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize_button" onclick="handleAuthClick()">Authorize</button>
<button id="signout_button" onclick="handleSignoutClick()">Sign Out</button>
<pre id="content" style="white-space: pre-wrap;"></pre>
<script type="text/javascript">
/* exported gapiLoaded */
/* exported gisLoaded */
/* exported handleAuthClick */
/* exported handleSignoutClick */
// TODO(developer): Set to client ID and API key from the Developer Console
const CLIENT_ID = 'CLIENT_ID';
const API_KEY = 'API_KEY';
// Discovery doc URL for APIs used by the quickstart
const DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/drive/v3/rest';
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
const SCOPES = 'https://www.googleapis.com/auth/drive';
let tokenClient;
let gapiInited = false;
let gisInited = false;
document.getElementById('authorize_button').style.visibility = 'hidden';
document.getElementById('signout_button').style.visibility = 'hidden';
/**
* Callback after api.js is loaded.
*/
function gapiLoaded() {
gapi.load('client', initializeGapiClient);
}
/**
* Callback after the API client is loaded. Loads the
* discovery doc to initialize the API.
*/
async function initializeGapiClient() {
await gapi.client.init({
apiKey: API_KEY,
discoveryDocs: [DISCOVERY_DOC],
});
gapiInited = true;
maybeEnableButtons();
}
/**
* Callback after Google Identity Services are loaded.
*/
function gisLoaded() {
tokenClient = google.accounts.oauth2.initTokenClient({
client_id: CLIENT_ID,
scope: SCOPES,
callback: '', // defined later
});
gisInited = true;
maybeEnableButtons();
}
/**
* Enables user interaction after all libraries are loaded.
*/
function maybeEnableButtons() {
if (gapiInited && gisInited) {
document.getElementById('authorize_button').style.visibility = 'visible';
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick() {
tokenClient.callback = async (resp) => {
if (resp.error !== undefined) {
throw (resp);
}
document.getElementById('signout_button').style.visibility = 'visible';
document.getElementById('authorize_button').innerText = 'Refresh';
await listFiles();
};
if (gapi.client.getToken() === null) {
// Prompt the user to select a Google Account and ask for consent to share their data
// when establishing a new session.
tokenClient.requestAccessToken({prompt: 'consent'});
} else {
// Skip display of account chooser and consent dialog for an existing session.
tokenClient.requestAccessToken({prompt: ''});
}
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick() {
const token = gapi.client.getToken();
if (token !== null) {
google.accounts.oauth2.revoke(token.access_token);
gapi.client.setToken('');
document.getElementById('content').innerText = '';
document.getElementById('authorize_button').innerText = 'Authorize';
document.getElementById('signout_button').style.visibility = 'hidden';
}
}
function listFiles() {
console.log("Listing files in folder");
gapi.client.drive.files.list({
"includeItemsFromAllDrives": true,
"supportsAllDrives": true,
"q": "trashed = false and parents in 'FOLDER_ID'"
}).then(function(response) {
console.log("Files listed successfully");
var files = response.result.files;
if (files && files.length > 0) {
console.log(files.length + " files found");
for (var i = 0; i < files.length; i++) {
var file = files[i];
var fileId = file.id;
var fileUrl = "https://drive.google.com/u/0/uc?id=" + fileId;
var imgTag = document.createElement("img");
imgTag.src = fileUrl;
document.getElementById("image-container").appendChild(imgTag);
}
} else {
console.log("No files found.");
}
}, function(reason) {
console.log("Error listing files: " + reason.result.error.message);
});
}
</script>
<script async defer src="https://apis.google.com/js/api.js" onload="gapiLoaded()"></script>
<script async defer src="https://accounts.google.com/gsi/client" onload="gisLoaded()"></script>
</body>
</html>
I already tried changing the scopes and I read all that I could, but this topic is just not on the internet. The best case would be to don't use OAuth, but as I've read it's needed for accessing this API. Even the Google Drive API Reference only says this note, but it doesn't elaborate on this aspect:
Note: Authorization optional.
Could somebody please help me on this topic?
I would like to access a public google drive folder and get all the images from it.
If all you want to do is read it and its public, then you could just use an API Key.
I read that you can actually do this by using the .json file from a service account.
Client side JavaScript does not support service account authorization flow. You need to use implicit flow in and request authorization of a user to access the ir private data.
To use Service accounts you must use a server sided programing language
I am very new to using API and getting JSON data using OAuth. Could anybody help me? I am trying to access clients google photos and read them. These code snippets are from google photos documentation. I modified it but still having error: "Failed to load resource: the server responded with a status of 401 ()" and "Uncaught {error: "idpiframe_initialization_failed", details: "Not a valid origin for the client: http://127.0.0.…itelist this origin for your project's client ID."}"
Thank you!!!
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
<script>
var GoogleAuth;
var SCOPE = 'https://www.googleapis.com/auth/drive.photos.readonly';
function handleClientLoad() {
// Load the API's client and auth2 modules.
// Call the initClient function after the modules load.
gapi.load('client:auth2', initClient);
}
function initClient() {
// Retrieve the discovery document for version 3 of Google Drive API.
// In practice, your app can retrieve one or more discovery documents.
var discoveryUrl = 'https://www.googleapis.com/discovery/v1/apis/photos/v1/rest';
// Initialize the gapi.client object, which app uses to make API requests.
// Get API key and client ID from API Console.
// 'scope' field specifies space-delimited list of access scopes.
gapi.client.init({
'apiKey': 'XXXXXXXXXXXX',
'discoveryDocs': [discoveryUrl],
'clientId': 'XXXXXXXXXXXXXXXXXX',
'scope': SCOPE
}).then(function () {
GoogleAuth = gapi.auth2.getAuthInstance();
// Listen for sign-in state changes.
GoogleAuth.isSignedIn.listen(updateSigninStatus);
// Handle initial sign-in state. (Determine if user is already signed in.)
var user = GoogleAuth.currentUser.get();
setSigninStatus();
// Call handleAuthClick function when user clicks on
// "Sign In/Authorize" button.
$('#sign-in-or-out-button').click(function () {
handleAuthClick();
});
$('#revoke-access-button').click(function () {
revokeAccess();
});
});
}
function handleAuthClick() {
if (GoogleAuth.isSignedIn.get()) {
// User is authorized and has clicked 'Sign out' button.
GoogleAuth.signOut();
} else {
// User is not signed in. Start Google auth flow.
GoogleAuth.signIn();
}
}
function revokeAccess() {
GoogleAuth.disconnect();
}
function setSigninStatus(isSignedIn) {
var user = GoogleAuth.currentUser.get();
var isAuthorized = user.hasGrantedScopes(SCOPE);
if (isAuthorized) {
$('#sign-in-or-out-button').html('Sign out');
$('#revoke-access-button').css('display', 'inline-block');
$('#auth-status').html('You are currently signed in and have granted ' +
'access to this app.');
} else {
$('#sign-in-or-out-button').html('Sign In/Authorize');
$('#revoke-access-button').css('display', 'none');
$('#auth-status').html('You have not authorized this app or you are ' +
'signed out.');
}
}
function updateSigninStatus(isSignedIn) {
setSigninStatus();
}
</script>
<button id="sign-in-or-out-button"
style="margin-left: 25px">Sign In/Authorize
</button>
<button id="revoke-access-button"
style="display: none; margin-left: 25px">Revoke access
</button>
<div id="auth-status" style="display: inline; padding-left: 25px"></div>
use this link to get more details
On right side there is button Execute, on click that button you will get all photos ,
you can also find code just clicking a icon right side square icon of text Try this API, a popup will open, click on JAVASCRIPT Tab , you will find code
https://developers.google.com/photos/library/reference/rest/v1/mediaItems/search
Accessing Google Photo API with your standard Google Apps Script token
I believe you can use the token that you already have with Google Apps Script.
I did go into the Console and setup the credentials for this project but I'm not using them.
function listImages() {
var token='';
var html='';
var n=0;
do{
var params = {muteHttpExceptions:true,headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()}};
var url=Utilities.formatString('https://photoslibrary.googleapis.com/v1/mediaItems?pageSize=100%s',(token!=null)?"&pageToken=" + token:"");
var resp=UrlFetchApp.fetch(url,params);
Logger.log(resp);
var js=JSON.parse(resp.getContentText());
for(var i=0;i<js.mediaItems.length;i++) {
html+=Utilities.formatString('<br />%s - File Name: %s<br /><img src="%s" width="265"/>',++n,js.mediaItems[i].filename,js.mediaItems[i].baseUrl);
}
token=js.nextPageToken;
}while(token!=null);
var userInterface=HtmlService.createHtmlOutput(html).setWidth(1200).setHeight(500);
//SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Images')//dialog
SpreadsheetApp.getUi().showSidebar(userInterface);//sidebard
}
Try This Code
call onAuthPhotoApiLoad function on button click
**also include js of google **
var scopeApi = ['https://www.googleapis.com/auth/photoslibrary', 'https://www.googleapis.com/auth/photoslibrary.readonly', 'https://www.googleapis.com/auth/photoslibrary.readonly.appcreateddata'];
function onAuthPhotoApiLoad() {
window.gapi.auth.authorize(
{
'client_id': "Put Client ID Here",
'scope': scopeApi,
'immediate': false
},
handlePhotoApiAuthResult);
}
function handlePhotoApiAuthResult(authResult) {
if (authResult && !authResult.error) {
oauthToken = authResult.access_token;
GetAllPhotoGoogleApi();
}
}
function GetAllPhotoGoogleApi() {
gapi.client.request({
'path': 'https://photoslibrary.googleapis.com/v1/mediaItems:search',
'method': 'POST',
'body': {
"filters": {
"mediaTypeFilter": {
"mediaTypes": ["PHOTO"]
}
}
}
}).then(function (response) {
console.log(response);
}, function (reason) {
console.log(reason);
});
}
I am trying to use the Gmail API to access the email in a web application. I have tried the example at https://developers.google.com/gmail/api/quickstart/php and is working fine. Now I want to get the access token using javascript API and use in the above example.
gapi.auth2.authorize({
client_id: 'CLIENT_ID.apps.googleusercontent.com',
scope: 'email profile openid',
response_type: 'id_token permission'
}, function(response) {
if (response.error) {
// An error happened!
return;
}
// The user authorized the application for the scopes requested.
var accessToken = response.access_token;
var idToken = response.id_token;
// You can also now use gapi.client to perform authenticated requests.
});
When I manually add the response from javascript API in the php script it is showing error
Uncaught exception 'LogicException' with message 'refresh token must be passed in or set as part of setAccessToken' in D:\wamp\www\gmailexample\google-api-php-client-2.2.0\src\Google\Client.php:267
Below is the php script I am using.
<?php
require_once '/google-api-php-client-2.2.0/vendor/autoload.php';
define('APPLICATION_NAME', 'Gmail API PHP Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/gmail-php-quickstart.json');
define('CLIENT_SECRET_PATH', 'client_secret.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/gmail-php-quickstart.json
define('SCOPES', implode(' ', array(
Google_Service_Gmail::GMAIL_READONLY)
));
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient() {
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
$accessToken= json_decode('{"access_token":"asdfsasdfsasdfsasdfs","expires_in":2255,"expires_at":254877}', true);
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
}
/**
* Expands the home directory alias '~' to the full path.
* #param string $path the path to expand.
* #return string the expanded path.
*/
function expandHomeDirectory($path) {
$homeDirectory = getenv('HOME');
if (empty($homeDirectory)) {
$homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
}
return str_replace('~', realpath($homeDirectory), $path);
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Gmail($client);
// Print the labels in the user's account.
$user = 'me';
$results = $service->users_labels->listUsersLabels($user);
if (count($results->getLabels()) == 0) {
print "No labels found.\n";
} else {
print "Labels:\n";
foreach ($results->getLabels() as $label) {
printf("- %s\n", $label->getName());
}
}
Please help.
Ok my friend, here is your solution. To make sure you understand this, I worked an example. First, inside your working directory, make sure you have the Google PHP Client library and two other files. The first one should be called index.php and paste the following code inside that file:
<html>
<head>
<title>JS/PHP Google Sample</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script type="text/javascript">
function handleClientLoad() {
// Loads the client library and the auth2 library together for efficiency.
// Loading the auth2 library is optional here since `gapi.client.init` function will load
// it if not already loaded. Loading it upfront can save one network request.
gapi.load('client:auth2', initClient);
}
function initClient() {
// Initialize the client with API key and People API, and initialize OAuth with an
// OAuth 2.0 client ID and scopes (space delimited string) to request access.
gapi.client.init({
apiKey: 'YOUR API KEY GOES HERE',
clientId: 'YOUR CLIENT ID GOES HERE',
scope: 'email profile https://www.googleapis.com/auth/gmail.readonly',
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
});
}
function updateSigninStatus(isSignedIn) {
// When signin status changes, this function is called.
// If the signin status is changed to signedIn, we make an API call.
if (isSignedIn) {
$("#signout-button").show();
$("#signin-button").hide();
makeApiCall();
} else {
$("#signin-button").show();
$("#signout-button").hide();
}
}
function handleSignInClick(event) {
// Ideally the button should only show up after gapi.client.init finishes, so that this
// handler won't be called before OAuth is initialized.
gapi.auth2.getAuthInstance().signIn();
}
function handleSignOutClick(event) {
var host = "http://"+window.location.hostname;
gapi.auth2.GoogleUser.prototype.disconnect();
window.open(host, "_self");
}
function makeApiCall() {
// Make an API call to the People API, and print the user's given name.
var accsTkn = gapi.auth2.getAuthInstance().$K.Q7.access_token;
var formData = new FormData();
formData.append("access_token", accsTkn); //send access token
$.ajax({
url : 'listEmails.php',
type : 'POST',
data : formData,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success : function(html) {
$("#myLabels").append(html);
}
});
}
</script>
<style>
#signin-button{
display: none;
}
#signout-button{
display: none;
}
#myLabels{
width: 80%;
min-height: 350px;
}
</style>
</head>
<body>
<center>
<h1>Google OAuth Gmail Example with Javascript and PHP</h1><br>
<button id="signin-button" onclick="handleSignInClick()">Sign In</button>
<br><br><br>
<div id="myLabels">
Emails list: <br><br>
</div>
<br><br>
<button id="signout-button" onclick="handleSignOutClick()">Sign Out</button>
</center>
<script async defer src="https://apis.google.com/js/api.js" onload="this.onload=function(){};handleClientLoad()" onreadystatechange="if (this.readyState === 'complete') this.onload()"> </script>
</body>
</html>
Next, the second file should be named listEmails.php and paste the following code inside:
<?php session_start();
require_once "path_to_php_client_lib/vendor/autoload.php"; //include php client library
//set the required parameteres
$scopes = array("https://www.googleapis.com/auth/gmail.readonly");
$client = new Google_Client();
$client->setRedirectUri('http://'.$_SERVER['HTTP_HOST'].'listEmails.php');
$client->setAuthConfig("client_secret.json");
$client->addScope($scopes);
$client->setAccessToken($_POST["access_token"]);
$service = new Google_Service_Gmail($client); // define service to be rquested
$pageToken = NULL;
$messages = array();
$opt_param = array("maxResults" => 5);
try {
$messagesResponse = $service->users_messages->listUsersMessages("me", $opt_param);
if ($messagesResponse->getMessages()) {
$messages = array_merge($messages, $messagesResponse->getMessages());
}
} catch (Exception $e) {
print 'An error occurred: ' . $e->getMessage();
}
foreach ($messages as $message) {
$msgId = $message->getId();
$optParams = array("format" => "full");
$uniqueMsg = $service->users_messages->get("me", $msgId, $optParams);
print 'Message with ID: ' . $uniqueMsg->id . '<br>';
print 'Message From: ' . $uniqueMsg->getPayload()->getHeaders()[18]->value . '<br><br>**************************<br><br>';
}
?>
Understanding the example:
The documentation here clearly explains
This OAuth 2.0 flow is called the implicit grant flow. It is designed for applications that access APIs only while the user is present at the application. These applications are not able to store confidential information.
That means that using the Javascript authentication flow you will NOT be able to get offline access. Having that in mind, we can move on.
As you can then see on the php script, you are not required to refresh the token since this will be managed by the Javascript client library; And there you go... I hope this helps!
I've been writing a client (Chrome browser) App that integrates with GMail via the REST API. My app is written in Javascript/Angular and most of the GMail integration works fine. It can fetch from GMail - emails, profiles, labels, etc.
I'm not able to send emails I create. However, the emails I try to send do appear in the GMail sent list and, if I modify the email by adding the 'INBOX' label, they also appear in the GMail inbox. But none of the emails make it to their destination. I've been testing with several email accounts - Hotmail, Yahoo and another GMail account. Emails are never delivered to their destinations - I've checked the inboxes, spam, etc.
My code is below ... Function 'initializeGMailInterface' is run first (via the User Interface) to authorize and then the 'sendEmail' function (also via the User Interface). The code seems to track with examples I've seen and the documentation Google provides for their REST API. Authentication seems to work OK - and as I mentioned, I'm able to fetch emails, etc.
How do I get the emails to their destination?
var CLIENT_ID = '853643010367revnu8a5t7klsvsc5us50bgml5s99s4d.apps.googleusercontent.com';
var SCOPES = ['https://mail.google.com/', 'https://www.googleapis.com/auth/gmail.send', 'https://www.googleapis.com/auth/gmail.modify', 'https://www.googleapis.com/auth/gmail.labels'];
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
loadGmailApi();
}
}
$scope.initializeGMailInterface = function() {
gapi.auth.authorize({
client_id: CLIENT_ID,
scope: SCOPES,
immediate: true
}, handleAuthResult);
};
function loadGmailApi() {
gapi.client.load('gmail', 'v1', function() {
console.log("Loaded GMail API");
});
}
$scope.sendEmail = function() {
var content = 'HELLO';
// I have an email account on GMail. Lets call it 'theSenderEmail#gmail.com'
var sender = 'theSenderEmail#gmail.com';
// And an email account on Hotmail. Lets call it 'theReceiverEmail#gmail.com'\
// Note: I tried several 'receiver' email accounts, including one on GMail. None received the email.
var receiver = 'theReceiverEmail#hotmail.com';
var to = 'To: ' +receiver;
var from = 'From: ' +sender;
var subject = 'Subject: ' +'HELLO TEST';
var contentType = 'Content-Type: text/plain; charset=utf-8';
var mime = 'MIME-Version: 1.0';
var message = "";
message += to +"\r\n";
message += from +"\r\n";
message += subject +"\r\n";
message += contentType +"\r\n";
message += mime +"\r\n";
message += "\r\n" + content;
sendMessage(message, receiver, sender);
};
function sendMessage(message, receiver, sender) {
var headers = getClientRequestHeaders();
var path = "gmail/v1/users/me/messages?key=" + CLIENT_ID;
var base64EncodedEmail = btoa(message).replace(/\+/g, '-').replace(/\//g, '_');
gapi.client.request({
path: path,
method: "POST",
headers: headers,
body: {
'raw': base64EncodedEmail
}
}).then(function (response) {
});
}
var t = null;
function getClientRequestHeaders() {
if(!t) t = gapi.auth.getToken();
gapi.auth.setToken({token: t['access_token']});
var a = "Bearer " + t["access_token"];
return {
"Authorization": a,
"X-JavaScript-User-Agent": "Google APIs Explorer"
};
}
Your code is doing an insert(). Do a send() instead:
var path = "gmail/v1/users/me/messages/send?key=" + CLIENT_ID;
The 'emailJS' is a good solution for sending email from Javascript.
EmailJS helps to send emails using client-side technologies only. No server is required.
Additionally, you can easily add attachments, require CAPTCHA validation, switch
between the email services without making code changes, review the history of
the email request, and more.
More Info
I want my website to have the ability to send an email without refreshing the page. So I want to use Javascript.
<form action="javascript:sendMail();" name="pmForm" id="pmForm" method="post">
Enter Friend's Email:
<input name="pmSubject" id="pmSubject" type="text" maxlength="64" style="width:98%;" />
<input name="pmSubmit" type="submit" value="Invite" />
Here is how I want to call the function, but I'm not sure what to put into the javascript function. From the research I've done I found an example that uses the mailto method, but my understanding is that doesn't actually send directly from the site.
So my question is where can I find what to put inside the JavaScript function to send an email directly from the website.
function sendMail() {
/* ...code here... */
}
You can't send an email directly with javascript.
You can, however, open the user's mail client:
window.open('mailto:test#example.com');
There are also some parameters to pre-fill the subject and the body:
window.open('mailto:test#example.com?subject=subject&body=body');
Another solution would be to do an ajax call to your server, so that the server sends the email. Be careful not to allow anyone to send any email through your server.
Indirect via Your Server - Calling 3rd Party API - secure and recommended
Your server can call the 3rd Party API. The API Keys are not exposed to client.
node.js
const axios = require('axios');
async function sendEmail(name, email, subject, message) {
const data = JSON.stringify({
"Messages": [{
"From": {"Email": "<YOUR EMAIL>", "Name": "<YOUR NAME>"},
"To": [{"Email": email, "Name": name}],
"Subject": subject,
"TextPart": message
}]
});
const config = {
method: 'post',
url: 'https://api.mailjet.com/v3.1/send',
data: data,
headers: {'Content-Type': 'application/json'},
auth: {username: '<API Key>', password: '<Secret Key>'},
};
return axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
}
// define your own email api which points to your server.
app.post('/api/sendemail/', function (req, res) {
const {name, email, subject, message} = req.body;
//implement your spam protection or checks.
sendEmail(name, email, subject, message);
});
and then use use fetch on client side to call your email API.
Use from email which you used to register on Mailjet. You can authenticate more addresses too. Mailjet offers a generous free tier.
Update 2023: As pointed out in the comments the method below does not work any more due to CORS
This can be only useful if you want to test sending email and to do this
visit https://api.mailjet.com/stats (yes a 404 page)
and run this code in the browser console (with the secrets populated)
Directly From Client - Calling 3rd Party API - not recommended
in short:
register for Mailjet to get an API key and Secret
use fetch to call API to send an email
Like this -
function sendMail(name, email, subject, message) {
const myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.set('Authorization', 'Basic ' + btoa('<API Key>'+":" +'<Secret Key>'));
const data = JSON.stringify({
"Messages": [{
"From": {"Email": "<YOUR EMAIL>", "Name": "<YOUR NAME>"},
"To": [{"Email": email, "Name": name}],
"Subject": subject,
"TextPart": message
}]
});
const requestOptions = {
method: 'POST',
headers: myHeaders,
body: data,
};
fetch("https://api.mailjet.com/v3.1/send", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
sendMail('Test Name',"<YOUR EMAIL>",'Test Subject','Test Message')
Note: Keep in mind that your API key is visible to anyone, so any malicious user may use your key to send out emails that can eat up your quota.
I couldn't find an answer that really satisfied the original question.
Mandrill is not desirable due to it's new pricing policy, plus it required a backend service if you wanted to keep your credentials safe.
It's often preferable to hide your email so you don't end up on any lists (the mailto solution exposes this issue, and isn't convenient for most users).
It's a hassle to set up sendMail or require a backend at all just to send an email.
I put together a simple free service that allows you to make a standard HTTP POST request to send an email. It's called PostMail, and you can simply post a form, use JavaScript or jQuery. When you sign up, it provides you with code that you can copy & paste into your website. Here are some examples:
JavaScript:
<form id="javascript_form">
<input type="text" name="subject" placeholder="Subject" />
<textarea name="text" placeholder="Message"></textarea>
<input type="submit" id="js_send" value="Send" />
</form>
<script>
//update this with your js_form selector
var form_id_js = "javascript_form";
var data_js = {
"access_token": "{your access token}" // sent after you sign up
};
function js_onSuccess() {
// remove this to avoid redirect
window.location = window.location.pathname + "?message=Email+Successfully+Sent%21&isError=0";
}
function js_onError(error) {
// remove this to avoid redirect
window.location = window.location.pathname + "?message=Email+could+not+be+sent.&isError=1";
}
var sendButton = document.getElementById("js_send");
function js_send() {
sendButton.value='Sending…';
sendButton.disabled=true;
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
js_onSuccess();
} else
if(request.readyState == 4) {
js_onError(request.response);
}
};
var subject = document.querySelector("#" + form_id_js + " [name='subject']").value;
var message = document.querySelector("#" + form_id_js + " [name='text']").value;
data_js['subject'] = subject;
data_js['text'] = message;
var params = toParams(data_js);
request.open("POST", "https://postmail.invotes.com/send", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(params);
return false;
}
sendButton.onclick = js_send;
function toParams(data_js) {
var form_data = [];
for ( var key in data_js ) {
form_data.push(encodeURIComponent(key) + "=" + encodeURIComponent(data_js[key]));
}
return form_data.join("&");
}
var js_form = document.getElementById(form_id_js);
js_form.addEventListener("submit", function (e) {
e.preventDefault();
});
</script>
jQuery:
<form id="jquery_form">
<input type="text" name="subject" placeholder="Subject" />
<textarea name="text" placeholder="Message" ></textarea>
<input type="submit" name="send" value="Send" />
</form>
<script>
//update this with your $form selector
var form_id = "jquery_form";
var data = {
"access_token": "{your access token}" // sent after you sign up
};
function onSuccess() {
// remove this to avoid redirect
window.location = window.location.pathname + "?message=Email+Successfully+Sent%21&isError=0";
}
function onError(error) {
// remove this to avoid redirect
window.location = window.location.pathname + "?message=Email+could+not+be+sent.&isError=1";
}
var sendButton = $("#" + form_id + " [name='send']");
function send() {
sendButton.val('Sending…');
sendButton.prop('disabled',true);
var subject = $("#" + form_id + " [name='subject']").val();
var message = $("#" + form_id + " [name='text']").val();
data['subject'] = subject;
data['text'] = message;
$.post('https://postmail.invotes.com/send',
data,
onSuccess
).fail(onError);
return false;
}
sendButton.on('click', send);
var $form = $("#" + form_id);
$form.submit(function( event ) {
event.preventDefault();
});
</script>
Again, in full disclosure, I created this service because I could not find a suitable answer.
I know I am wayyy too late to write an answer for this question but nevertheless I think this will be use for anybody who is thinking of sending emails out via javascript.
The first way I would suggest is using a callback to do this on the server. If you really want it to be handled using javascript folowing is what I recommend.
The easiest way I found was using smtpJs. A free library which can be used to send emails.
1.Include the script like below
<script src="https://smtpjs.com/v3/smtp.js"></script>
2. You can either send an email like this
Email.send({
Host : "smtp.yourisp.com",
Username : "username",
Password : "password",
To : 'them#website.com',
From : "you#isp.com",
Subject : "This is the subject",
Body : "And this is the body"
}).then(
message => alert(message)
);
Which is not advisable as it will display your password on the client side.Thus you can do the following which encrypt your SMTP credentials, and lock it to a single domain, and pass a secure token instead of the credentials instead.
Email.send({
SecureToken : "C973D7AD-F097-4B95-91F4-40ABC5567812",
To : 'them#website.com',
From : "you#isp.com",
Subject : "This is the subject",
Body : "And this is the body"
}).then(
message => alert(message)
);
Finally if you do not have a SMTP server you use an smtp relay service such as Elastic Email
Also here is the link to the official SmtpJS.com website where you can find all the example you need and the place where you can create your secure token.
I hope someone find this details useful. Happy coding.
You can find what to put inside the JavaScript function in this post.
function getAjax() {
try {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch (try_again) {
return new ActiveXObject('Microsoft.XMLHTTP');
}
}
} catch (fail) {
return null;
}
}
function sendMail(to, subject) {
var rq = getAjax();
if (rq) {
// Success; attempt to use an Ajax request to a PHP script to send the e-mail
try {
rq.open('GET', 'sendmail.php?to=' + encodeURIComponent(to) + '&subject=' + encodeURIComponent(subject) + '&d=' + new Date().getTime().toString(), true);
rq.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status >= 400) {
// The request failed; fall back to e-mail client
window.open('mailto:' + to + '?subject=' + encodeURIComponent(subject));
}
}
};
rq.send(null);
} catch (fail) {
// Failed to open the request; fall back to e-mail client
window.open('mailto:' + to + '?subject=' + encodeURIComponent(subject));
}
} else {
// Failed to create the request; fall back to e-mail client
window.open('mailto:' + to + '?subject=' + encodeURIComponent(subject));
}
}
Provide your own PHP (or whatever language) script to send the e-mail.
I am breaking the news to you. You CAN'T send an email with JavaScript per se.
Based on the context of the OP's question, my answer above does not hold true anymore as pointed out by #KennyEvitt in the comments. Looks like you can use JavaScript as an SMTP client.
However, I have not digged deeper to find out if it's secure & cross-browser compatible enough. So, I can neither encourage nor discourage you to use it. Use at your own risk.
There seems to be a new solution at the horizon. It's called EmailJS. They claim that no server code is needed. You can request an invitation.
Update August 2016: EmailJS seems to be live already. You can send up to 200 emails per month for free and it offers subscriptions for higher volumes.
window.open('mailto:test#example.com'); as above
does nothing to hide the "test#example.com" email address from being harvested by spambots. I used to constantly run into this problem.
var recipient="test";
var at = String.fromCharCode(64);
var dotcom="example.com";
var mail="mailto:";
window.open(mail+recipient+at+dotcom);
In your sendMail() function, add an ajax call to your backend, where you can implement this on the server side.
Javascript is client-side, you cannot email with Javascript. Browser recognizes maybe only mailto: and starts your default mail client.
JavaScript can't send email from a web browser. However, stepping back from the solution you've already tried to implement, you can do something that meets the original requirement:
send an email without refreshing the page
You can use JavaScript to construct the values that the email will need and then make an AJAX request to a server resource that actually sends the email. (I don't know what server-side languages/technologies you're using, so that part is up to you.)
If you're not familiar with AJAX, a quick Google search will give you a lot of information. Generally you can get it up and running quickly with jQuery's $.ajax() function. You just need to have a page on the server that can be called in the request.
It seems like one 'answer' to this is to implement an SMPT client. See email.js for a JavaScript library with an SMTP client.
Here's the GitHub repo for the SMTP client. Based on the repo's README, it appears that various shims or polyfills may be required depending on the client browser, but overall it does certainly seem feasible (if not actually significantly accomplished), tho not in a way that's easily describable by even a reasonably-long answer here.
There is a combination service. You can combine the above listed solutions like mandrill with a service EmailJS, which can make the system more secure.
They have not yet started the service though.
Another way to send email from JavaScript, is to use directtomx.com as follows;
Email = {
Send : function (to,from,subject,body,apikey)
{
if (apikey == undefined)
{
apikey = Email.apikey;
}
var nocache= Math.floor((Math.random() * 1000000) + 1);
var strUrl = "http://directtomx.azurewebsites.net/mx.asmx/Send?";
strUrl += "apikey=" + apikey;
strUrl += "&from=" + from;
strUrl += "&to=" + to;
strUrl += "&subject=" + encodeURIComponent(subject);
strUrl += "&body=" + encodeURIComponent(body);
strUrl += "&cachebuster=" + nocache;
Email.addScript(strUrl);
},
apikey : "",
addScript : function(src){
var s = document.createElement( 'link' );
s.setAttribute( 'rel', 'stylesheet' );
s.setAttribute( 'type', 'text/xml' );
s.setAttribute( 'href', src);
document.body.appendChild( s );
}
};
Then call it from your page as follows;
window.onload = function(){
Email.apikey = "-- Your api key ---";
Email.Send("to#domain.com","from#domain.com","Sent","Worked!");
}
There is not a straight answer to your question as we can not send email only using javascript, but there are ways to use javascript to send emails for us:
1) using an api to and call the api via javascript to send the email for us, for example https://www.emailjs.com says that you can use such a code below to call their api after some setting:
var service_id = 'my_mandrill';
var template_id = 'feedback';
var template_params = {
name: 'John',
reply_email: 'john#doe.com',
message: 'This is awesome!'
};
emailjs.send(service_id,template_id,template_params);
2) create a backend code to send an email for you, you can use any backend framework to do it for you.
3) using something like:
window.open('mailto:me#http://stackoverflow.com/');
which will open your email application, this might get into blocked popup in your browser.
In general, sending an email is a server task, so should be done in backend languages, but we can use javascript to collect the data which is needed and send it to the server or api, also we can use third parities application and open them via the browser using javascript as mentioned above.
If and only if i had to use some js library, i would do that with SMTPJs library.It offers encryption to your credentials such as username, password etc.
The short answer is that you can't do it using JavaScript alone. You'd need a server-side handler to connect with the SMTP server to actually send the mail. There are many simple mail scripts online, such as this one for PHP:
Use Ajax to send request to the PHP script ,check that required field are not empty or incorrect using js also keep a record of mail send by whom from your server.
function sendMail() is good for doing that.
Check for any error caught while mailing from your script and take appropriate action.
For resolving it for example if the mail address is incorrect or mail is not send due to server problem or it's in queue in such condition report it to user immediately and prevent multi sending same email again and again.
Get response from your script Using jQuery GET and POST
$.get(URL,callback);
$.post(URL,callback);
Since these all are wonderful infos there's a little api called Mandrill to send mails from javascript and it works perfectly. You can give it a shot. Here's a little tutorial for the start.
Full AntiSpam version:
<div class="at">info<i class="fa fa-at"></i>google.com</div>
OR
<div class="at">info#google.com</div>
<style>
.at {
color: blue;
cursor: pointer;
}
.at:hover {
color: red;
}
</style>
<script>
const el33 = document.querySelector(".at");
el33.onclick = () => {
let recipient="info";
let at = String.fromCharCode(64);
let dotcom="google.com";
let mail="mailto:";
window.open(mail+recipient+at+dotcom);
}
</script>
Send an email using the JavaScript or jQuery
var ConvertedFileStream;
var g_recipient;
var g_subject;
var g_body;
var g_attachmentname;
function SendMailItem(p_recipient, p_subject, p_body, p_file, p_attachmentname, progressSymbol) {
// Email address of the recipient
g_recipient = p_recipient;
// Subject line of an email
g_subject = p_subject;
// Body description of an email
g_body = p_body;
// attachments of an email
g_attachmentname = p_attachmentname;
SendC360Email(g_recipient, g_subject, g_body, g_attachmentname);
}
function SendC360Email(g_recipient, g_subject, g_body, g_attachmentname) {
var flag = confirm('Would you like continue with email');
if (flag == true) {
try {
//p_file = g_attachmentname;
//var FileExtension = p_file.substring(p_file.lastIndexOf(".") + 1);
// FileExtension = FileExtension.toUpperCase();
//alert(FileExtension);
SendMailHere = true;
//if (FileExtension != "PDF") {
// if (confirm('Convert to PDF?')) {
// SendMailHere = false;
// }
//}
if (SendMailHere) {
var objO = new ActiveXObject('Outlook.Application');
var objNS = objO.GetNameSpace('MAPI');
var mItm = objO.CreateItem(0);
if (g_recipient.length > 0) {
mItm.To = g_recipient;
}
mItm.Subject = g_subject;
// if there is only one attachment
// p_file = g_attachmentname;
// mAts.add(p_file, 1, g_body.length + 1, g_attachmentname);
// If there are multiple attachment files
//Split the files names
var arrFileName = g_attachmentname.split(";");
// alert(g_attachmentname);
//alert(arrFileName.length);
var mAts = mItm.Attachments;
for (var i = 0; i < arrFileName.length; i++)
{
//alert(arrFileName[i]);
p_file = arrFileName[i];
if (p_file.length > 0)
{
//mAts.add(p_file, 1, g_body.length + 1, g_attachmentname);
mAts.add(p_file, i, g_body.length + 1, p_file);
}
}
mItm.Display();
mItm.Body = g_body;
mItm.GetInspector.WindowState = 2;
}
//hideProgressDiv();
} catch (e) {
//debugger;
//hideProgressDiv();
alert('Unable to send email. Please check the following: \n' +
'1. Microsoft Outlook is installed.\n' +
'2. In IE the SharePoint Site is trusted.\n' +
'3. In IE the setting for Initialize and Script ActiveX controls not marked as safe is Enabled in the Trusted zone.');
}
}
}