Sending email from browser mailgun - javascript

I want to send a simple email from the browser using mailgun. I send a working email from postman and with the download code function I managed to get the javascript code which is:
var data = new FormData();
data.append("from", "Mailgun Sandbox <postmaster#sandbox1985406854ad9e8b8dfe094531fa41e8.mailgun.org>");
data.append("to", "Example <example#gmail.com>");
data.append("subject", "Hello from Mailgun");
data.append("text", "Congratulations Example, you just sent an email with Mailgun! You are truly awesome!");
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://api:key-75a05cfds8c66bd1y4c3e854305438e5#api.mailgun.net/v3/sandbox1985406854ad9e8b8dfe094531fa41e8.mailgun.org/messages");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "0a3ad9d5-22b5-6308-d6e7-59f66360fa26");
xhr.send(data);
But when I execute this code from my browser (firefox) it does nothing. What am I doing wrong?
Changing the url from
https://api:key-75a05cfds8c66bd1y4c3e854305438e5#api.mailgun.net/v3/sandbox1985406854ad9e8b8dfe094531fa41e8.mailgun.org/messages
to
https://api.mailgun.net/v3/sandbox1985406854ad9e8b8dfe094531fa41e8.mailgun.org/messages
seems to execute, is the api:key-xx part invalid?

Don't do this. This is not an appropriate use of the Mailgun API.
By delivering this Javascript to a browser, you are giving them access to your Mailgun API key. This API key is not limited in any way whatsoever -- a malicious client could misuse the key to send an unlimited number of messages to any recipient they want, potentially racking up large bills and/or getting your account blocked for spam.
Use the Mailgun API on the server side. If you need to send messages via Javascript, create an endpoint in your application which calls the Mailgun API with appropriate restrictions in place.

Related

Secure Password Sent from Native App to HTTPS API

I have a HTTPS API server, and want to connect to it from a native Android app (built in Cordova). The app uses is a simple XHR request like so:
function authenticate() {
const username = document.querySelector('#usernameInput').value;
const password = document.querySelector('#passwordInput').value;
const xhr = new XMLHttpRequest();
const body = JSON.stringify({
username,
password,
});
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
xhr.onload = function () {
console.log(this.responseText);
};
xhr.onerror = function () {
alert('Request failed');
};
xhr.send(body);
}
function handleSubmit(event) {
event.preventDefault();
authenticate();
}
document.querySelector('#submitButton').addEventListener('click', handleSubmit);
The request works fine and the username/password are authenticated on the server or 403 is returned. My concern is I can see the password in plain text if I look at the request payload in a local debugger. Does this mean passwords are exposed over the network? If so, what should I be doing differently?
When using HTTPS only your computer and the server know the key to decrypt the data in the request, since they previously agreed on a key during the key exchange phase of the SSL/TLS connection.
Other computers in your network should not be able to read your request's content since they don't have the key. You can see it in plain text in your browser's debugger because it is plain text before you actually send it.
Don't worry about manually encrypting your data before sending it to the server, the protocol already takes care of that.

How to get new messages using gmail api

I'm writing a Google Chrome browser extension. It uses gmail-api and I want to receive incoming messages coming to the email address of the user who is logged in. How do I implement this in the background script in terms of code. I know that gmail api uses post requests such as watсh, then I don’t know how to implement the code so that I can see messages that would come in real time and my background script would be updated during this event.
My application uses the methods of pull alerts, and accordingly the documentation says that I should use requests such as
https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.subscriptions/pull
https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.subscriptions/acknowledge
How can I use all this in my code so that my script is constantly updated when I receive a new message and is it even possible in javascript?
function POST_request(method,url,_async,params)
{
let xhr= new XMLHttpRequest();
xhr.open(method,url,_async);
xhr.setRequestHeader('Authorization', 'Bearer ' + current_token);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify(params));
return(xhr.responseText);
}
let tmp={
"topicName":"projects/myprofect/topics/mytopic",
"labelFilterAction":"include",
"labelIds": ["INBOX"]
};
console.log(POST_request("POST","https://www.googleapis.com/gmail/v1/users/me/watch",false,tmp));
This query works by returning the view body
{
"historyId": "678576",
"expiration": "1555318376357"
}

How to remove automatically added connections proxy in XCC?

I want to make an ajax request from IBM Connections XCC:
let api = 'https://my-server2/api.xml'
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = () => {
if (xmlhttp.readyState == XMLHttpRequest.DONE)
if (xmlhttp.status == 200) {
console.log(xmlhttp.responseText)
}else {
console.log(`Error: ${xmlhttp.readyState}`)
}
}
Result in the network tab is a request to https://connections-host/communities/ajaxProxy/https/my-server2/api.xml so the request is proxied over the connections server. Because of this I get an empty API result since I need an authorized user session. My idea was: The user is logged in in his browser on my-server2 application. So when making an ajax request to my-server2, I can get the API information in his user context.
So my question is: How can I bypass those proxy?
Since I don't set it, I assume that connections manipulate the XMLHttpRequest class in a way like this: https://gist.github.com/dewdad/8830348
I want to view it's code to see the manipulation with this code in the console, but it only shows native code
window.XMLHttpRequest.prototype.open.toString()
"function open() {
[native code]
}"
Connections uses an AJAX proxy to control what's sent out to non-Connections sites/apps. You can configure it for your site to allow specific methods, headers and cookies to be sent to the non-Connections site. I'd take a look at this document on Connections 6.0 https://www.ibm.com/support/knowledgecenter/en/SSYGQH_6.0.0/admin/secure/t_admin_config_ajax_proxy_feature.html
I think that should help you get what you want.

Why does this email sending function not work?

Heres my email sending function:
function send() {
var key = "dJdJekCVAFIqvUJ13DEczZjgIh_4MyeIGEHz2GBYKFe";
var message_name = "defender_send_message";
var data = {};
data.value1 = document.getElementById('textBox').value;
data.value2 = localStorage.getItem("AdminsEmail");
var url = "https://maker.ifttt.com/trigger/" + message_name + "/with/key/" + key;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
console.log("Message Sent");
}
}
}
xmlhttp.open('POST', url, true);
xmlhttp.responseType = 'json';
xmlhttp.send(new FormData(data));
}
I wanted to create an email sending function with only pure js, not jquery or anything. I get the following errors when i click send:
(ignore the first error i fixed that already)
I had a jquery function that worked (but i had to get rid of it):
var message = localStorage.getItem("Message");
console.log(message + localStorage.getItem("AdminsEmail"));
var key = "dJdJekCVAFIqvUJ13DEczZjgIh_4MyeIGEHz2GBYKFe"; // << YOUR KEY HERE
var message_name = "defender_send_message"; // << YOUR MESSAGE NAME HERE
var url = "https://maker.ifttt.com/trigger/" + message_name + "/with/key/" + key;
$.ajax({
url: url,
data: {value1: message,
value2: localStorage.getItem("AdminsEmail")},
dataType: "jsonp",
complete: function(jqXHR, textStatus) {
console.log("Message Sent");
}
});
why would this work and my other function not?
EDIT 2 : Since it seems the endpoint doesn't actually return JSON, I think your original jQuery code wasn't correct either. You need to do more research into this iftt.com platform and how to use it. From what I can tell, it's meant to be used in a mobile app, not in the browser- it would be a normal POST XHR then, and CORS doesn't apply to mobile apps. They have this page for testing the endpoint- notice that it gives you an example using curl, a command-line tool, where again CORS doesn't apply. So I think you need to rethink things, this service is not designed to be used from a browser, like you are trying to do.
EDIT: since it turns out you are actually trying to use JSONP and not a plain XHR, all you need to do is implement that without jQuery- create a script tag with the server's URL and add a URL parameter to define your callback function to handle the data. This answer should give you the solution.
In your case the code might look like this :
http://www.codeply.com/go/bp/VRCwId81Vr
function foo(data)
{
// do stuff with JSON
console.log(data)
}
var script = document.createElement('script');
script.src = "https://maker.ifttt.com/trigger/defender_send_message/with/key/"+
"dJdJekCVAFIqvUJ13DEczZjgIh_4MyeIGEHz2GBYKFe?callback=foo";
document.getElementsByTagName('head')[0].appendChild(script);
Note that this doesn't work for me(but with your code, you would get Message sent printed to the console, so maybe you thought it was working?)- the response isn't JSON. Most likely the endpoint isn't actually meant to be used for JSONP?
My answer below only applies if you are trying to do a regular XHR in a browser without JSONP.
This happens because of the Cross Origin Resource Sharing policy of your browser. Your code is hosted at localhost, and it is trying to access a resource hosted at maker.ifttt.com through an XmlHttpRequest. In order to allow this to happen, the server at maker.ifttt.com would need to be configured to allow access from the localhost origin. Presumably you can not make that change as you don't control that server.
In your case, the best solution would be to make the request to maker.ifttt.com through your own server- CORS doesn't apply for server-to-server requests. Send the XmlHttpRequest to your server, take the data regarding the email from the request URL parameters, and then make the request to maker.ifttt.com using that data.

How to get HTTP header from Javascript?

I have a Tomcat server that only serves static files(html, css, js). When the request comes in it gets intercepted by a proxy server. Proxy server authenticates the user and adds a userId field to the header and forwards it my Tomcat server.
How can I access userId that has been stored in the header from javascript?
Thank you
You can't, BUT...
If such header is send to the browser you could make an ajax request and get that value from it.
This little javascript could be useful in your case. Watch out, use it with caution and sanitize or change the URL depending on your needs, this is just a "concept", not a copy-paste solution for every case. In many other cases this is not a valid solution, cause it is not the header of the loaded document, but another request. Anyway the server, content-type, etc can be use quite safely.
xmlhttp = new XMLHttpRequest();
xmlhttp.open("HEAD", document.URL ,true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
console.log(xmlhttp.getAllResponseHeaders());
}
}
xmlhttp.send();
EDIT: Ooops, seem already anwser that part also... Accessing the web page's HTTP Headers in JavaScript
Didn't read it all.
Use below script for access userId
var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
headers = req.getAllResponseHeaders().split("\n")
.map(x=>x.split(/: */,2))
.filter(x=>x[0])
.reduce((ac, x)=>{ac[x[0]] = x[1];return ac;}, {});
console.log(headers.userId);

Categories

Resources