Hi I have a form which the user inputs a message and sends it to multiple recipients. I am using Mandrill as my email client and the script is as follows
function sendMail() {
var email = $("#email").val();
var array = email.split(',');
var name = $("#name").val();
var msg = $("#msg").val();
$.ajax({
type: 'POST',
url: 'https://mandrillapp.com/api/1.0/messages/send.json',
data: {
'key': 'xxxxxxx',
'message': {
'from_email': 'xxx#xxx.com',
'to': [
{
'email': email,
'type': 'to'
}
],
'autotext': 'true',
'subject': 'Hello world ' + name,
'html': msg + '<br> <br> <img src="http://res.cloudinary.com/dzmi0gssmwn/image/upload/v1434831725/wpeqmuld5gzdplf7kzcw.jpg" width:320px;height:auto/>'
}
}
}).done(function(response) {
alert('Your message has been sent. Thank you!'); // show success message
$("#name").val(''); // reset field after successful submission
$("#email").val(''); // reset field after successful submission
$("#msg").val(''); // reset field after successful submission
})
.fail(function(response) {
alert('Error sending message.');
});
}
</script>
When I input one email address the message gets successfully sent and received in the inbox. But when I submit with multiple addresses, I get a response that the message has been sent, but when I looked at the logs it states
[{"email":"xxxx#xxx.xxx, xxxx#xxx.xxx","status":"invalid","_id":"c045cbffbd0c4c5ab5581f5edaff2007","reject_reason":null}]
Does anybody know how to solve this issue or understand whats going wrong ? Thanks for taking the time to read this.
First just use mandrill API through js SDK
<script type="text/javascript" src="mandrill.min.js"></script>
It can be found here.
var m = new mandrill.Mandrill('api key');
function sendTheMail(){
m.messages.send({
"message": {
"from_email": "xx#xx.com",
"from_name": "test",
"to":[{"email": "xx#x.com", "name": "someone's_name"}],
"subject": "subj",
"text": "msg"
}
});
}
Shouldn't you be doing this on server, however, since this will basically show your API to public, and once it's public even for millisecond a bot will have it saved forever.
Related
I'm using this code to add a contact form to my Serverless website (hosted on S3). When an email is successfully sent, the Lambda instance returns the message "Thank you! You can download the sample here: <a href='https://someurl.com'>Download</a>". I want to display that message to the user who submitted the form but I can't figure out how to do so. Currently, my javascript displays a hard-coded message based on the response code from the AWS API Gateway. But I don't want to include the download url in the javascript because I don't want users to be able to see the download without first signing up via the form.
Is there a way to grab the string returned by the Lambda instance and pass it back in the response body and then display that message to the user via javascript?
My current jQuery javascript for the form:
! function($) {
"use strict";
$("form", ".contact-form ").submit(function(t) {
t.preventDefault();
var r = !0,
s = this,
e = $(s).siblings(".contact-form-result"),
o;
// Escape if the honeypot has been filled
if (!!$("#whatname").val()) return;
if ($(s).find(":required").each(function() {
$(this).css("border-color", ""), $.trim($(this).val()) || ($(this).css("border-color", "red"), r = !1);
var t = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
"email" != $(this).attr("type") || t.test($.trim($(this).val())) || ($(this).css("border-color", "red"), r = !1)
}).keyup(function() {
$(this).css("border-color", "")
}).change(function() {
$(this).css("border-color", "")
}), r) {
//var c = $(this).serialize();
var firstname = $("#name-input").val();
var lastname = $("#lastname-input").val();
var mobile = $("#mobile-input").val();
var email = $("#email-input").val();
var message = $("#message-input").val();
var data = {
firstname : firstname,
lastname : lastname,
mobile : mobile,
email : email,
message : message }
$.ajax({
url: "PATH-TO-AMAZON-API",
type: "post",
dataType: "json",
crossDomain: "true",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
beforeSend: function(data) {
$('#submit-mail').attr('disabled', true);
//$('#status').html('<i class="fa fa-refresh fa-spin"></i> Sending Mail...').show();
o = '<p class="form-message form-success">Sending...</p>';
e.removeClass("hidden").html(o)
},
success: function (data) {
// clear form and show a success message
//alert("Successfull");
o = '<p class="form-message form-success">Thank you for your message!</p>';
e.removeClass("hidden").html(o)
$(s)[0].reset();
setTimeout(function() {
e.addClass("hidden").html("")
}, 5e3);
$('#submit-mail').removeProp('disabled');
},
error: function (jqXHR, textStatus, errorThrown) {
// show an error message
//alert("UnSuccessfull");
o = '<p class="form-message form-error">Sorry, there was an error. Please try again later.</p>';
e.removeClass("hidden").html(o)
setTimeout(function() {
e.addClass("hidden").html("")
}, 5e3);
$('#submit-mail').removeProp('disabled');
}
});
}
})
}(jQuery);
And my Python Lambda function (using an API, SES and Dynamo [not currently using Dynamo]):
import boto3
from botocore.exceptions import ClientError
import json
import os
import time
import uuid
import decimal
client = boto3.client('ses')
sender = os.environ['SENDER_EMAIL']
subject = os.environ['EMAIL_SUBJECT']
configset = os.environ['CONFIG_SET']
charset = 'UTF-8'
dynamodb = boto3.resource('dynamodb')
recipient = 'example#email.com'
def sendMail(event, context):
print(event)
#Send mail for contact form
try:
data = event['body']
content = 'Message from ' + data['firstname'] + ' ' + data['lastname'] + ',<br>Phone: ' + data['mobile'] + ',<br>Message Contents: ' + data['message']
#saveToDynamoDB(data)
response = sendMailToUser(data, content)
except ClientError as e:
print(e.response['Error']['Message'])
else:
print("Email sent! Message Id:"),
print(response['MessageId'])
return "Thank you! You can download the sample here: <a href='https://someurl.com'>Download</a>"
def list(event, context):
table = dynamodb.Table(os.environ['DYNAMODB_TABLE'])
# fetch all records from database
result = table.scan()
#return response
return {
"statusCode": 200,
"body": result['Items']
}
def saveToDynamoDB(data):
timestamp = int(time.time() * 1000)
# Insert details into DynamoDB Table
table = dynamodb.Table(os.environ['DYNAMODB_TABLE'])
item = {
'id': str(uuid.uuid1()),
'firstname': data['firstname'],
'lastname': data['lastname'],
'email': data['email'],
'message': data['message'],
'createdAt': timestamp,
'updatedAt': timestamp
}
table.put_item(Item=item)
return
def sendMailToUser(data, content):
# Send Email using SES
return client.send_email(
Source=sender,
ReplyToAddresses=[ data['email'] ],
Destination={
'ToAddresses': [
recipient,
],
},
Message={
'Subject': {
'Charset': charset,
'Data': subject
},
'Body': {
'Html': {
'Charset': charset,
'Data': content
},
'Text': {
'Charset': charset,
'Data': content
}
}
}
)
Thanks for your help!
Well, that was easy...after all the searching online for days trying to figure this out. Turns out the message is right there in success: function (data) so I all I have to do is return the data variable in my javascript. So it would look like this:
success: function (data) {
// clear form and show a success message
//alert("Successfull");
o = '<p class="form-message form-success">' + data + '</p>';
e.removeClass("hidden").html(o)
$(s)[0].reset();
setTimeout(function() {
e.addClass("hidden").html("")
}, 5e3);
$('#submit-mail').removeProp('disabled');
},
I am getting these errors when trying to use Facebook Login for the Web with the JavaScript SDK to store the user data into the database.
Undefined property: stdClass::$gender in /home/domain/public_html/loguser/facebook.php on line 30
Undefined property: stdClass::$locale in /home/domain/public_html/loguser/facebook.php on line 31
Undefined property: stdClass::$link in /home/domain/public_html/loguser/facebook.php on line 33
Apparently on Browser I am getting Gender : undefined message for one test login so in case like this thata a user may not specified his/her Gender, Locale or link how can I prevent this error on PHP side?
function verify_user() {
FB.api('/me', {locale: 'en_US', fields: 'id, name, first_name, last_name,email, link, gender,locale, picture'},
function (response) {
$.ajax({
url: "facebook.php",
data: {userinfo : JSON.stringify(response)},
type: "POST",
success: function(resp) {
//Your cutom code after successful login
}
});
});
}
and on facebook.php I have
$qry_body = " `oauth_provider` = 'facebook',
`oauth_id` = '".$userInfo->id."',
`name` = '".$userInfo->name."',
`first_name` = '".$userInfo->first_name."',
`last_name` = '".$userInfo->last_name."',
`email` = '".$userInfo->email."',
`gender` = '".$userInfo->gender."',
`locale` = '".$userInfo->locale."',
`picture` = '".$userInfo->picture->data->url."',
`link` = '".$userInfo->link."',
`modified` = '".date("Y-m-d H:i:s")."' ";
We're trying to have the modal-body div below included in the email sent by Mandrill. Or set it up as a variable. Does anyone know how we could do this in a simple manner using the same setup we have now for the other included variables in the email? Thanks so much!
eventClick: function(event) {
console.log(event)
// alert(event.start.format('MMMM Do YYYY'))
var start = event.start.format('MMMM Do YYYY'),
end = event.end.format('MMMM Do YYYY'),
html = '<p>Starts: ' + start + '<p>';
html += '<p>Ends: ' + end + '<p>';
var modal = $("#modal");
modal.find(".modal-title").html(event.title);
modal.find('.modal-body').html(html)
modal.modal();
}
});
});
});//]]>
jQuery(function($)
{
$("#contact_form").submit(function()
{
var email = $("#email").val(); // get email field value
var name = $("#name").val(); // get name field value
var msg = $("#msg").val(); // get message field value
$.ajax(
{
type: "POST",
url: "https://mandrillapp.com/api/1.0/messages/send.json",
data: {
'key': 'API',
'message': {
'from_email': "email#email.com",
'from_name': "name",
'headers': {
'Reply-To': "email#email.com"
},
'subject': 'Confirmation - Sign Up',
RIGHT HERE--->'text': ,
'to': [
{
'email': email,
'name': name,
'type': 'to'
}]
}
}
})
.done(function(response) {
alert('You have been signed up. Thank you!'); // show success message
$("#name").val(''); // reset field after successful submission
$("#email").val(''); // reset field after successful submission
$("#msg").val(''); // reset field after successful submission
})
HTML:
I am not a JSON specialist and therefore I need help to solve a little problem.
When submitting a form, before the form closes, it returns 'Unexpected end of input'.
I have searched the Internet and this forum, I found nothing solving the problem. I hope you'll be able to help me sort it out.
So, to make it easier for you, what's going on?
The user requests a listing. He fills the form with a message and a price. The item_id is transmitted directly (and working as I get it working so far).
The form data are sent via JSON to a remote server (VPS) which un-json the data. However, in addition to the 'unexpected end of input', I got on my remote server 'Server response: 400 (Bad Request)'
I am almost sure it is due to this code and not the remote server one.
I have identified thanks to debug that the error is at the line :
JSON.parse(data);
$('#requestListingSubmit').click(function (evt) {
evt.preventDefault();
rL_form.hide();
rL_load.show();
rL_controls.hide();
rL_alert.empty();
var item_id = $(this).data('item-id');
var route = '/request';
$.ajax(
{
type: 'POST',
url: coreURL + route,
data:
{
'item_id': item_id,
'message': $('#message').val(),
'price': $('#price').val(),
},
success: function (data)
{
try
{
JSON.parse(data);
window.location = coreURL+'/account/listings?new';
}
catch(e)
{
rL_load.hide();
rL_form.show();
rL_controls.show();
rL_alert.alert(
{
type: 'danger',
message: 'Error: '+e.message
});
}
},
error: function (jqXHR, status, httperror) {
rL_load.hide();
rL_form.show();
rL_controls.show();
rL_alert.alert({
type: 'danger',
message: (jqXHR.responseJSON.message || httperror)
});
}
});
});
Thank you very much guys!
How can I get the names of the Facebook friends of the user?
I send requests to using FB.ui({ method: 'apprequests'?
Here is my code:
<input id="btSelectFriends" type="button" value="Select Friends" onclick="javascript:FBUISelectFriends()" />
<div id="fb-root"></div>
<script type="text/javascript" src="https://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
function FBUISelectFriends()
{
var selectedFriendsRequest_ids;
FB.ui({ method: 'apprequests', message: 'Select friends', data: 'tracking information for the user', tite: 'Select friends' },
function (response) {
if (!response || !response.request_ids) { alert('Request could not be sent'); return; }
selectedFriendsRequest_ids = response.request_ids;
for (var i = 0; i < selectedFriendsRequest_ids.length; i++) {
FB.api('/me/apprequests/?request_ids=' + selectedFriendsRequest_ids[i].toString(),
function (response) {
if (!response || response.error) { alert('Friends Selection error occured'); return; }
}
)
FB.api(selectedFriendsRequest_ids[0],
function (response)
{
alert(response.name);
}
);
}
}
);
return;
}
</script>
I tried this code but it didn't work:
FB.api(selectedFriendsRequest_ids[0], function (response) {console.log(response.name);});
Can you please help?
Thanks.
Just change this in your function
function FBUISelectFriends()
{
FB.ui(
{
method: 'apprequests',
redirect_uri: 'YOUR APP URL',
message: "Tom sent you a request"
},
function(response) {
if(response && response.hasOwnProperty('to')) {
for(i = 0; i < response.to.length; i++) {
//alert( response.to[i]);
// response.to[i] gives the selected facebook friends ID
// To get name of selected friends call this function below
getfbnames(response.to[i]);
}
}
}
);
}
function getfbnames(selectedfrndid)
{
var url = 'getfriendfbname.php'; // call a php file through URL and jquery ajax
$.ajax({
type:'POST',
url: url,
data : { fbid : selectedfrndid },
async: false,
success: function(data)
{
alert(data);
}
}); // end of ajax
}
A file getfriendfbname.php which returns the name of facebook friend name using friend facebook id in php
$fbid=$_POST['fbid'];
$json = file_get_contents('https://graph.facebook.com/'.$fbid);
$data = json_decode($json);
echo $data->name;
return $data->name;
Since 30 Sept. Facebook released a Requests 2.0 implementation of their system, which is a LOT more useful than the old one.
Here's why :
With the old one, your user first sent requests, Facebook returned to you the request_ids, then you had to verify who you sent the requests to...
With the new one, for each group of requests (like when a user sends multiple requests using multi-friend-selector) Facebook returns you one request id (parameter : response.request) and a parameter with all Facebook user ids requests were sent to (parameter : response.to)
You just have to activate Requests 2.0 in your app dashboard, then just change the conditions in your Javascript callback.
There's requests to retrieve information about your user's friends FB.api('/me/friends?fields=id,name,first_name,last_name and you just have to parse the result of this request with the Facebook user ids you sent requests to !
Everything is explained here about Requests 2.0 : http://developers.facebook.com/blog/post/569/