0

I am developing a plugin that sends emails to users on activation. I am using SendinBlue API for this purpose.

Right now, I am testing with just one email address (hardcoded) and static content. The problem I am facing is that the plugin upon activation, keeps sending multiple emails having the same content multiple times to the same email address.

It should send only one email per user and then stop execution.

This is in the primary stage of development. Later, there will be more conditions added. I would use a loop of users filtered based on some criteria and send only one email per user. Once the loop completes, the execution must stop immediately.

Plugin (index.php) code:

<?php
/**
 * Plugin Name: SIB Auto Mailing
 */

require_once ( __DIR__ . '/vendor/autoload.php' );

//Setting up the credential
$credentials = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey( 'api-key', 'xkeysib-xxxxxxxxx' );
$apiInstance = new SendinBlue\Client\Api\TransactionalEmailsApi( new GuzzleHttp\Client(), $credentials );

//Get the content
$template = file_get_contents( get_template_directory_uri() . '/templates/e-invite.html' );
$template = str_replace( '{username}', 'Subrata', $template );

//Email setup
$sendSmtpEmail = new \SendinBlue\Client\Model\SendSmtpEmail( array(
    'subject'     => 'A warm welcome',
    'sender'      => [ 'name' => 'UCOH Ex-Students\' Association', 'email' => '[email protected]' ],
        'replyTo'     => [ 'name' => 'UCOH Ex-Students\' Association', 'email' => '[email protected]' ],
        'to'          => [ [ 'name' => 'Recipient Name', 'email' => '[email protected]' ] ],
        'htmlContent' => $template,
        'params'      => [ 'bodyMessage' => 'made just for you!' ],
    ) );

//Send
try {
    $result = $apiInstance->sendTransacEmail( $sendSmtpEmail );
    print_r( $result );
} catch ( Exception $ex ) {
    echo $ex->getMessage(), PHP_EOL;
}
1

1 Answer 1

1

The code in the file itself can be executed multiple times. If you want to do something when the plugin is activated use register_activation_hook and wrap your email sending codes in it.

function my_plugin_activation() {
   //Setting up the credential
    ...
 }
register_activation_hook( __FILE__, 'my_plugin_activation' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.