function onSubmit(e) {
//.......
var NewSpreadSheetID = NewSpreadSheet.getId();
var File = Drive.Files.get(NewSpreadSheetID);
var url = File.exportLinks[MimeType.CSV];
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer' + token
}
});
var blobs = [response.getBlob().setName(DirectoryName)];
if (EmailBoolean == "yes") {
var UserEmail = e.response.getResponseForItem(frm[130]).getResponse().toString();
var CreatorEmail = Session.getEffectiveUser().getEmail();
MailApp.sendEmail({
to : UserEmail,
subject: "Your project spreadsheet",
attachments: blobs
});
}
MailApp.sendEmail({
to : CreatorEmail,
subject: "Your project spreadsheet",
attachments: blobs
});
}
When this email is sent to the non-gmail account, say a hotmail account, the file essentially is attached as a link to a site that redirects the user to log in to a g-mail account.
Related
I'm wondering if it is possible to link a previously user created with email & password with Facebook login if the email is the same?
I've tested registering and logging in with Facebook and it works fine, same for email & password, but if I already have my facebook email registered then the Facebook log in button won't work and the accounts are not linked at all.
I don't think the code is necessary but either way I'm puting it below:
$(document).on('click', "#btn-login-fb", function (event) {
var provider = new firebase.auth.FacebookAuthProvider();
provider.addScope('public_profile');
provider.addScope('email');
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)
.then(function () {
})
.catch(function (error) {
var errorCode = error.code;
var errorMessage = error.message;
});
firebase.auth().signInWithPopup(provider).then(function (result) {
var token = result.credential.accessToken;
var user = result.user;
if (result.additionalUserInfo.isNewUser) {
var SendData = {
uidAux: user.uid,
FotoPerfilAux: user.photoURL,
NomeCompleto: user.displayName,
Email: user.email,
FotoPerfilAux: user.photoURL,
Telefone: user.phoneNumber
};
$.ajax({
url: '#Url.Action("CadastraUsuarioFacebook", "Home")',
type: "POST",
data: JSON.stringify(SendData),
contentType: 'application/json'
}).always(function (data, status) {
if (status == "success") {
}
});
}
window.location.href = '/Portal/PortalCliente';
}).catch(function (error) {
var errorCode = error.code;
var errorMessage = error.message;
var email = error.email;
var credential = error.credential;
// ...
});
});
If you want to link a Firebase Auth account with an authentication provider such as Facebook, it's required to write code to link the other account with the Firebase account. It doesn't happen automatically.
I'm trying to authenticate to an API via fetch. For that, I'm using an encrypted username and password. The problem is that no matter what I do, the response I get from the API is that my password is invalid. I know the password works because it was provided by my admins.
This is the code I'm using:
import CryptoJS from 'crypto-js';
import CryptoJSAesJson from './helpers/helpers';
var username = 'myusername';
var pass = 'mypassword';
var hash = CryptoJS.SHA1(username).toString();
var password = CryptoJS.AES.encrypt(JSON.stringify(pass), 'mypassphrase', {format: CryptoJSAesJson}).toString();
var credentials = {
user: hash,
password: password
}
fetch("https://demo.mediainfo.com/api/user/login", {
body: JSON.stringify(credentials),
headers: {
"Content-Type": "application/json"
},
method: "POST"
}).then(response => {
// do something with the response
});
On helpers.js I have this code:
var CryptoJSAesJson = {
stringify: function (cipherParams) {
var j = {ct: cipherParams.ciphertext.toString(CryptoJS.enc.Base64)};
if (cipherParams.iv) j.iv = cipherParams.iv.toString();
if (cipherParams.salt) j.s = cipherParams.salt.toString();
return JSON.stringify(j).replace(/\s/g, '');
},
parse: function (jsonStr) {
var j = JSON.parse(jsonStr);
var cipherParams = CryptoJS.lib.CipherParams.create({ciphertext: CryptoJS.enc.Base64.parse(j.ct)});
if (j.iv) cipherParams.iv = CryptoJS.enc.Hex.parse(j.iv);
if (j.s) cipherParams.salt = CryptoJS.enc.Hex.parse(j.s);
return cipherParams;
}
}
export default CryptoJSAesJson;
Unfortunately the API documentation is null so I'm not sure what could be the problem, the only message I get when fetching is: "Wrong password exchange. Please contact administrator."
Thanks!
I need to create an api that sends html emails through amazon SES. I created properly my ses credentials and I want to create an AWS lambda in javascript (nodejs). Due the lack of good AWS documentation for sending an email using javascript, I need to know how to create a lambda that sends an email and responds with a proper message to AWS api gateway.
The following was code written in javascript. Works perfect in AWS lambda and works great when is invoked from AWS Api gateway (no malformed message errors):
var aws = require("aws-sdk");
var ses = new aws.SES({
accessKeyId: "Your SES Access Key",
secretAccesskey: "Your Secret key",
region: "us-east-1" // CHANGE with the region where you configured SES
});
exports.handler = function(event, context, callback) {
var requestPath = JSON.parse(JSON.stringify(event.pathParameters));
var requestBody = JSON.parse(event.body);
var responseBody = {};
var response = {};
if (
requestBody &&
requestBody.emailFrom &&
requestBody.subject &&
requestBody.htmlBody
) {
var emailTo = requestPath.emailto;
var emailFrom = requestBody.emailFrom;
var subject = requestBody.subject;
var htmlBody = requestBody.htmlBody;
} else {
responseBody = {
result: "fail",
resultCode: 400,
description:
"Incorrect Parameters. Mandatory: emailFrom, subject and bodyHTML"
};
response = {
statusCode: 400,
headers: {
"Access-Control-Allow-Origin": "*"
},
body: JSON.stringify(responseBody),
isBase64Encoded: false
};
callback(null, response);
}
var emailParams = {
Destination: {
ToAddresses: [emailTo]
},
Message: {
Body: {
Html: {
Data: htmlBody
}
},
Subject: {
Data: subject
}
},
Source: emailFrom
};
var email = ses.sendEmail(emailParams, function(err, data) {
var resultCode = 200;
if (err) {
var responseBody = {
result: "FAIL",
resultCode: 500,
description: "Error sending email: " + err
};
resultCode = 500;
} else {
var responseBody = {
result: "OK",
resultCode: 200,
description: "Email sent successfully"
};
}
response = {
statusCode: resultCode,
headers: {
"Access-Control-Allow-Origin": "*"
},
body: JSON.stringify(responseBody),
isBase64Encoded: false
};
callback(null, response);
});
};
I am new to javascript any help would be appreciated.
Update
Steps so far:
1.) Created Wixsite and form
2.) Created Mailjet account and registered email address as approved sender
3.) I have my APIkey and my Secret APIkey
4.) I have 2 backend .js files _a.) mailjet.js _b.)email.js
The following code is in my mailjet.js:
import wixFetch from 'wix-fetch'; export function sendWithMailjet(MJ_APIKEY_PUBLIC, MJ_APIKEY_PRIVATE, FromEmail, FromName, Recipients, subject, content) {
var headers = {
"Authorization": "Basic" + btoa(MJ_APIKEY_PUBLIC + ":" + MJ_APIKEY_PRIVATE),
"Content-Type": "application/json"
};
var body = {
"FromEmail": FromEmail,
"FromName": FromName,
"Subject": subject,
"Text-part": content,
"Recipients": [{
"Email": Recipients
}
]
};
return fetch('"https://api.mailjet.com/v3/send', {
method: 'POST',
headers: headers,
body: JSON.stringify(body)
})
.then((res) => {
if (res.status === 200)
return 'Email was sent';
else {
var headersString = '';
res.headers.forEach((value, name) => headersString += `${name}: ${value}\n`);
return res.text()
.then((bodyText) => {
return Promise.reject(new Error('Failed to send email.\n' +
`Status: ${res.status}\n` +
headersString +
bodyText));
})
}
});}
The following code is in my email.js
import {sendWithMailjet} from 'backend/mailjet.js'; export function sendEmail(FromEmail, FromName, Recipients, subject, content) {
const MJ_APIKEY_PUBLIC = 'myapipubliccode'; //mailjet API key
const MJ_APIKEY_PRIVATE = 'myapisecretcode'; //mailjet secret key
FromEmail = 'jparks#jonescarter.com';
FromName = '"James Parks" <jparks#jonescarter.com>';
return sendWithMailjet(MJ_APIKEY_PUBLIC, MJ_APIKEY_PRIVATE, FromEmail, FromName, Recipients, subject, content);
}
On my form page I have the following code:
import {sendEmail} from 'backend/email';
function SendClientEmail() {
const Subject = `New Submission from ${$w("#input3").value}`;
var content = `Name: ${$w("#input1").value}
\rEmail: ${$w("#input3").value}
\rFirstName: ${$w("#input1").value}
\rLastName: ${$w("#input2").value}
\rUserEmail: ${$w("#input3").value}
\rLocation: ${$w("#dropdown1").value}
\rPractice: ${$w("#dropdown2").value}
\rEventName: ${$w("#input4").value}
\rEventDate: ${$w("#datePicker1").value}
\rNeededBy: ${$w("#datePicker2").value}
\rQuantity: ${$w("#input5").value}
\rConfirm: ${$w("#dropdown3").value}
\rComments: ${$w("#textBox1").value}`;
var Recipients = `${$w("#input3").value}`;
//Make sure your from email address is validated in mailjet
sendEmail("FromEmail","FromName","Recipients",Subject, content)
.then(response => console.log(response));}
Resources:
Wix how to send email form submissions - https://support.wix.com/en/article/how-to-send-an-email-on-form-submission
Mailjet for Developers - https://dev.mailjet.com/guides/?java#getting-started
Again, any help would be much appreciated. Thank you!
I am trying to send an email, by using the google api in node.js
var sendmsg = function(auth) {
var to = 'foo#gmail.com',
subject = 'Hello World',
content = 'send a Gmail.'
var email = "To: "+ to +"\r\n"+
"Subject: "+subject+"\r\n"+
content;
var base64EncodedEmail = new Buffer(email).toString('base64');
var gmail = google.gmail('v1');
var request = gmail.users.messages.send({
'userId': auth,
'message': {
'raw': base64EncodedEmail
}
}, function (err, result) {
console.log('result'+result);
});
};
I took this example from the quick start sample in google's documentation, that reads the labels in my email account(which worked fine). And I just changed the scopes to:
var SCOPES = ['https://mail.google.com/',
'https://www.googleapis.com/auth/gmail.modify',
'https://www.googleapis.com/auth/gmail.compose',
'https://www.googleapis.com/auth/gmail.send'];
And created that var = email
var to = 'foo#gmail.com',
subject = 'Hello World',
content = 'send a Gmail.'
var email = "To: "+ to +"\r\n"+
"Subject: "+subject+"\r\n"+
content;
Then I am just trying to use the gmail.users.messages.send method.. But when running the result is returning the following:
<HTML>
<HEAD>
<TITLE>Bad Request</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Bad Request</H1>
<H2>Error 400</H2>
</BODY>
</HTML>
Any idea what I am missing? I think the way I am creating my var 'email' is wrong, but I am not sure how it should be
The value of the userId-field has to be the senders email address (or me for short), the auth-object has to be passed in the auth field, and the message should be passed in the resource-field. Your message lacks a From header and an extra new line before the content to be valid. The message also has to be base64url-encoded:
function sendMessage(auth, from, to, subject, content) {
// The Gmail API requires url safe Base64
// (replace '+' with '-', and '/' with '_')
var encodedEmail = new Buffer(
'From: ' + from + '\r\n' +
'To: ' + to + '\r\n' +
'Subject: ' + subject + '\r\n\r\n' +
content
).toString('base64').replace(/\+/g, '-').replace(/\//g, '_');
var gmail = google.gmail('v1');
var request = gmail.users.messages.send({
auth: auth,
userId: 'me',
resource: {
raw: encodedEmail
}
}, function (err, result) {
console.log('result:', result);
});
};
Instead of constructing the body yourself I'd highly reccomend using Nodemailers system:
const sendMail = async () => {
const mail = await new MailComposer({
to: ...,
from: ...,
subject: ...,
html: ...,
});
const message = await mail.compile().build();
const encodedMessage = message
.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '');
await gmail.users.messages.send({
userId: 'me',
requestBody: { raw: encodedMessage },
});
}