PHP Mail function not working on Web Services - php

I am using two different servers for dev site and live site. My webservice function to send email confirmation is working on Dev Site but it is not working in Live Site. My
email confirmation function is:
function getEmailConfirmation($UserName, $ChecklistID,$UserID,$AnswerBulkID, $TotalSubmitted){
if ( ($UserID == '') || (!isset($UserID)) ) {
return error("partial");
}
$entry = new Entry();
$entry_date_check = date('Y-m-d'); //for check if already
$count_tbl_answers = $entry->listEntry("SELECT count(*) as total_from_answers FROM tbl_answers where user_id='".$UserID."' and answer_bulk_id ='".$AnswerBulkID."' and date(ent_date) = '".$entry_date_check."' ");
$to = "****#gmail.com";
$subject = "TDL Checklist email";
$message = "Hello there! \n User ID: ".$UserID." \n User Name: ".$UserName."\n Check List ID: ".$ChecklistID."\n Answer Bulk ID: ".$AnswerBulkID;
$from = "TLD-Email-Confirmation";
$headers = "From:" . $from;
if(($count_tbl_answers[0]['total_from_answers']) == $TotalSubmitted){
mail($to,$subject,$message,$headers);
$result = array(
"user_id" => $UserID,
"user_name" => $UserName,
"check_list_id" => $ChecklistID,
"answer_bulk_id" => $AnswerBulkID,
);
} else{
$delete_bulk = $entry->query("delete FROM tbl_answerbulk WHERE user_id ='".$UserID."' and check_list_id ='".$ChecklistID."' and id ='".$AnswerBulkID."' ");
$delete_answer = $entry->query("delete FROM tbl_answers WHERE user_id='".$UserID."' and answer_bulk_id ='".$AnswerBulkID."' ");
return error("custom","","Could not submit your answer this time. Please try again later.");
}
$message = json_encode(
$result
);
$fin_data['response'] = json_encode(array('Message'=>'ok','Data'=>$message));
return $fin_data;
}
This function works perfectly on dev server, but it does not work on live server. What might be the reason?
Note:
Although mail function not working on Live site, it returns the result array which is just after the mail function.
That is:
#mail($to,$subject,$message,$headers);
$result = array(
"user_id" => $UserID,
"user_name" => $UserName,
"check_list_id" => $ChecklistID,
"answer_bulk_id" => $AnswerBulkID,
);
I also tried ini_set('smtp_port', 587); and #mail($to,$subject,$message,$headers); but does not worked.

Related

regarding mail sent from my custom registration form in drupal

I have created a custom registration form in Drupal 8, and now i want to sent a mail from the submission of the form. So I have did it like this
This is my .module file
/**
* Implements hook_mail().
*/
function Registration_form_mail($key, &$message, $params) {
$options = array(
'langcode' => $message['langcode'],
);
switch ($key) {
case 'contact_form':
$message['from'] = \Drupal::config('system.site')->get('mail');
$message['subject'] = $params['subject'];
$message['body'][] = $params['body'];
break;
}
}
public function submitForm(array &$form, FormStateInterface $form_state){
$mailManager = \Drupal::service('plugin.manager.mail');
$module = 'Registration_form';
$key = 'contact_form'; // Replace with Your key
$to = $form_state->getValue('Email');
$params = array(
'body' => 'test',
'subject' => 'Website Information Request',
);
$langcode = \Drupal::currentUser()->getPreferredLangcode();
$send = true;
$message['subject'] = t('nouveau contact ');
$message['body'][] = t('test');
$result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
if ($result['result'] != true) {
$message = t('There was a problem sending your email notification to #email.', array('#email' => $to));
drupal_set_message($message, 'error');
\Drupal::logger('mail-log')->error($message);
return;
}
else{
$message = t('An email notification has been sent to #email ', array('#email' => $to));
drupal_set_message($message);
\Drupal::logger('mail-log')->notice($message);
}
}
So my question is i'm using localhost in xampp and i want to sent a mail after submission of the form, but i'm getting this error
Unable to send email. Contact the site administrator if the problem persists.
There was a problem sending your email notification to ABC#gmail.com
So how I can resolve my problem, i have gone through whole sites but not able to find answer.
The problem may be with the email configuration. See if this article helps you:
https://stevepolito.design/blog/drupal-configure-smtp-module-work-gmail-updated/

PHP MAIL: one of my variables send a "false" value

I am sending an e-mail with different variables as an JSON encoded array from an online store. I get the mail just fine and all the data is in there except for one of the variables, which is a JSON encoded array by itself. this particular variable shows as "false" in the e-mail. I'm missing something?
I'm using PHP mail to do it.
<?php
require_once "Mail.php";
$link = mysqli_connect("localhost", "xxx", "xxx", "xxx");
if ($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM users WHERE user = '" . $_SESSION['logged'] . "'";
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_assoc($result);
$user = $_SESSION['logged'];
$rua = $_POST['rua'];
$numero = $_POST['numero'];
$apt = $_POST['apt'];
$cep = $_POST['cep'];
$total = $_POST['total'];
$comment = $_POST['observacion'];
$from = $row['mail'];
$mailTo = "xxxxx#hotmail.com";
$subject = "compra online - no cep";
$compra = $_SESSION["shopping_cart"];
$compra2 = json_encode($compra);
$bod = array(
'user' => $user,
'rua' => $rua,
'cep' => $cep,
'compra' => $compra2,
'comment' => $comment,
'total' => $total,
);
$body = json_encode($bod);
$headers = array(
'From' => $from,
'To' => $mailTo,
'Subject' => $subject,
);
$smtp = Mail::factory('smtp', array(
'host' => 'smtp-mail.outlook.com',
'port' => '587',
'auth' => true,
'username' => 'xxxxxxx#hotmail.com',
'password' => 'xxxxxxx',
));
$mail = $smtp->send($mailTo, $headers, $body);
if (PEAR::isError($mail)) {
echo ("<p>" . $mail->getMessage() . "</p>");
} else {
header("Location: lojacart.php?mailok");
}
mysqli_close($link);
I'm getting the e-mail with all the data except for the $compra2 variable which is showing as 'compra'=false. now if I echo the variable $compra2 it actually have a large string of data on it.
I think it might have to do with the variable being a JSON encoded session, but I'm not sure.
After a lot of trying and getting frustrated I came with a solution, for those looking for a something like this:
I added a hidden input to the form on the previous page and assigned it a value as "print_r($SESSION['whatever you session is called'], TRUE)" ...
on the next page I took the $_POST[] form that input and added the variable to the $body array for the mail().
It will print some array garbage in the middle BUT it works like a charm! and I cleaned all the "extra" text form the array using preg_replace(). It may not be an elegant way of doing it but as I said... it worked

Connecting Zapier with PHPMailer Script

I'm using Zapier to collect leads from facebook,and than send them to my CRM.
I Have a script connected to my CRM,that is supposed to handle the leads.
for every new lead the script will trigger,
the script collects the data passed from Zapier and converts it to an XML and sends it my client.
Everything works except for one thing.
The PHPMailer seems to cause trouble with zapier,because whenever the email() function is enabled Zapier will give me an Error.
FYI - this works when I go to the script url and set the GET parameters by hand .
the xml is being sent. But when triggering the script from zapier the problem occurs.
Zapier Error:
"We had trouble sending your test through.
The app returned "Internal Server Error" with no further details. It looks like the server for your connected app is down or currently experiencing problems. Please check the app's status page or contact support if there are no reported issues."
<?php
$firstName = isset($_GET['firstName']) ? $_GET['firstName'] : '';
$lastName = isset($_GET['lastName']) ? $_GET['lastName'] : '';
$fullName = isset($_GET['fullName']) ? $_GET['fullName'] : '';
$phone = isset($_GET['phone']) ? $_GET['phone'] : '';
$experience = isset($_GET['experience']) ? $_GET['experience'] : '';
$city = isset($_GET['city']) ? $_GET['city'] : '';
$email = isset($_GET['email']) ? $_GET['email'] : '';
$utm_source = isset($_GET['utm_source']) ? $_GET['utm_source'] : '';
$campaignId = isset($_GET['campaignId']) ? $_GET['campaignId'] : '';
$utm_medium = isset($_GET['utm_medium']) ? $_GET['utm_medium'] : '';
require 'vendor/autoload.php';
header('Content-Type: text/plain');
function createXML($data,$dataSource){
$dom = new DOMDocument('1.0', 'utf-8');
$cv = $dom->createElement("cv");
$candidate = $dom->createElement('candidate');
$source_type = $dom->createElement('source_type');
function recursive($dom, $parent, $key, $value) {
if(is_array($value)) {
$new_parent = $dom->createElement($key);
foreach($value as $k => $v){
recursive($dom, $new_parent, $k, $v);
}
$parent->appendChild($new_parent);
} else {
$field = $dom->createElement($key, htmlspecialchars($value));
$parent->appendChild($field);
}
}
foreach($dataSource as $key => $value){
// api need COLUMN without end of _<number>
if(preg_match('/COLUMN_([0-9]+)/', $key)) $key = 'COLUMN';
recursive($dom, $source_type, $key, $value);
}
foreach($data as $key => $value){
// api need COLUMN without end of _<number>
if(preg_match('/COLUMN_([0-9]+)/', $key)) $key = 'COLUMN';
recursive($dom, $candidate, $key, $value);
}
// $cv->appendChild($candidate)
$cv->appendChild($candidate);
$cv->appendChild($source_type);
$dom->appendChild($cv);
$node = $cv->appendChild($source_type);
$node->setAttribute('type','other');
$dom->formatOutput = true;
return $dom;
}
$data = array(
"first_name" => filter_var($firstName, FILTER_SANITIZE_STRING),
"last_name" => filter_var($lastName, FILTER_SANITIZE_STRING),
"mobile" => filter_var($phone, FILTER_SANITIZE_STRING),
'email' => '',
'id' => '',
);
$dataSource = array(
"source_title" => filter_var($utm_source, FILTER_SANITIZE_STRING),
"first_name" => '',
"last_name" => '',
"mobile" => '',
"email" => '',
"employee_number" => '',
"department" => '',
"email" => '',
);
//problematic function
function email(){
global $xmlData;
$mail = new PHPMailer(true);
$mail->isHTML(false);
$mail->isSMTP();
$mail->setFrom('XML#gmail.com', 'Yashir CV Lead');
$mail->addAddress("BinaryRx#gmail.com");
$mail->Subject = "Yashir CV Lead";
$mail->Body = $xmlData;
$today = date('d-m-Y H:i:s');
$mail->send();
echo "Report Sent - " . $today;
}
///////// IF I uncomment bellow,Zapier will give me the following error:
//We had trouble sending your test through.
//The app returned "Internal Server Error" with no further details.
//It looks like the server for your connected app is down or currently experiencing problems.
//Please check the app's status page or contact support if there are no reported issues.
//Uncomment bellow.
// email();
?>
I Expect for every Lead to send an email containing a XML.
Two key problems. Firstly, you're using SMTP, but you have not set Host to your mail server - so it won't work unless it's localhost - is that the case?
You're asking PHPMailer to throw exceptions (by passing true to the constructor), but you don't have a try/catch block wrapped around the calls to PHPMailer, so any errors will result in uncaught exceptions - which will give you exactly the symptom you're seeing. Try this:
function email()
{
global $xmlData;
$mail = new PHPMailer(true);
try {
$mail->isHTML(false);
$mail->isSMTP();
$mail->setFrom('XML#gmail.com', 'Yashir CV Lead');
$mail->addAddress("BinaryRx#gmail.com");
$mail->Subject = "Yashir CV Lead";
$mail->Body = $xmlData;
$today = date('d-m-Y H:i:s');
$mail->send();
echo "Report Sent - ".$today;
} catch (Exception $e) {
echo 'Sending failed'.$e->getMessage();
}
}
Overall, the main thing is to debug one thing at a time - check that the email() function actually works independently before you start trying to do things that depend on it working, because otherwise you won't know which bit of the code is failing.
If you're using PHP 7.0 or later, you can simplify those initial checks for params by using the null coalesce operator. You can replace this:
$firstName = isset($_GET['firstName']) ? $_GET['firstName'] : '';
with:
$firstName = $_GET['firstName'] ?? '';

PHP returning extra whitespace with return statement?

My code works, but for some strange reason when I return a string it adds extra space and I think a new line as well.
The code below works fine. However the length of this when fetched with Ajax is 11, the string success has a length of seven so this isn't right and it also doesn't equal to 'success' when comparing.
I've looked through a few other questions but all the solutions they offer don't seem to be working for me. No trailing spaces anywhere as far as I can see. And it's also not coming from any of the files I'm requiring.
<?php
/*
Plugin Name: Quotation Rest API
Plugin URI:
Description: A rest API for sending quotation request through to email using Sendgrid.
Version: 1.0
Author: Niels
Author URI:
*/
add_action( 'rest_api_init', function () {
register_rest_route( 'offerte', '/send',array(
'methods' => 'POST',
'callback' => 'send_mail',
) );
} );
include('MailChimp.php');
use \DrewM\MailChimp\MailChimp;
function send_mail( WP_REST_Request $request) {
$data = $request['data'];
$name = htmlspecialchars($request['name']);
$email = htmlspecialchars($request['email']);
$comment = htmlspecialchars($request['comment']);
$website = htmlspecialchars($request['url']);
$company = htmlspecialchars($request['company']);
$tel = htmlspecialchars($request['tel']);
$mailchimp = htmlspecialchars($request['mailchimp']);
$dataArray = json_decode($data, true);
ob_start();
include('mail.php');
$mailHTML = ob_get_clean();
$success = 'success';
if (!empty($mailchimp)) {
// add email to mailchimp list
$client = new MailChimp('-us14');// get from setttings
$list_id = ' ';// get from setttings
$result = $client->post("lists/$list_id/members", [
'email_address' => $email,
'status' => 'subscribed',
]);
}
$to = " #icloud.com";// get from setttings
$subject = "Offerte van " . $name;// // get from setttings (maybe...)
$message = $mailHTML;
if(wp_mail( $to, $subject, $message)){
return $success;
} else {
// return 'error';
}
}
?>

Adding media to Twilio group messaging system

My group messaging app allowing people in a group (people.php) to sms each other in a closed system where all users can view and reply to the sms.
My next step would be to allow the media files which I can see on the Twilio Console to be sent to others in this group message system and possibly save a record of that media file.
This my code so far, it functions just missing the media part.
listener.php
<?php
include("../Services/Twilio.php");
include("config.php");
$client = new Services_Twilio($accountsid, $authtoken);
include("functions.php");
include("pdo.class.php");
include("people.php");
if( isset($_POST['Body']) ){
$phone = $_POST['From'];
$message = ($_POST['Body']);
$media = ($_POST['MediaUrl0']);
$name = $people[ $phone ];
if( empty($name) ) $name = $phone;
// resends sms message to group
$message = '['.$name.'] '.$message .$media;
foreach ($people as $number => $name) {
if( $number == $phone ) continue;
$sid = send_sms($number,$message,$media);
}
// reply message for succesfull sent sms
print_sms_reply("Message delivered");
// insert sms traffic into database for record purposes
$now = time();
$pdo = Db::singleton();
$sql = "INSERT INTO message_log SET `message`='{$message}', `sent_from`='{$name}'";
$pdo->exec( $sql );
}
?>
function.php
<?php
function send_sms($number,$message){
global $client,$fromNumber;
$sms = $client->account->sms_messages->create(
$fromNumber,
$number,
$message
);
return $sms->sid;
}
function print_sms_reply ($sms_reply){
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
echo "<Response>\n<Sms>\n";
echo $sms_reply;
echo "</Sms></Response>\n";
}
?>
people.php
<?php
include("config.php");
$conn=mysqli_connect("$dbhost","$dbuser","$dbpass","$dbname")
or die (mysqli_error());
$query = "SELECT phone, name FROM grouplist";
$result = mysqli_query($conn, $query);
$people = array();
while ($row = mysqli_fetch_assoc($result)) {
$people[$row['phone']] = $row['name'];
}
?>
Twilio developer evangelist here.
Looks like you need to update your send_sms function to include the media url. Something like this should work:
<?php
function send_sms($number,$message,$media_url){
global $client,$fromNumber;
$sms = $client->account->messages->create(array(
'To' => $number,
'From' => $fromNumber,
'Body' => $message,
'MediaUrl' => $media_url
);
return $sms->sid;
}
?>
Notably, I've updated the call from $client->account->sms_messages->create because the sms_messages resource is deprecated and cannot send media messages. Using $client->account->messages->create uses the newer Messages resource and means you will be able to send media messages.
Let me know if this helps at all.

Categories