PHP Form Sending Issues (using SendInBlue) - php

I have a basic PHP contact form which I use on a couple of sites, which sends email using the SendInBlue API.
My problem is that I have the form working perfectly on 1 site, now I am using the EXACT same code for a second site and just changing the email, name, etc - however when testing it I now get this error:
Fatal error: Call to undefined method Mailin::send_email() in
/URL/contactpage.php on line 71
FYI, line 71 is:
$mailin->send_email($data);
I have attached the complete code below - this works perfectly on 1 site, but I get this error on my second site.
Any ideas?
Thank you!
<?php
//Email Details for Form Notifications
$email_to = 'Test#test.com'; //the address to which the email will be sent
$email_to_name = 'Test';
//Form Fields
$fname = $_POST['firstname'];
$lname = $_POST['lastname'];
$email = $_POST['email'];
$fullmessage = $_POST['message'];
//Subject Lines
$subject_to = 'Test';
$subject_touser = 'Test';
//URL Redirects
$confirm = 'TestConfirm';
$errorurl = 'TestError';
//Validate
$emailval = filter_var( $email, FILTER_VALIDATE_EMAIL );
if ($emailval == false)
{
header("Location: $errorurl");
} else {
// The email to us
$message_to = 'Message here';
//
// The email to them
$message_touser = 'Message here';
//
require('Mailin.php');
//Notification Email
$mailin = new Mailin('https://api.sendinblue.com/v2.0','MY_KEY');
$data = array( "to" => array($email_to=>$email_to_name),
"cc" => array($email_to_cc=>$email_to_cc_name),
"from" => array($email,$fname),
"subject" => $subject_to,
"html" => $message_to
);
$mailin->send_email($data);
//Email to User
$mailin = new Mailin('https://api.sendinblue.com/v2.0','MY_KEY');
$data2 = array( "to" => array($email=>$fname),
"from" => array($email_to,$email_to_name),
"subject" => $subject_touser,
"html" => $message_touser
);
$mailin->send_email($data2);
header("Location: $confirm");
}
?>

I was using a deprecated Mailin.php. Updated the file and everything works now.

Related

MailGun Check if an email already is subscribing

I have been trying to solve this in all ways I can figure out, but have surely missed something. I've tried to access the fields using for-loops, just calling it, arrays, objects etc. I just can't get it to work.
What I'm talking about is to check if a provided email in a form already is subscribing to my maillist at MailGun. I don't know how to check this and I've been searching the web for answer for about 1-2 hours now and I'm finally asking here aswell.
My code so far:
<?php
session_start();
ini_set('display_errors', 1);
require_once 'init.php';
if (!isset($_POST['email']) && isset($_POST['name'])) {
echo 'You have to provide an email!';
} else if (!isset($_POST['name']) && isset($_POST['email'])) {
echo 'You have to provide a name!';
} else if (isset($_POST['name'], $_POST['email'])) {
$name = $_POST['name'];
$email = $_POST['email'];
// This is temporary to test and only works if an email existing is provided.
// If an invalid email is provided, an error is cast
// See below for the error
if (!$mailgun->get('lists/' . MAILGUN_LIST . '/members' . $email)) {
echo "Email doesnt exist";
die();
$validate = $mailgunValidate->get('address/validate', [
'address' => $email
])->http_response_body;
if ($validate->is_valid) {
$hash = $mailgunOptIn->generateHash(MAILGUN_LIST, MAILGUN_SECRET, $email);
$mailgun->sendMessage(MAILGUN_DOMAIN, [
'from' => 'noreply#adamastmar.se',
'to' => $email,
'subject' => 'Please confirm your subscription to the mailing list',
'html' => "
Hello {$name},<br><br>
You signed up to our mailing list. Please confirm your subscription below.<br><br>
<a href='http://www.adamastmar.se/confirm.php?hash={$hash}'>Click here to confirm</a>"
]);
$mailgun->post('lists/' . MAILGUN_LIST . '/members', [
'name' => $name,
'address' => $email,
'subscribed' => 'no'
]);
$_SESSION['joined'] = "A message has been sent to the provided email. Please confirm the subscription by clicking the link in the mail.";
header('Location: ./');
}
} else {
$_SESSION['alreadysub'] = "You are already a subscriber to this list!";
header('Location: ./');
}
}
?>
The error I get if I use the code above:
Uncaught exception 'Mailgun\Connection\Exceptions\MissingEndpoint' with message 'The endpoint you've tried to access does not exist.
Check your URL.' in /home/jivusmc/domains/adamastmar.se/public_html/vendor/mailgun/mailgun-php/src/Mailgun/Connection/RestClient.php:258
Stack trace: #0 /home/jivusmc/domains/adamastmar.se/public_html/vendor/mailgun/mailgun-php/src/Mailgun/Connection/RestClient.php(110):
Mailgun\Connection\RestClient->responseHandler(Object(GuzzleHttp\Psr7\Response))
#1 /home/jivusmc/domains/adamastmar.se/public_html/vendor/mailgun/mailgun-php/src/Mailgun/Connection/RestClient.php(195):
Mailgun\Connection\RestClient->send('GET', 'lists/news#mail...') #2 /home/jivusmc/domains/adamastmar.se/public_html/vendor/mailgun/mailgun-php/src/Mailgun/Mailgun.php(215):
Mailgun\Connection\RestClient->get('lists/news#mail...', Array) #3 /home/jivusmc/domains/adamastmar.se/public_html/mailinglist.php(16):
Mailgun\Mailgun->get('lists/news#mail...') #4 {main} thrown in /home/jivusmc/domains/adamastmar.se/public_html/vendor/mailgun/mailgun-php/src/Mailgun/Connection/RestClient.php on line 258
Any help & tips/tricks is appreciated!
I found a solution to the issue I had. Instead of doing everything in an if-statement, I instead surrounded it in a try-catch. I try to check if the email can be fetched from the mailgun list and if it fails, it catches the error and instead adds the mail to the list. (I'm posting it here since it's nearly impossible to find a solution to this in a better way)
$name = $_POST['name'];
$email = $_POST['email'];
try {
$mailgun->get('lists/' . MAILGUN_LIST . '/members/' . $email);
$_SESSION['alreadysub'] = "You are already a subscriber to this list!";
header('Location: ./');
} catch (Exception $e) {
$validate = $mailgunValidate->get('address/validate', [
'address' => $email
])->http_response_body;
if ($validate->is_valid) {
$hash = $mailgunOptIn->generateHash(MAILGUN_LIST, MAILGUN_SECRET, $email);
$mailgun->sendMessage(MAILGUN_DOMAIN, [
'from' => 'noreply#adamastmar.se',
'to' => $email,
'subject' => 'Please confirm your subscription to the mailing list',
'html' => "
Hello {$name},<br><br>
You signed up to our mailing list. Please confirm your subscription below.<br><br>
<a href='http://www.adamastmar.se/confirm.php?hash={$hash}'>Click here to confirm</a>"
]);
$mailgun->post('lists/' . MAILGUN_LIST . '/members', [
'name' => $name,
'address' => $email,
'subscribed' => 'no'
]);
$_SESSION['joined'] = "A message has been sent to the provided email. Please confirm the subscription by clicking the link in the mail.";
header('Location: ./');
}
}
I know this problem and the answer are in PHP. But I just figured out a way in NodeJS and wish I've found a solution for it earlier. Maybe it helps someone.
FYI: I'm checking if an email exists in mailing list from Mailgun.
var DOMAIN = 'YOUR_DOMAIN_NAME';
var mailgun = require('mailgun-js')({ apiKey: "YOUR_API_KEY", domain: DOMAIN});
const array = await mailgun.getList().catch(console.error);
if(checkIfEmailExcistInMailinglist(array.items, dbUser.email)){
// if then do something
}
checkIfEmailExcistInMailinglist(array, email) {
for (var i = 0; i < array.length; i++) {
if (array[i].address === email) {
return true;
}
}
return false;
}

Why is this script sending blank emails without using template in SugarCRM?

This is my code to send emails in SugarCRM CE 6.5.x version,
<?php
if (!defined('sugarEntry') || !sugarEntry) die('Not A Valid EntryPoint');
require_once('include/SugarPHPMailer.php');
$msg = new SugarPHPMailer();
$emailObj = new Email();
$defaults = $emailObj->getSystemDefaultEmail();
//Setup template
require_once('XTemplate/xtpl.php');
$xtpl = new XTemplate('custom/modules/Users/ChangePassword.html');
//assign recipients email and name
$rcpt_email = 'sohan.tirpude#mphasis.com';
$rcpt_name = 'Sohan';
//Set RECIPIENT's address
$email = $msg->AddAddress($rcpt_email, $rcpt_name);
//Send msg to users
$template_name = 'User';
//Assign values to variables in template
$xtpl->assign('EMAIL_NAME', $rcpt_name);
$xtpl->parse();
//$body = "Hello Sohan, It's been 80 days that you haven't changed your password. Please take some time out to change password first before it expires.";
$msg->From = $defaults['email'];
$msg->FromName = $defaults['name'];
$msg->Body = from_html(trim($xtpl->text($template_name)));
//$msg->Body = $body;
$msg->Subject = 'Change Password Request';
$msg->prepForOutbound();
$msg->AddAddress($email);
$msg->setMailerForSystem();
//Send the message, log if error occurs
if (!$msg->Send()){
$GLOBALS['log']->fatal('Error sending e-mail: ' . $msg->ErrorInfo);
}
?>
Now this script send blanks emails, and when I hardcoded body part then it is takes those message written in body, and sends an email. So, please help me here.

Mailchimp API - Subscribe to list

I'm working on adding a script to my site for a MailChimp subscribe form. I think I have everything setup right but when I hit the subscribe button I'm getting a blank page.
Here is the script I have currently
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
require_once 'Mailchimp.php';
$apikey = "XXXXXXXXXXXXXXX";
$Mailchimp = new Mailchimp($apikey);
if (!empty($_POST)) {
$id = "XXXXXXXXXX";
$email = array(
'email' => trim($_POST['email'])
);
$result = $Mailchimp->$lists->subscribe($id, $email, $double_optin=false, $replace_interests=false);
var_dump($result);
}
echo "TESTING";
So I'm not getting the $result variable or "TESTING echo'd right now, so I assume I must be doing something simple wrong. Anyone see anything obvious? I believe I'm using the correct default JSON format. (keys have been X'd out, but the one's I'm using are correct)
Any help is much appreciated.
Thanks!!
EDIT: I have updated the code to something I believe to be more correct, but it still isn't working. I could really use some help on this.
Here's how I've handled AJAX email submissions in the past for MailChimp's API (MCAPI):
define("MC_API_KEY", "Your mailchimp API key");
define("MC_API_LIST", "The list ID to subscribe user to");
define("EMAIL_TO", "email address in case subscription fails");
require "MailChimp.API.class.php";
function json($error = true, $message = "Unknown error") {
die(json_encode(array("error" => $error, "message" => $message)));
}
if(!empty($_POST)) {
$email = !empty($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ? $_POST['email'] : false;
if($email !== false) {
$api = new MCAPI(MC_API_KEY);
$result = $api->listSubscribe(MC_API_LIST, $email);
if($api->errorCode || !$result) {
if(isset($api->errorCode) && $api->errorCode == 214) { // already subscribed
json(true, "You are already subscribed!");
} else {
$error = "Unable to save user email via MailChimp API!\n\tCode=".$api->errorCode."\n\tMsg=".$api->errorMessage."\n\n";
$headers = "From: your#email.com\r\nReply-to: <{$email}>\r\nX-Mailer: PHP/".phpversion();
mail(EMAIL_TO, "Newsletter Submission FAIL [MC API ERROR]", "{$error}Saved info:\nFrom: {$email}\n\nSent from {$_SERVER['REMOTE_ADDR']} on ".date("F jS, Y \# g:iA e"), $headers);
json(false, "Thank you - your email will be subscribed shortly!");
}
} else {
json(false, "Thanks - A confirmation link has been sent to your email!");
}
} else {
json(true, "Please enter your valid email address");
}
} else json();
SOLVED:
Here is the correct code - hopefully this will help others looking to use the new api -
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
require_once 'Mailchimp.php';
$apikey = "XXXXXXXXXXXXXXXXXXX";
$Mailchimp = new Mailchimp($apikey);
if (!empty($_POST)) {
$id = "XXXXXXXXXX";
$email = array(
'email' => trim($_POST['email'])
);
$result = $Mailchimp->lists->subscribe($id, $email, $merge_vars=null, $double_optin=false, $replace_interests=false);
}

queries regarding PHP mail() 'issues'

So I recently made a basic site for a family members small company. I included a mail form, for enquiries etc.
here is the code i use:
<?php
function check_input($data){ // SANITIZE USER STRING INPUT
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$name = check_input($_POST['name']);
$surname = check_input($_POST['surname']);
$email = check_input($_POST['email']);
$telephone = check_input($_POST['telephone']);
$comments = check_input($_POST['message']);
$message = "From: $name $surname
Email: $email
Telephone: $telephone
--------------------------------------------------------------
Comments: $comments
";
mail("#############.com","Website Enquiry from www.#######.co.uk",$message,"From: webserver");
?>
now when I try it, it works absoloutely fine. However I have noticed sometimes it is realllllly slow and so we have been receiving blank emails through the form (the user input data is not present), so it appears someone has attempted to use it and given up perhaps because it is taking too long?
I am assuming this is to do with the mail server rather than php mail. But I wanted to see if anyone could highlight potential issues that I could take to the company hosting for her?
many thanks,
check if name and email fields are entered and then proceed with mail function..this reduces getting blank emails.
<?php
if (isset($_POST['name']) && isset($_POST['email'])) //check if name and email fields are entered and then proceed with mail function
{
//process the data and send mail.
}
else
{
echo "Error missing name or email field.please enter";
}
?>
Alternatively you can also use array_key_exists()
<?php
if (array_key_exists("name", $_POST) && $_POST["name"] != "" && array_key_exists("email", $_POST) && $_POST["email"] != "")
//check if name and email fields are entered and then proceed with mail function
{
//process the data and send mail.
}
else
{
echo "Error missing name or email field.please enter";
}
?>
Actually you are not checking if someone fill the form empty that's why you are getting blank fields
<?php
function check_input($data){ // SANITIZE USER STRING INPUT
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(!empty($data))
{
$name = check_input($_POST['name']);
$surname = check_input($_POST['surname']);
$email = check_input($_POST['email']);
$telephone = check_input($_POST['telephone']);
$comments = check_input($_POST['message']);
$message = "From: $name $surname
Email: $email
Telephone: $telephone
--------------------------------------------------------------
Comments: $comments
";
mail("#############.com","Website Enquiry from www.#######.co.uk",$message,"From: webserver");
}
?>

jQuery, PHP & AJAX Issues

So I've read the jQuery AJAX pages, and a bunch of tutorials, but am having a slight problem over here.
There are no errors, or warnings, just a blank page.
I am trying to send an email when the user fills in the newsletter subscription test field with their email address, and when you click submit, the page refreshes! (1st problem) and it fails to display anything on the page (second problem), all you see is just a blank page. No emails were received.
I've tested the email script separately, which works fine. I've been using for months with different sites so I know it works.
I've tried changing things around in jQuery etc but nothing has helped fix this problem.
jQuery:
$(function () {
var txt = $('.email').val();
$.ajax({
url: 'index.php',
type: 'post',
data: {
email: txt
},
success: function (data) {
alert(data);
},
error: function (err, req) {
$('#Response').html({
"Somethin' got broked. Please try again."
});
}
});
});
PHP:
<?php
if($_POST["email"] != null)
{
require_once "Mail.php";
$email = $_POST["email"];
// Send it.
$from = "X#X.com.au";
$to = $email;
$subject = "Newsletter Subscription Request.";
$body = "Thank you for subscribing to our newsletter!";
$host = "mail.X.com.au";
$username = "no-reply#X.com.au";
$password = "X";
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
}
?>
HTML:
<h4 id="Response">Stay informed. Subscribe to our Newsletter!</h4>
<form class="newsletterForm" action="index.php" method="post">
<input type="text" class="email" name="email" />
<input type='submit' class="btn" value="Subscribe" />
</form>
Can someone please help me figure out why this won't work?
Thank you
The 1st thing I do when stuff like this isn't working is to watch the page calls in the Chrome Developer Tools window.
As far as your code goes, the reason the page is refreshing is because the form submit is going through. To keep that from happening, you have to trap the form submit:
$("form").submit(function() {
// Do ajax
return false; // Keeps the form from submitting
});
Once you have that in place, you should be getting better results.
I would caution, however, that it is much easier to get the PHP email sending form working without using ajax at first by just having it handle the regular form submit. Once that works, then tie in the ajax on top of it.
With the following line you suppose to receive an answer from the PHP Script
success: function(data) {
alert(data);
}
But in the PHP script you don't output anything...Try writing something like
//[...]
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
die(1);
please try this surely you can get the problem solve.
function FormSubmit()
{
$.ajax({
type: "POST",
url: 'index.php',
data: $("#form_main").serialize(),
async: false
}).done(function( data ) {
$("#Response").hide();
if (isNaN(data))
{
dispmsg = "<div class='alert alert-danger' role='alert'>Oops..Something had gone wrong! Please try again!</div>";
$("#assess_me_response").html(dispmsg);
setTimeout('ResetForm();',3000);
}
else
{
dispmsg = "<div class='alert alert-success' role='alert'>Thank you for sharing the details. Our Consultant will contact you shortly!</div>";
$("#assess_me_response").html(dispmsg);
setTimeout('Redirect();',3000);
}
return true;
});
}
make your php as this..
<?php
$to = "xxxx#some.com";
$name = $_POST['name'];
$email = $_POST['email'];
$age = $_POST['age'];
$phone = $_POST['phone'];
$subject = "Entry received";
$msg = "\n Name:" . $name . "\n Email id:" . $email ."\n Age:". $age . "\n Contact number: " . $phone;
$headers = "From:xxx#yyy.com";
mail($to,$subject,$msg,$headers);
echo "<div align='center'>Thank you " . $name . "!, we will contact you shortly.</div>";
?>
try this you can solve.

Categories