Search code examples
phpphpmailerzapier

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('[email protected]', 'Yashir CV Lead');

    $mail->addAddress("[email protected]");        
    $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.


Solution

  • 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('[email protected]', 'Yashir CV Lead');
    
            $mail->addAddress("[email protected]");
            $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'] ?? '';