Sendgrid node js not sending email. Program has no error messages - javascript

I am trying to set up an email contact page on my heroku website using sendgrid. I have tried the code with the helper mailer and the one without; however, both do are not able to send an email to my email address. I added my sendgrid API key as a variable in my heroku app settings and also imported the username and password.
My email process starts when the user click on a button. I have an action to a post route within the form element, and I use body parser to retrieve the input values from the user (message, their email address, and their message). Within my post route, I call a function in my email.js file that wraps the code from sendgrid.
//My html using handlebars.
<div class = "mainDiv" id = "sectionAbout">
<h1 class="mainDivH1" id = "AboutMe">{{ ContactLi }}</h1>
<form action="/email" method="POST">
<label for="fullName">{{ formName }}</label> <br><br>
<input type="text" name="fullName">
<br>
<br>
<label for="subject">{{ formSubject }}</label> <br><br>
<input type="text" name="subject">
<br>
<br>
<label for="email">{{ formEmail }}</label> <br><br>
<input type="text" name="email">
<br>
<br>
<label for="message">{{ formMessage }}</label> <br><br>
<textarea rows="15" cols="80" type="text" name="message id="textbox"></textarea>
<br>
<br>
<button id="but" type="submit">Submit</button>
</form>
</div>
//The code for the POST route
var email = require('../mail/email');
router.post('/email', function(req, res){
var name = req.body.fullName;
var emSubject = req.body.subject;
var senderMail = req.body.email;
var message = name + " " + req.body.message;
var myEmail = 'examplee#yahoo.com';
email.send(emSubject, senderMail, message, function(){
res.redirect('/contact');
});
});
//email.js
var helper = require('sendgrid').mail
var sg = require('sendgrid')(process.env.SENDGRID_API_KEY);
var email = {
send: function(emSubject, senderMail, message, callback){
var from_email = new helper.Email(senderMail);
var to_email = new helper.Email('helper#yahoo.com');
var subject = emSubject;
var content = new helper.Content("text/plain", message);
var mail = new helper.Mail(from_email, subject, to_email, content);
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON()
});
console.dir("request");
console.dir(JSON.stringify(request, null, 4));
sg.API(request, function(error, response) {
if(error){
console.log(error);
}
console.log(response.statusCode)
console.log(response.body)
console.log(response.headers)
callback(error);
});
}
}
module.exports = email;

You mentioned that you added your Sendgrid API key as an env var, and imported your username and password. You should not have to do any of that. Just add the Sendgrid add-on to your Heroku account as follows:
heroku addons:create sendgrid:starter

Related

How to redirect users based on their email addresses to a specific dynamic profile page?

I'm making a social Media Website I have added Firebase Authorization in it by now. I want to redirect Users to there profile page based on their email address that they entered, but I don't know much about JavaScript and don't want to use PHP. I want to make it Using HTML, JavaScript and Firebase only. Profile page contains their profile photo and name linked with their Google account. There will be only one profile page that manages all the users
Here's my code
firebase.initializeApp(firebaseConfig);
const auth = firebase.auth();
function SignUp() {
var firstname = document.getElementById("fname");
var lastname = document.getElementById("lname");
var username = document.getElementById("username");
var email = document.getElementById("email");
var passoword = document.getElementById("password");
const promise = auth.createUserwithEmailAndPassword(username.value, email.nodeValue, password.value);
promise.catch(e => alert(e.message));
alert("Signed Up");
}
function SignIn() {
var username = document.getElementById("username");
var email = document.getElementById("email");
var passoword = document.getElementById("password");
const promise = auth.signInwithEmailAndPassword(email.Value, password.value);
promise.catch(e => alert(e.message));
alert("Signed In" + email.value, "as" + username.value);
}
function SignOut() {
auth.signOut();
alert("Signed Out")
}
auth.onAuthStateChanged(function(user) {
if (user) {
var email = user.email
alert("Active user " + email)
//is signed in
} else {
alert("No Active User")
//no user is signed in
}
})
<div id="formContainer">
<br><input type="email" name="Email" id="email" size="25px" placeholder="Email Address">
<br><input type="password" name="Password" id="password" size="25px" placeholder="Password">
<br><input type="submit" name="submit" value="Sign Up!" onclick="signUp()">
<br><input type="submit" name="submit" value="Sign In!" onclick="signIn()">
<br><input type="submit" name="submit" value="Sign Out!" onclick="signOut()">
</div>

2CheckOut - TwoCheckoutException: Bad request - parameter error

So basically i am trying to implement 2checkout in my website and i have done everything from documentation but i get this error: TwoCheckoutException: Bad request - parameter error. I tried checking and playing with private/public keys and id but when i change them it says "authoization error" so i am sure they are okay. I read about addresses and everything and i have changed them but still not working.
Here is my full code:
#{
ViewData["Title"] = "Test";
}
<script type="text/javascript" src="https://www.2checkout.com/checkout/api/2co.min.js"></script>
<h2>Test</h2>
<form id="myCCForm" action="/Home/SubmitCard" method="post">
<input name="token" type="hidden" value="" />
<div>
<label>
<span>Card Number</span>
<input id="ccNo" type="text" value="" autocomplete="off" required />
</label>
</div>
<div>
<label>
<span>Expiration Date (MM/YYYY)</span>
<input id="expMonth" type="text" size="2" required />
</label>
<span> / </span>
<input id="expYear" type="text" size="4" required />
</div>
<div>
<label>
<span>CVC</span>
<input id="cvv" type="text" value="" autocomplete="off" required />
</label>
</div>
<input type="submit" value="Submit Payment" />
</form>
<script type="text/javascript">
// Called when token created successfully.
var successCallback = function (data) {
var myForm = document.getElementById('myCCForm');
// Set the token as the value for the token input
myForm.token.value = data.response.token.token;
// IMPORTANT: Here we call `submit()` on the form element directly instead of using jQuery to prevent and infinite token request loop.
myForm.submit();
};
// Called when token creation fails.
var errorCallback = function (data) {
if (data.errorCode === 200) {
alert("Error 200");
// This error code indicates that the ajax call failed. We recommend that you retry the token request.
} else {
alert(data.errorMsg);
}
};
var tokenRequest = function () {
// Setup token request arguments
var args = {
sellerId: "901417674",
publishableKey: "309FC596-8380-4B6F-B269-3E157A5A5D0B",
ccNo: $("#ccNo").val(),
cvv: $("#cvv").val(),
expMonth: $("#expMonth").val(),
expYear: $("#expYear").val()
};
// Make the token request
TCO.requestToken(successCallback, errorCallback, args);
};
$(function () {
// Pull in the public encryption key for our environment
TCO.loadPubKey('sandbox');
$("#myCCForm").submit(function (e) {
// Call our token request function
tokenRequest();
// Prevent form from submitting
return false;
});
});
</script>
and here is server side code:
public IActionResult SubmitCard()
{
TwoCheckout.TwoCheckoutConfig.SellerID = "901417674";
TwoCheckout.TwoCheckoutConfig.PrivateKey = "4E704021-B233-435F-A904-47B2620B9E66";
TwoCheckout.TwoCheckoutConfig.Sandbox = true;
try
{
TwoCheckout.AuthBillingAddress Billing = new TwoCheckout.AuthBillingAddress();
Billing.addrLine1 = "123 Main Street";
Billing.city = "Townsville";
Billing.zipCode = "43206";
Billing.state = "Ohio ";
Billing.country = "USA";
Billing.name = "Joe Flagster";
Billing.email = "Ex#a.com";
Billing.phoneNumber = "065";
TwoCheckout.ChargeAuthorizeServiceOptions Customer = new TwoCheckout.ChargeAuthorizeServiceOptions();
Customer.total = 1;
Customer.currency = "USD";
Customer.merchantOrderId = "12";
Customer.billingAddr = Billing;
Customer.token = Request.Form["token"];
TwoCheckout.ChargeService Charge = new TwoCheckout.ChargeService();
var result = Charge.Authorize(Customer);
return View("Success", result);
}
catch(TwoCheckout.TwoCheckoutException ex)
{
return View("Error", ex.ToString());
}
}
and here is all info from my sandbox:
You may need to update your site settings for sandbox from Site Management -> Site Settings and Turn to On for Demo Settings and check again
May it helps you

Access Denied when trying to do Browser-Based Upload using HTTP POST (Using AWS Signature Version 4)

I am using these resources to try and get this working:
This question.
The official Amazon HTTP POST example.
The Amazon HTTP POST documentation.
I am trying to upload a file to my s3 bucket by signing a form. I have cut down my form and policy to only the most basic required options as per the documentation and I still get "AccessDenied". Currently dates are hard-coded for simplicity.
Code in my ExpressJS Router
var accessKeyID = credentials.accessKeyId;
var secretAccessKey = credentials.secretAccessKey;
var bucket = 'images.mybucket.com';
var region = 'us-east-1';
var expiration = '2016-11-28T12:00:00.000Z';
var date = '20161108';
var serviceName = 's3';
var credentialUrl = accessKeyID + '/' + date + '/' + region + '/' + serviceName + '/aws4_request';
var amazonDate = '20161108T000000Z';
var s3Policy = {
'expiration': expiration,
'conditions': [
{'bucket': bucket},
['starts-with', '$key', 'UserUploads/'],
{'acl': 'public-read'},
{'x-amz-server-side-encryption': 'AES256'},
{'x-amz-credential': credentialUrl},
{'x-amz-algorithm': 'AWS4-HMAC-SHA256'},
{'x-amz-date': amazonDate}
]
};
var base64Policy = new Buffer(JSON.stringify(s3Policy), 'utf-8').toString('base64');
var signatureKey = getSignatureKey(secretAccessKey, date, region, serviceName);
var s3Signature = CryptoJS.HmacSHA256(base64Policy, signatureKey).toString(CryptoJS.enc.Hex);
function getSignatureKey(key, dateStamp, regionName, serviceName) {
var kDate = CryptoJS.HmacSHA256(dateStamp, 'AWS4' + key);
var kRegion = CryptoJS.HmacSHA256(regionName, kDate);
var kService = CryptoJS.HmacSHA256(serviceName, kRegion);
var kSigning = CryptoJS.HmacSHA256('aws4_request', kService);
return kSigning;
}
HTML
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<form action="http://images.mybucket.com.s3.amazonaws.com/" method="post" enctype="multipart/form-data">
<p>key to upload</p>
<input type="input" name="key" value="UserUploads/${filename}">
<input type="hidden" name="acl" value="public-read">
<input type="hidden" name="x-amz-server-side-encryption" value="AES256">
<input type="text" name="X-Amz-Credential" value="REDACTED-access-key-id/20161108/us-east-1/s3/aws4_request">
<input type="text" name="X-Amz-Algorithm" value="AWS4-HMAC-SHA256">
<input type="text" name="X-Amz-Date" value="20161108T000000Z">
<p>tags for file</p>
<input type="hidden" name="Policy" value="REDACTED-base64-encoded-policy">
<input type="hidden" name="X-Amz-Signature" value="REDACTED-signature">
<p>file</p>
<input type="file" name="file"><input type="submit" value="Upload File to S3">
</form>
The permission s3:PutObjectAcl is required because in your bucket policy, you're setting the acl via "acl": "public-read".

Information not being recorded in Parse

I am working with Parse for Javascript, and below is my dilema:
During the signup process, along with the username, and password, the first and last name of the user would have to recorded into parse. As of now, only the username and password is stored.
Below is the javascript signup function code:
SignUp: function(e) {
var self = this;
var username = this.$("#signup-username").val();
var password = this.$("#signup-password").val();
var first_name = this.$("#fname").val();
var last_name = this.$("#lname").val();
Parse.User.signUp(username, password, { ACL: new Parse.ACL() }, {
success: function(user) {
user.set("first_name", first_name);
user.set("last_name", last_name);
new ManageTodosView();
self.undelegateEvents();
delete self;
},
Below is the html form code (ask user to enter their information):
<form class="signup-form">
<h2>Sign Up</h2>
<div class="error" style="display:none"></div>
<input type="text" id="fname" placeholder="Please enter your First Name" />
<input type="text" id="lname" placeholder="Please enter your Last Name" />
<input type="email" id="signup-username" placeholder="Please enter your email" />
<input type="password" id="signup-password" placeholder="Create a Password" />
<button>Sign Up</button>
</form>
Any help would be greatly appreciated.
User.set won't save the changes you will need to call save once you set the first name and last name. Also you don't need to do this after calling signing up. Try the code below it should work.
SignUp: function(e) {
var self = this;
var username = this.$("#signup-username").val();
var password = this.$("#signup-password").val();
var first_name = this.$("#fname").val();
var last_name = this.$("#lname").val();
var user = new Parse.User();
user.set("username", username);
user.set("password", password);
user.set("first_name", first_name);
user.set("last_name", last_name);
user.signUp(null, {
success: function(user) {
new ManageTodosView();
self.undelegateEvents();
delete self;
}
}

Send image using Javascript/Ajax and save it to MongoDB

I am trying to save a profile using Ajax to sent the data. I can save when I dont have image, but the problem is that the profile has an image and I would like to send it using the same Ajax function I am using to send the other information. If I don't do this, I have to create a different another Ajax function with 'PUT' request just to modify the document and save the image in it.
Is there some way to send image as Json along with the the other info such as name and email?
This is my HTML:
<input class="teamName" type="text" id="teamName" name="teamName" size="25" maxlength="60" value="Team Name">
<input class="companyName" type="text" id="companyName" name="companyName" size="25" maxlength= "60" value="Company Name">
<input class="teamDescription" type="text" id="teamDescription" name="teamDescription" size="25" maxlength= "60" value="Team Description">
<input class= "email" type="text" id="email" name="email" size="25" maxlength= "60" value="emails">
<input class="charityID" type="text" id="charityID" name="charityID" size ="25" maxlength="60">
<input class="upload-area" id="upload-area" type="file" size="150">
This is my function and I call using the 'greenButton' onclick method:
function createTeam(){
var _teamName= document.getElementById("teamName").value;
var _companyName =document.getElementById("companyName").value; //maybe not, tae it off.
var _charityID = document.getElementById("charityID").value;
var _teamDescription = document.getElementById("teamDescription").value;
var _profileImage = document.getElementById("upload-area").value; //PATH of the Image
if((_teamName.trim() === "") || (_companyName.trim() === "") || (_charityID.trim() === ""))
{
alert("You did not fill the team Name or companyName or Charity, Please enter with a name");
}else{
var sessionID = $.cookie("sessionID")
$.ajax({
type: "POST",
url: "http://xxx.xxx.x.xx:8085/team/?sessionID="+sessionID,
dataType:'json',
data:{
teamName: _teamName,
companyName:_companyName,
teamDescription:_teamDescription,
charityID:_charityID,
profileImage:_profileImage **//CAN I DO THIS, SEND AS JSON?**
},
success: function(msg) {
$.cookie("teamID",msg.teamID)
$.cookie("sessionID",sessionID)
alert("team supposedly saved")
}
});
}
}
And this is how I receive data in my NodeJs to save on my DataBase:
router.post('/', function (req, res){
//TEAM INFO
var sessionID = req.query.sessionID // to get variable form URL is "req.query"
var team = req.body;
var teamName = team.teamName;
var teamDescription = team.teamDescription;
var charityID = team.charityID;
var teamLink = team.teamLink;
var image = team.profileImage;
sessionOBJ.isAuthorized(sessionID, function(sessionID){
log.d("Checking session to save team", sessionID);
var adminID = sessionID.userID;
var newTeam = new teamModel({
teamName: teamName,
teamDescription: teamDescription,
teamAdminID: adminID,
teamLink: teamLink,
charityID: charityID,
image: {
data:fs.readFileSync(image),
contentType:image.type
}
});
newTeam.save(function(err, team){
if(err) return console.error(err);
res.send({"status" : "Created", "teamID" : team._id, "teamAdminID":team.teamAdminID });
log.d("Created Team ID", team._id)
log.d("XXXXXXX XXXXXX XXXXXXX Team Saved inside save method",team);
});//end save new team
});//end is Authorized
});
The code above is not working.
How can I send the image file using javascript and Ajax? Can I do this using the same Ajax request?
Thanks in advance.

Categories