Search code examples
phpemailmailgun

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'      => '[email protected]',
                '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!


Solution

  • 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'      => '[email protected]',
                    '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: ./');
            }
        }