How to send contact email with node js and mailgun? - javascript

new to node js and mail gun. I am trying to send a 'contact us' email from a website that is using the following for my send button (on my index.html page).
<!-- START CONTACT SECTION -->
<section class="section-contact" id="contacts">
<div class="container">
<!-- START SECTION HEADER -->
<h2 class="reveal reveal-top">Contact Us</h2>
<div class="subheading reveal reveal-top">
Hit us up. Let us know how we can make things better ( <b>Support#mail.com </b>).
</div>
<!-- END SECTION HEADER -->
<div class="contact-form-wrapper reveal reveal-bottom">
<!-- START CONTACT FORM -->
<!-- <form method="POST" action="./scripts/writeus.php" accept-charset="UTF-8" class="contact-form" id="jvalidate" novalidate="novalidate"> -->
<form method="POST" action="./scripts/mailgun.php" accept-charset="UTF-8" class="contact-form" id="jvalidate" novalidate="novalidate">
<!-- <form method="POST" action="send_mailgun($email)" accept-charset="UTF-8" class="contact-form" id="jvalidate" novalidate="novalidate"> -->
<div class="row">
<div class="col-sm-12 col-md-4">
<div class="field-holder">
<input class="form-control input-lg field" placeholder="John Snow" name="name" type="text">
</div>
</div>
<div class="col-sm-12 col-md-4">
<div class="field-holder">
<input class="form-control input-lg field" placeholder="myReplyEmail#Address.com" name="email" type="email">
</div>
</div>
<div class="col-sm-12 col-md-4">
<div class="field-holder">
<input class="form-control input-lg field" placeholder="Subject" name="website" type="text">
</div>
</div>
<div class="col-md-12 col-xs-12">
<div class="field-holder">
<textarea class="form-control" placeholder="Some text" name="message" cols="50" rows="10"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<div class="alert alert-success" role="alert" style="display: none;">
Message has been successfully sent.
</div>
<div class="alert alert-danger" role="alert" style="display: none;">
<div class="alert-text">Server error</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<button class="btn btn-primary btn-contact" type="submit" value="SEND MESSAGE">SEND MESSAGE</button>
</div>
</div>
</form>
<!-- END CONTACT FORM -->
</div>
</div>
</section>
<!-- END CONTACT SECTION -->
I have Node.js with Express and mailgun installed and working on my local machine with the snippet bellow hard coded as a test in my server.js
var Mailgun = require('mailgun').Mailgun;
var mg = new Mailgun('some-api-key');
mg.sendText('example#example.com', 'Recipient 1 <rec1#example.com>',
'This is the subject',
'This is the text',
'noreply#example.com', {},
function(err) {
if (err) console.log('Oh noes: ' + err);
else console.log('Success');
});
How do I get the button info and send from my index.html ?
Thanks for the help. Much appreciated.

You need create web server to receive submit from your form or ajax call. Look this: http://expressjs.com/
example:
var express = require('express');
var Mailgun = require('mailgun').Mailgun;
var app = express();
app.post('/sendMail', function (req, res) {
/*use body-parser (https://github.com/expressjs/body-parser) for parameters */
var mg = new Mailgun('some-api-key');
mg.sendText('example#example.com', 'Recipient 1 <rec1#example.com>',
'This is the subject',
'This is the text',
'noreply#example.com', {},
function(err) {
if (err) {
console.log('Oh noes: ' + err);
res.send('Error occurred');
}
res.send('Email sent');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});

Related

Send email from HTML page using JS

I'm trying to send a mail from a html page using the below:
<script>
function sendMail() {
var link = "mailto:email#live.co.uk &subject=" + encodeURIComponent(document.getElementById('myText').value)
+ "&body=" + encodeURIComponent(document.getElementById('myText2').value)
;
window.location.href = link;
}
</script>
<!-- Contact Form -->
<div class="col-md-6 contact">
<form role="form">
<!-- Name -->
<div class="row">
<div class="col-md-6">
<!-- E-Mail -->
<div class="form-group">
<input type="text" class="form-control" placeholder="Your name" id="myText">
</div>
</div>
<div class="col-md-6">
<!-- Phone Number -->
<div class="form-group">
<input type="email" class="form-control" placeholder="Email address">
</div>
</div>
</div>
<!-- Message Area -->
<div class="form-group">
<textarea class="form-control" placeholder="Write you message here..." style="height:232px;" id="myText2"></textarea>
</div>
<!-- Subtmit Button -->
<button type="submit" class="btn btn-send" onclick="sendMail(); return false">
Send message
</button>
</form>
</div>
When I press button to click all of the data ends up in the default mail apps "To:" Text input area. Can anyone tell me how to split out the subject and body correctly?? I'd like these to go into the subject and body sections of the email by default.
Your query string variables should start with "?", not "&".
var link = "mailto:email#live.co.uk?subject=" + encodeURIComponent(document.getElementById('myText').value)
+ "&body=" + encodeURIComponent(document.getElementById('myText2').value)
;

Contact form not parsing all fields

I have created a contact form for users to email through a web app. The fields on the form are Name, Company, Contact Number and Message. When I tested the app the email sends but it only sends the data from the message input and the remain blank.
app.js file
let mailOptions = {
from: '"Nodemailer Contact" <**********>', // sender address
to: '*************', // list of receivers
subject: 'TW Contact Request', // Subject line
Name: req.body.Name,
Company: req.body.Company,
Phone: req.body.Phone,
message: req.body.Body, // plain text body
html: req.body.body // html body
};
index.ejs file
<form action="/send-email" method="post">
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
<label for="Name">Name:</label>
<input type="text" class="form-control" name="Name">
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
<label for="Company">Company:</label>
<input type="text" class="form-control" name="Company">
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
<label for="Phone">Contact Number:</label>
<input type="text" class="form-control" name="Phone">
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
<label for="body">Message:</label>
<textarea cols="5" rows="5"class="form-control" name="body"></textarea>
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
<button type="submit" class="btn btn-success">Send</button>
</div>
</div>
</form>
I cant see why it is not pulling all the data.
Please use following code for getting request data
var express = require("express");
var myParser = require("body-parser");
var app = express();
app.use(myParser.urlencoded({extended : true}));

Unable to post record using vue and laravel backend

When i try to submit a record to my SQL from vue component with laravel API nothing happens. I have compared my code to other working code but nothing seem to work.
Here is my register method:
register() {
axios
.post('/api/register', this.user)
.then(res => {
console.log(user)
})
.catch(err => {
console.log(err.message)
})
},
Here is the register form:
<template>
<form>
<div class="form-group">
<input
type="text"
v-model="user.name"
name="username"
class="form-control"
id="name"
placeholder="Email or username"
/>
<div class="validation"></div>
</div>
<div class="form-group">
<input
v-model="user.email"
type="email"
class="form-control"
name="email"
id="password"
placeholder="Your Email"
/>
<div class="validation"></div>
</div>
<div class="form-group">
<input
v-model="user.password"
type="password"
class="form-control"
name="password"
placeholder="Your Password"
data-rule="password"
/>
<div class="validation"></div>
</div>
<div id="errormessage"></div>
<div class="text-center">
<button type="submit" title="Register" v-on:click="register">Login</button>
</div>
</form>
</template>
My laravel page:
<section id="pricing" class="wow fadeInUp section-bg">
<div class="container">
<header class="section-header">
<h3>Register</h3>
<p>Come prepared!!</p>
</header>
<div class="row flex-items-xs-middle flex-items-xs-center">
<div class="col-xs-12 col-lg-6">
<div class="card">
<div class="card-header">
<div id="app">
<register></register>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
Here is my controller:
if ($v->fails())
{
return response()->json([
'status' => 'error',
'errors' => $v->errors()
], 422);
}
$user = new User;
$user->name = $request->name;
$user->email = $request->email;
$user->password = Hash::make($request->password);
$user->save();
return response()->json(['status' => 'success'], 200);
}
The record should post successfully, however nothing happens. I only see the parameters on my url like so, and I don't get any error on console.
You'll need to prevent the default form submission behavior first, then trigger your own register method.
<form #submit.prevent="register">

Displaying Javascript response object in MODAL

I have created a view as:
<div class="container" style="padding-top:20px">
<div class="row">
#foreach (var item in Model)
{
<div class="col-lg-4" style="padding-top:20px;">
<div class="card" style="width:18rem">
<img src="#Url.Content(item.ImagePath)" class="card-img-top" />
<div class="card-body">
<div class="row">
<h5 class="card-title">#item.ProductName</h5>
<p style="color:crimson">  ( Rs #item.ProductPrice )</p>
</div>
#*Details*#
<button class="btn btn-primary btndetails" data-product-id="#item.Id" #*data-target="#loginModal" data-toggle="modal"*#>Details</button>
</div>
</div>
</div>
}
</div>
when I click the Details button the JavaScript function is invoked in which I am making an ajax call to Admin controller and GetProduct actionMethod which takes an Id, Gets the data with that id and returns a JSON object:
<script>
$(document).ready(function () {
$(".btndetails").on("click", function () {
$.ajax({
method: "POST",
url: "/Admin/GetProduct/" + $(this).attr("data-product-id"),
success: function (response) {
}
});
});
});
</script>
Its all working correct until here, I get the object in success function response object but now I want to display that object in a MODAL that I have created as:
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="modal fade" data-backdrop="static" id="loginModal" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title"> Details</h4>
<button class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
#using (Html.BeginForm())
{
}
</div>
<div class="modal-footer">
<button class="btn btn-success">Save</button>
<button class="btn btn-primary" data-dismiss="modal">Close</button>
<button class="btn btn-danger">Delete</button>
</div>
</div>
</div>
</div>
</div>
So in short I want to display the object I received in JavaScript Response object in MODAL I created.
Wait it looks like you are trying to use ASP.Net rendering engine (which is generated during request on SERVER side) to render a result of an AJAX request which is performed by the client.
Sorry friend but that's just not going to work.
I mean if you really have to use ASP.Net to render that form, I'd suggest creating a separate view which just returns the form (Html.BeginForm()) section, then use jquery to paste that into the modal-body class as a raw html.
$('.modal-body').html(response);
It'd be a really bad solution from a MVC point of view and I'd advise against that, but it'd get the job done.
I am succesful in woring out the solution as :
I used getElementById and value functions to get the MODAL input field and then used value function to set the values in response object to MODAL input fields.
My AJAX Call is :
$(".btndetails").on("click", function () {
$.ajax({
method: "POST",
url: "/Admin/GetProduct/" + $(this).attr("data-product-id"),
success: function (response) {
var pName = document.getElementById("pName");
pName.value = response.ProductName;
var pPrice = document.getElementById("pPrice");
pPrice.value = response.ProductPrice;
var pDPrice = document.getElementById("pDPrice");
pDPrice.value = response.DiscountPrice;
var imgTitle = document.getElementById("imgTitle");
imgTitle.value = response.ImageTitle;
var stock = document.getElementById("stock");
stock.value = response.Stock;
var description = document.getElementById("description");
description.value = response.Description;
var img = document.getElementById("img");
img.value = response.ImagePath;
$("#img").attr("src", img);
}
});
});
And the modal i created below it is :
<div class="modal-body">
<form>
<div class="row">
<div class="form-group">
<label for="exampleInputEmail1">Product Name</label>
<input id="pName" type="text" class="form-control" aria-describedby="emailHelp" placeholder="Enter email">
</div>
<div>
<img src="" id="img" width="150px" height="150px" style="float:right" />
</div>
</div>
<div class="row">
<div class="form-group col-lg-6">
<label for="exampleInputEmail1">Product Price</label>
<input id="pPrice" type="text" class="form-control" aria-describedby="emailHelp" placeholder="Enter email">
</div>
<div class="form-group col-lg-6">
<label for="exampleInputEmail1">Discount Price</label>
<input id="pDPrice" type="text" class="form-control" aria-describedby="emailHelp" placeholder="Enter email">
</div>
</div>
<div class="row">
<div class="form-group col-lg-6">
<label for="exampleInputEmail1">Image Title</label>
<input id="imgTitle" type="text" class="form-control" aria-describedby="emailHelp" placeholder="Enter email">
</div>
<div class="form-group col-lg-6">
<label for="exampleInputEmail1">Quantity in stock</label>
<input id="stock" type="text" class="form-control" aria-describedby="emailHelp" placeholder="Enter email">
</div>
</div>
<div class="row">
<div class="form-group col-lg-6">
<label for="exampleInputEmail1">Description</label>
<input id="description" type="text" class="form-control" aria-describedby="emailHelp" placeholder="Enter email">
</div>
<div class="form-group col-lg-6">
<div class="col-lg-6">
<label for="exampleInputEmail1">Category</label>
#Html.DropDownList("Category", new SelectList((System.Collections.IEnumerable)ViewData["Category"], "Id", "CategoryName"), new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
</div>
</form>
</div>
Anfinal outpur is like :

Ajax Different checkboxes should send user to different pages

I am trying to send users to different pages/URL's based on the option they choose in the checkbox. I tried everything but can't seem to figure out the correct "if statement" to do it. Not sure what the easiest way to accomplish this is. PLEASE HELP!
Here is my HTML code for the form:
<!-- Register start -->
<section id="register">
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>Register Now</h2>
</div>
</div>
<div class="row registration-success-msg">
<div class="col-md-12">
<div class="alert alert-success"><strong>Congratulations!</strong> Your registration was successful.</div>
</div>
</div>
<div class="row validation-error-msg">
<div class="col-md-12">
<div class="alert alert-danger">Please check your data! All fields are required.</div>
</div>
</div>
<!-- Checkboxes Start Here -->
<div class="row">
<div class="col-md-6 plans">
<h3>1. Select your Plan</h3>
<div class="plan">
<div class="checkbox">
<i class="fa fa-square-o" name="Option1"></i>
</div>
<div class="offer">
<h4>1 DAY TICKET <span class="label">$ 29.00</span></h4>
<p>Here is some dummy text. You can also use tooltips. on top, but you can have it on the bottom too! </p>
</div>
</div>
<div class="plan">
<div class="checkbox">
<i class="fa fa-square-o" name="Option2"></i>
</div>
<div class="offer">
<h4>2 DAYS TICKET <span class="label">$ 39.00</span></h4>
<p>Here is some dummy text. You can also use tooltips. on top, but you can have it on the bottom too! </p>
</div>
</div>
<div class="plan">
<div class="checkbox">
<i class="fa fa-square-o" name="Option3"></i>
</div>
<div class="offer">
<h4>3 DAYS TICKET <span class="label">$ 49.00</span></h4>
<p>Here is some dummy text. You can also use tooltips. on top, but you can have it on the bottom too! </p>
</div>
</div>
</div>
<!-- Checkboxes END Here -->
<div class="col-md-6 register-form">
<h3>2. Enter your Personal information</h3>
<form action="submit-forms.php" method="post">
<input type="hidden" name="plan">
<input type="hidden" name="type" value="registration">
<div class="row">
<div class="col-md-12">
<input type="text" name="first_name" class="form-control" placeholder="First Name">
</div>
</div>
<div class="row">
<div class="col-md-12">
<input type="text" name="last_name" class="form-control" placeholder="Last Name">
</div>
</div>
<div class="row">
<div class="col-md-12">
<input type="text" name="email" class="form-control" placeholder="Email">
</div>
</div>
<div class="row">
<div class="col-md-12">
<input type="text" name="address" class="form-control" placeholder="Address">
</div>
</div>
<div class="row">
<div class="col-md-12">
<input type="text" name="zip_code" class="form-control" placeholder="Zip Code">
</div>
</div>
<div class="row">
<div class="col-md-12">
<input type="text" name="city" class="form-control" placeholder="City">
</div>
</div>
<div class="row">
<div class="col-md-12">
<button class="btn btn-block btn-default" data-loading-text="Loading..." data-complete-text="Registration Successful!" id="submit-registration">Submit Registration</button>
</div>
</div>
</form>
</div>
</div>
</div>
</section>
<!-- Register end -->
Here is the ajax form that process the form and sends to the php file:
var formData = $("#register form").serialize();
// Send the Form
$.ajax({
//this is the php file that processes the data and send mail
url: "submit-forms.php",
//POST method is used
type: "POST",
//pass the data
data: formData,
//Do not cache the page
cache: false,
//success
success: function(data) {
//$("#submit-registration").button('complete');
//$('.registration-success-msg').fadeIn("slow");
console.log("success");
window.location.href = 'http://link1goeshere.com';
}
});
Here is the PHP FILE:
if('registration' == $submitType)
{
// prepare message
$body = "You have got a new registration from your website : \n\n";
$body .= "First Name: $_POST[first_name] \n\n";
$body .= "Last Name: $_POST[last_name] \n\n";
$body .= "Email: $_POST[email] \n\n";
$body .= "Address: $_POST[address] \n\n";
$body .= "Zip Code: $_POST[zip_code] \n\n";
$body .= "City: $_POST[city] \n\n";
$body .= "Plan: $_POST[plan] \n\n";
if( $_POST['email'] && !preg_match( "/[\r\n]/", $_POST['email']) ) {
$headers = "From: $_POST[email]";
} else {
$headers = "From: $youremail";
}
mail($youremail, 'New Registration', $body, $headers );
}
First of all your jQuery selector isn't going to match anything.
var formData = $("#register form").serialize();
You will need to use:
var formData = $("#register").find(form).serialize();
since the form element isn't a direct chidl of your #register element.
Edit: Sorry that is completely wrong, the two are identical.
Next, serialize() will give you a string 'name=value&name2=value2' etc whereas post data should be in the form of {name: value, name2: value2}.
Try serializeArray():
var formData = $("#register").find(form).serializeArray();
var postData = {};
formData.forEach(function (form) {
postData[form.name] = form.value;
});
$.post('submit-forms.php', postData, function (data) {
console.log(data);
window.href.location = 'http://link1goeshere.com';
});
However I still see no checkboxes...

Categories