# Custom script using our code

## Before using our code

### Making sure your CMS is loaded

If you want to use the AcyMailing code outside of your site, you will need to load your site's library then [the AcyMailing library](/developers/acymailing-developer-documentation.md#code-api-for-quick-integration).

{% tabs %}
{% tab title="Joomla 3" %}
Add these lines first in your script and don't forget to replace **PATH\_TO\_YOUR\_JOOMLA\_SITE\_ROOT\_FOLDER** by the real value

{% code lineNumbers="true" %}

```php
define('_JEXEC', 1);
define('DS', DIRECTORY_SEPARATOR);
 
if (file_exists(dirname(__FILE__) . '/defines.php')) {
 include_once dirname(__FILE__) . '/defines.php';
}
 
if (!defined('_JDEFINES')) {
 define('JPATH_BASE', 'PATH_TO_YOUR_JOOMLA_SITE_ROOT_FOLDER');
 require_once JPATH_BASE.'/includes/defines.php';
}
 
require_once JPATH_BASE.'/includes/framework.php';
$app = JFactory::getApplication('site');
```

{% endcode %}
{% endtab %}

{% tab title="Joomla 4" %}
Add these lines first in your script and don't forget to replace **PATH\_TO\_YOUR\_JOOMLA\_SITE\_ROOT\_FOLDER** by the real value

{% code lineNumbers="true" %}

```php
define('_JEXEC', 1);
define('DS', DIRECTORY_SEPARATOR);
 
if (file_exists(dirname(__FILE__) . '/defines.php')) {
 include_once dirname(__FILE__) . '/defines.php';
}
 
if (!defined('_JDEFINES')) {
 define('JPATH_BASE', 'PATH_TO_YOUR_JOOMLA_SITE_ROOT_FOLDER');
 require_once JPATH_BASE.'/includes/defines.php';
}
 
require_once JPATH_BASE.'/includes/framework.php';

$container = \Joomla\CMS\Factory::getContainer();
$container->alias(\Joomla\Session\SessionInterface::class, 'session.web.site');
$app = $container->get(\Joomla\CMS\Application\SiteApplication::class);
```

{% endcode %}
{% endtab %}

{% tab title="Joomla 5" %}
Add these lines first in your script and don't forget to replace **PATH\_TO\_YOUR\_JOOMLA\_SITE\_ROOT\_FOLDER** by the real value, and to change $context if needed.

{% code lineNumbers="true" %}

```php
// site, administrator or cli, it depends on the way the script is called
$context = 'site';

define('_JEXEC', 1);
define('DS', DIRECTORY_SEPARATOR);
 
if (file_exists(dirname(__FILE__) . '/defines.php')) {
 include_once dirname(__FILE__) . '/defines.php';
}
 
if (!defined('_JDEFINES')) {
 define('JPATH_BASE', 'PATH_TO_YOUR_JOOMLA_SITE_ROOT_FOLDER');
 require_once JPATH_BASE.'/includes/defines.php';
}
 
require_once JPATH_BASE.'/includes/framework.php';

$contextConfig = [
    'site' => [
        'session' => 'session.web.site',
        'applicationClass' => \Joomla\CMS\Application\SiteApplication::class
    ],
    'administrator' => [
        'session' => 'session.web.administrator',
        'applicationClass' => \Joomla\CMS\Application\AdministratorApplication::class
    ],
    'cli' => [
        'session' => 'session.cli',
        'applicationClass' => \Joomla\Console\Application::class
    ]
];

$container = \Joomla\CMS\Factory::getContainer();
$container->alias('session', $contextConfig[$context]['session'])
          ->alias('JSession', $contextConfig[$context]['session'])
          ->alias(\Joomla\CMS\Session\Session::class, $contextConfig[$context]['session'])
          ->alias(\Joomla\Session\Session::class, $contextConfig[$context]['session'])
          ->alias(\Joomla\Session\SessionInterface::class, $contextConfig[$context]['session']);
          
          
$app = $container->get($contextConfig[$context]['applicationClass']);
\Joomla\CMS\Factory::$application = $app;
```

{% endcode %}
{% endtab %}

{% tab title="WordPress" %}
Add these lines first in your script and don't forget to replace **PATH\_TO\_YOUR\_WORDPRESS\_SITE\_ROOT\_FOLDER** by the real value

{% code lineNumbers="true" %}

```php
define('WP_USE_THEMES', false);
require('PATH_TO_YOUR_WORDPRESS_SITE_ROOT_FOLDER/wp-load.php');
```

{% endcode %}
{% endtab %}
{% endtabs %}

### Load the AcyMailing library

Before each of the following examples, please make sure the AcyMailing library is loaded.

{% tabs %}
{% tab title="Joomla" %}
{% code lineNumbers="true" %}

```php
$ds = DIRECTORY_SEPARATOR;
$initFile = rtrim(JPATH_ADMINISTRATOR, $ds).$ds.'components'.$ds.'com_acym'.$ds.'Core'.$ds.'init.php';
if (!include_once($initFile)) {
    echo 'This code can not work without the AcyMailing Component';
    return false;
}
```

{% endcode %}
{% endtab %}

{% tab title="WordPress" %}
{% code lineNumbers="true" %}

```php
$ds = DIRECTORY_SEPARATOR;
$initFile = WP_PLUGIN_DIR.$ds.'acymailing'.$ds.'back'.$ds.'Core'.$ds.'init.php';
if (!include_once($initFile)) {
    echo 'This code can not work without the AcyMailing plugin';
    return false;
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

## Subscribers

### Create a new subscriber

{% code lineNumbers="true" %}

```php
use AcyMailing\Classes\UserClass;

$myUser = new stdClass();
$myUser->email = 'address@example.com';
$myUser->name = 'example name'; // this information is optional
$customFieldId = 18;
 
// If you require a confirmation but don't want the user to have to confirm his subscription, you can set the confirmed field to 1:
// $myUser->confirmed = 1;
 
// You can add as many extra fields as you want if you already created them in AcyMailing
$customFields = [];
$customFields[$customFieldId] = 'france'; // the custom field id can be found in the Custom fields list of the AcyMailing admin page
//...
 
$userClass = new UserClass();
$userClass->sendConf = true; // Or false if you don't want a confirmation email to be sent
$userId = $userClass->save($myUser, $customFields); // this function will return you the ID of the user inserted in the AcyMailing table
```

{% endcode %}

### Get a subscriber and / or its subscriptions

{% code lineNumbers="true" %}

```php
use AcyMailing\Classes\UserClass;

$email = 'test@example.com';
$userID = 23;

$userClass = new UserClass();
 
// Get the AcyMailing user from his email address
$user = $userClass->getOneByEmail($email);
 
// Or you can get the AcyMailing user from his site user ID
$user = $userClass->getOneByCMSId($userID);
 
// Get subscription
$userSubscriptions = $userClass->getUserSubscriptionById($user->id);
 
// If you need a simpler result, you can use this method
$userSubscriptions = $userClass->getSubscriptionStatus($user->id);
```

{% endcode %}

## Lists

### Create a list

{% code lineNumbers="true" %}

```php
use AcyMailing\Classes\ListClass;

$newList = new stdClass();
$newList->name = 'Your list name';
$newList->active = 1;
$newList->welcome_id = 43; // Optional. This is the Id of the mail you want to send as welcome email
$newList->unsubscribe_id = 52; // Optional. This is the Id of the mail you want to send when a user unsubscribes
$newList->color = '#3366ff'; // Optional. This is the color of the list
 
$listClass = new ListClass();
$listId = $listClass->save($newList); // This function will create the list and return the ID of the created list
```

{% endcode %}

### Get the lists

{% code lineNumbers="true" %}

```php
use AcyMailing\Classes\ListClass;

$listClass = new ListClass;
$allLists = $listClass->getAll();
 
// You can then do a foreach on this variable (which contains an array of objects) and use ->name
// You can get a specific list like this
 
$myList = $listClass->getOneById(34);
 
// Or multiple lists like this
 
$myLists = $listClass->getListsByIds([22, 48]);
```

{% endcode %}

### Delete a list

{% code lineNumbers="true" %}

```php
use AcyMailing\Classes\ListClass;

// This code will detach the list from your campaigns, delete the user subscriptions to that list then delete the list
 
$listClass = new ListClass();
$listClass->delete([43]); // You should replace 43 by the ID of the list you want to delete
```

{% endcode %}

## Subscriptions

### Subscribe or remove a user from one or several lists

{% code lineNumbers="true" %}

```php
use AcyMailing\Classes\UserClass;

$subscribe = [2,4,6]; // Id of the lists you want the user to be subscribed to (can be empty)
$unsubscribe = [1,3]; // Id of the lists you want the user to be unsubscribe from (can be empty)
$acyUserIds = [23]; // you can use the previous example code to get the user by its site user id or its email address
 
$userClass = new UserClass();
 
if (!empty($subscribe)) {
    // The last two parameters are are to make sure to send the welcome email 
    $userClass->subscribe($acyUserIds, $subscribe, true, true);
}
 
if (!empty($unsubscribe)) {
    $userClass->unsubscribe($acyUserIds, $unsubscribe);
}
```

{% endcode %}

## Campaigns

### Create a campaign

{% code lineNumbers="true" %}

```php
use AcyMailing\Classes\MailClass;
use AcyMailing\Classes\CampaignClass;

// Lists you want to attach the campaign to
$listIds = [3,5,8];
 
// We create the Campaign element that we will save in the database.
// You can use all fields from the database the same way we do it with subject and body.
 
$mail = new stdClass();
$mail->subject = 'your subject'; // Subject of your email
$mail->name = 'your campaign name'; // Name of the campaign
$mail->body = 'Hi folks, we have a big announcement...'; // Body of your email
$mail->bcc = 'example@test.com'; // BCC for your campaign
$mail->type = MailClass::TYPE_STANDARD; // Type of email
 
$mailClass = new MailClass();
$mailId = $mailClass->save($mail);
 
$campaign = new stdClass();
$campaign->draft = 1; // Create as a draft
$campaign->mail_id = $mailId;
$campaign->sending_type = CampaignClass::SENDING_TYPE_NOW; // Create a standard campaign
 
$campaignClass = new CampaignClass();
$campaignId = $campaignClass->save($campaign);
$campaignClass->manageListsToCampaign($listIds, $mailId);
```

{% endcode %}

### Sending a campaign to its lists

{% code lineNumbers="true" %}

```php
use AcyMailing\Classes\CampaignClass;

$campaignClass = new CampaignClass();
$nbQueuedEmails = $campaignClass->send($campaignId);
```

{% endcode %}

## Sending emails

### Insert an e-mail in the queue

{% code lineNumbers="true" %}

```php
use AcyMailing\Classes\QueueClass;
use AcyMailing\Classes\MailClass;

// The purpose of this code is to let AcyMailing send an e-mail to a specific user at a specific time.
// You just have to add an entry in the queue and AcyMailing will take care of the rest.
 
$acyUserId = 23;
$mailId = 45; // ID of the email you want to add in the queue
$sendDate = time(); //When do you want the e-mail to be sent to this user? you should specify a timestamp here (time() is the current time)
 
 // If you want to add the email in the queue only for one specific user
$queueClass = new QueueClass();
$queueClass->addQueue($acyUserId, $mailId, acym_date($sendDate, 'Y-m-d H:i', false));
 
// If you want to send the email to all the users subscribed to the list the email is attached to, you can use this:
$mailClass = new MailClass();
$mailToSend = $mailClass->getOneById($mailId);
$mailToSend->sending_date = acym_date($sendDate, 'Y-m-d H:i', false);
$mailToSend->parent_id = $mailId;
$mailToSend->sending_params = [''];
$queueClass->queue($mailToSend);
```

{% endcode %}

### Send an email to a single user

Sometimes you want to send a pre-saved email to a single user only...\
In that case you should not bother with the queue system and use this code (it will send the email ID 67 to the user "<user@example.com>"):

{% hint style="warning" %}
The email ID can be found in the xxxx\_acym\_mail table, this is NOT the campaign ID displayed on the campaigns listing
{% endhint %}

{% code lineNumbers="true" %}

```php
use AcyMailing\Helpers\MailerHelper;

$mailId = 67; // This is the mail ID, not the campaign ID. It is shown in a tooltip while hovering the campaign ID.
$userId = 28;

$mailer = new MailerHelper();
$mailer->report = true; // set it to true or false if you want Acy to display a confirmation message or not (message successfully sent to...)
$mailer->trackEmail = true; // set it to true or false if you want Acy to track the message or not (it will be inserted in the statistics table)
$mailer->addParam('var1', 'Value of the variable 1'); // Acy will automatically replace the tag {var1} by the value specified in the second parameter... you can use this function several times to replace tags in your email
$mailer->sendOne($mailId, $userId); // The first parameter is the ID of the email you want to send
```

{% endcode %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.acymailing.com/developers/custom-script-using-our-code.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
