[mod] different email sender for different category

Everything related to Hesk - helpdesk software

Moderator: mkoch227

Post Reply
alxik
Posts: 6
Joined: Mon Mar 11, 2024 2:57 pm

[mod] different email sender for different category

Post by alxik »

Hi guys,

Im here quite new, doing small changes to Hesk system, to get it working like we need, as we have different emails used for piping, found out that its be better to use same email addresses as category (so as email piping is routing customer email in different category in depending where customer sended it), then system email (ie, you got answer/new ticket) is sending also from same email which category was applied.
DISCLAIMER! Im not PHP-programmer, studied coding a long time ago in university, but code is working , so sharing it here, maybe it will be added to next version of HESK, if its good :) and english is not my primary language aswell :)

1) In SQL, additional row "sender" is needed to be added to "category" table

2) \hesk\inc\email_functions.inc.php: need to change 2 functions and also add $from_email to each function in files where its used (CTRL+F will save time):
2.1) hesk_notifyCustomer, add before // Format email subject and message:

Code: Select all

	// Mod: provide from email to system to send customer email with correct from email
	/* Get sender from category */
	$result = hesk_dbQuery("SELECT `sender` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` WHERE `id`='".intval($ticket['category'])."' LIMIT 1");

	/* If this category has been deleted use the default category with ID 1 */
	if (hesk_dbNumRows($result) != 1)
	{
		$result = hesk_dbQuery("SELECT `sender` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` WHERE `id`='1' LIMIT 1");
	}

	$from_email = hesk_dbFetchAssoc($result);
	// mod end.
change hesk_mail few lines below to:

Code: Select all

    hesk_mail($from_email['sender'], $ticket['email'], $subject, $message, $html_message, $ticket['trackid']); // Mod: add $from_email['sender']
2.2) change hesk_mail function to that (added $from_email variable, added check, if email was not empty or was empty, and changed mailer function to use from_email variable

Code: Select all

function hesk_mail($from_email, $to, $subject, $message, $html_message, $tracking_ID = null) // Mod: add from variable to end
{
    global $hesk_settings, $hesklang;

    // Demo mode
    if (defined('HESK_DEMO')) {
        return true;
    }

    // usleep(100);

    // Empty recipient?
    if ($to == '') {
        return true;
    }

    // Stop if we find anything suspicious in the headers
    if (preg_match("/\n|\r|\t|%0A|%0D|%08|%09/", $to . $subject)) {
        return false;
    }

    // Encode subject to UTF-8
    $subject = hesk_html_entity_decode($subject);

	// Mod: add check for from_email variable, is it available or use default email
	// Setup "name <email>" for headers
	if ($from_email == '') {
		if ($hesk_settings['noreply_name']) {
         $hesk_settings['from_name'] = $hesk_settings['noreply_name'];
		} else {
         $hesk_settings['from_name'] = $hesk_settings['noreply_mail'];
		}
		$from_email = $hesk_settings['noreply_mail']; // Mod: use standart email from settings if blank
	}
	else {
		if ($hesk_settings['noreply_name']) {
         $hesk_settings['from_name'] = $hesk_settings['noreply_name'];
		} else {
         $hesk_settings['from_name'] = $hesk_settings['noreply_mail'];
		}
	}

    // Uncomment for debugging
    #echo "<p>FROM: $from_email<br >TO: $to<br >SUBJECT: $subject<br >MSG: $message</p>";
    #return true;

    // Remove duplicate recipients
    $to_arr = array_unique(explode(',', $to));
    $to_arr = array_values($to_arr);

    // Start output buffering so that any errors don't break headers
    ob_start();

    try {
        $mailer = new PHPMailer(true);
        $mailer->XMailer = ' ';

        if ($hesk_settings['smtp']) {
            $mailer->SMTPDebug = SMTP::DEBUG_SERVER;
            $mailer->isSMTP();
            $mailer->Host = $hesk_settings['smtp_host_name'];
            $mailer->Port = $hesk_settings['smtp_host_port'];

            if (strlen($hesk_settings['smtp_user']) || strlen($hesk_settings['smtp_password']) || $hesk_settings['smtp_oauth_provider']) {
                $mailer->SMTPAuth = true;
                $mailer->Username = $hesk_settings['smtp_user'];

                if ($hesk_settings['smtp_conn_type'] == 'oauth') {
                    require_once(HESK_PATH . 'inc/oauth_functions.inc.php');
                    require_once(HESK_PATH . 'inc/mail/HeskOAuthTokenProvider.php');

                    $oauthTokenProvider = new \PHPMailer\PHPMailer\HeskOAuthTokenProvider();
                    $oauthTokenProvider->username = $hesk_settings['smtp_user'];
                    $oauthTokenProvider->provider = $hesk_settings['smtp_oauth_provider'];

                    $mailer->AuthType = 'XOAUTH2';
                    $mailer->setOAuth($oauthTokenProvider);
                } else {
                    $mailer->Password = hesk_htmlspecialchars_decode($hesk_settings['smtp_password']);
                }
            }

            $mailer->Timeout = $hesk_settings['smtp_timeout'];
            if ($hesk_settings['smtp_noval_cert']) {
                $mailer->SMTPOptions = array(
                    'ssl' => array(
                        'verify_peer' => false,
                        'verify_peer_name' => false,
                        'allow_self_signed' => true
                    )
                );
            }
            if ($hesk_settings['smtp_enc'] == 'ssl') {
                $mailer->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            } elseif ($hesk_settings['smtp_enc'] == 'tls') {
                $mailer->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            }
        }
		
		$mailer->setFrom($from_email, $hesk_settings['noreply_name']); // Mod: use custom from email
        $mailer->addReplyTo($from_email, $hesk_settings['noreply_name']); // Mod: use custom from email
		
        foreach ($to_arr as $to) {
            $mailer->addAddress($to);
        }
        $mailer->Subject = $subject;
        $mailer->CharSet = $hesklang['ENCODING'];

        // Save ticket ID in a custom header
        if ($tracking_ID !== null) {
            $mailer->addCustomHeader('X-Hesk-Tracking_ID', $tracking_ID);
        }

        // Do we auto-generate the AltBody from the HTML template?
        if ($hesk_settings['email_formatting'] == 2) {
            $mailer->msgHTML($html_message);
        } else {
            // HTML email?
            if ($hesk_settings['email_formatting']) {
                $mailer->isHTML();
            }

            // Body holds plaintext if we're not sending HTML
            $mailer->Body = $hesk_settings['email_formatting'] ?
                $html_message :
                $message;

            // Only include plain text in Alt if both HTML and plain text are being sent
            if ($hesk_settings['email_formatting'] == 3) {
                $mailer->AltBody = $message;
            }
        }
    } catch (Exception $e) {
        if ($hesk_settings['debug_mode']) {
            $error = $hesklang['cnsm'] . ' ' . $to . '<br /><br />' . $hesklang['error'] . ': ' . htmlspecialchars($mailer->ErrorInfo);
            if ($debug_log = ob_get_contents()) {
                $error .= '<br /><br /><textarea name="smtp_log" rows="10" cols="60">' . $debug_log . '</textarea>';
            }
            $_SESSION['HESK_2ND_NOTICE'] = true;
            $_SESSION['HESK_2ND_MESSAGE'] = $hesklang['esf'] . ' ' . $error;
        } else {
            $_SESSION['HESK_2ND_NOTICE'] = true;
            $_SESSION['HESK_2ND_MESSAGE'] = $hesklang['esf'] . ' ' . $hesklang['contact_webmsater'] . ' <a href="mailto:' . $hesk_settings['webmaster_mail'] . '">' . $hesk_settings['webmaster_mail'] . '</a>';
        }

        ob_end_clean();
        return false;
    }

    try {
        ob_start();
        $mailer->send();
        ob_end_clean();
    } catch (Exception $e) {
        if ($hesk_settings['debug_mode']) {
            $error = $hesklang['cnsm'] . ' ' . $to . '<br /><br />' . $hesklang['error'] . ': ' . htmlspecialchars($mailer->ErrorInfo);
            if ($debug_log = ob_get_contents()) {
                $error .= '<br /><br /><textarea name="smtp_log" rows="10" cols="60">' . $debug_log . '</textarea>';
            }
            $_SESSION['HESK_2ND_NOTICE'] = true;
            $_SESSION['HESK_2ND_MESSAGE'] = $hesklang['esf'] . ' ' . $error;
        } else {
            $_SESSION['HESK_2ND_NOTICE'] = true;
            $_SESSION['HESK_2ND_MESSAGE'] = $hesklang['esf'] . ' ' . $hesklang['contact_webmsater'] . ' <a href="mailto:' . $hesk_settings['webmaster_mail'] . '">' . $hesk_settings['webmaster_mail'] . '</a>';
        }

        ob_end_clean();
        return false;
    }

    ob_end_clean();
    return true;
} // END hesk_mail()
2.3) changes to other functions files:
before hesk_mail add:

Code: Select all

	// mod add additional variable for custom from email - here we can use standart system email
	$from_email = $hesk_settings['noreply_mail'];
and ADD to hesk_mail function "$from_email" variable in files:
\hesk\index.php line~ 538
\hesk\inc\mfa_functions.inc.php line~58
\hesk\admin\admin_ticket.php line~487
\hesk\admin\mail.php line~367
\hesk\admin\password.php line~165

3) changes to \hesk\admin\manage_category.php:
line ~39 change $category to:

Code: Select all

// Populate default values for creation
$category = array(
    'id' => 0,
    'name' => '',
    'priority' => $priorities['low']['id'],
    'autoassign' => $hesk_settings['autoassign'],
    'autoassign_config' => null,
    'type' => 0,
    'default_due_date_unit' => 'day',
    'default_due_date_amount' => '',
	'sender' => $hesk_settings['noreply_mail'] // MOD: add default email cat for category creation
);
line ~60, change to:

Code: Select all

    // Fetch category information
    $res = hesk_dbQuery("SELECT * FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` WHERE `id` = ".intval(hesk_REQUEST('id')));
    if ($row = hesk_dbFetchAssoc($res)) {
        $category['id'] = $row['id'];
        $category['name'] = $row['name'];
        $category['priority'] = intval($row['priority']);
        $category['autoassign'] = intval($row['autoassign']);
        $category['autoassign_config'] = $row['autoassign_config'];
        $category['type'] = intval($row['type']);
        $category['default_due_date_amount'] = $row['default_due_date_amount'] ? intval($row['default_due_date_amount']) : '';
        $category['default_due_date_unit'] = $row['default_due_date_unit'];
	$category['sender'] = $row['sender']; // add default sender output
    }
line ~110 add:

Code: Select all

			<div class="form-group">
                <label for="sender">
                    <?php echo $hesklang['emlsend2']; ?>: <span class="important">*</span>
                </label>
                <input type="text"
                       name="sender"
                       class="form-control"
                       id="sender"
                       maxlength="255"
                       value="<?php echo stripslashes($category['sender']); ?>">
            </div>
search for:

Code: Select all

/* Category name */
    $category['name'] = hesk_input(hesk_POST('name'));
and add after that:

Code: Select all

    /* Mod: Category sender */
    $category['sender'] = hesk_input(hesk_POST('sender'));
search for

Code: Select all

    // Prepare autoassign config for saving
    $sql_friendly_autoassign_config = $category['autoassign_config'] === null ? 'NULL' : "'".hesk_dbEscape($category['autoassign_config'])."'";
    $sql_friendly_due_date_amount = $category['default_due_date_amount'] === '' ? 'NULL' : $category['default_due_date_amount'];
    $sql_friendly_due_date_unit = $sql_friendly_due_date_amount === 'NULL' ? 'NULL' : "'".hesk_dbEscape($category['default_due_date_unit'])."'";
    if ($category['id'] === 0) {
        hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` (`name`,`cat_order`,`autoassign`,
                      `autoassign_config`,`type`, `priority`,`default_due_date_amount`,`default_due_date_unit`,`sender`) 
                    VALUES ('".hesk_dbEscape($category['name'])."',
                            '".intval($my_order)."',
                            '".intval($category['autoassign'])."',
                            ".$sql_friendly_autoassign_config.",
                            '".intval($category['type'])."',
                            '".intval($category['priority'])."',
                            ".$sql_friendly_due_date_amount.",
                            ".$sql_friendly_due_date_unit.");
        $_SESSION['selcat2'] = hesk_dbInsertID();
    } else {
        hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."categories`
                      SET `name` = '".hesk_dbEscape($category['name'])."',
                          `autoassign` = '".intval($category['autoassign'])."',
                          `autoassign_config` = {$sql_friendly_autoassign_config},
                          `type` = '".intval($category['type'])."',
                          `priority` = '".intval($category['priority'])."',
                          `default_due_date_amount` = {$sql_friendly_due_date_amount},
                          `default_due_date_unit` = {$sql_friendly_due_date_unit}
                      WHERE `id` = ".intval($category['id'])); 
        $_SESSION['selcat2'] = $category['id'];
    }
and change to (2 lines where sender variable added

Code: Select all

    // Prepare autoassign config for saving
    $sql_friendly_autoassign_config = $category['autoassign_config'] === null ? 'NULL' : "'".hesk_dbEscape($category['autoassign_config'])."'";
    $sql_friendly_due_date_amount = $category['default_due_date_amount'] === '' ? 'NULL' : $category['default_due_date_amount'];
    $sql_friendly_due_date_unit = $sql_friendly_due_date_amount === 'NULL' ? 'NULL' : "'".hesk_dbEscape($category['default_due_date_unit'])."'";
    if ($category['id'] === 0) {
        hesk_dbQuery("INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."categories` (`name`,`cat_order`,`autoassign`,
                      `autoassign_config`,`type`, `priority`,`default_due_date_amount`,`default_due_date_unit`,`sender`) 
                    VALUES ('".hesk_dbEscape($category['name'])."',
                            '".intval($my_order)."',
                            '".intval($category['autoassign'])."',
                            ".$sql_friendly_autoassign_config.",
                            '".intval($category['type'])."',
                            '".intval($category['priority'])."',
                            ".$sql_friendly_due_date_amount.",
                            ".$sql_friendly_due_date_unit.",
							'".hesk_dbEscape($category['sender'])."')"); // MOD: add sender to query
        $_SESSION['selcat2'] = hesk_dbInsertID();
    } else {
        hesk_dbQuery("UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."categories`
                      SET `name` = '".hesk_dbEscape($category['name'])."',
                          `autoassign` = '".intval($category['autoassign'])."',
                          `autoassign_config` = {$sql_friendly_autoassign_config},
                          `type` = '".intval($category['type'])."',
                          `priority` = '".intval($category['priority'])."',
                          `default_due_date_amount` = {$sql_friendly_due_date_amount},
                          `default_due_date_unit` = {$sql_friendly_due_date_unit},
						  `sender` = '".hesk_dbEscape($category['sender'])."' 
                      WHERE `id` = ".intval($category['id'])); // MOD: add sender to query
        $_SESSION['selcat2'] = $category['id'];
    }
Hope, that everything is clear, and if will be helpfull :)
Last edited by alxik on Mon Apr 08, 2024 11:56 am, edited 1 time in total.
Klemen
Site Admin
Posts: 10135
Joined: Fri Feb 11, 2005 4:04 pm

Re: [mod] different email sender for different category

Post by Klemen »

Thank you for sharing!

This might get a bit tricky (complicated) when you use a different SMTP server or authentication parameters for each sender. But sure, on a simple local set up, this works well!
Klemen, creator of HESK and PHPJunkyardWas this helpful? You can buy me a drink here Image

Image You should follow me on Twitter here

Help desk software | Cloud help desk | Guestbook | Link manager | Click counter | more PHP Scripts ...

Also browse for php hosting companies, read php books, find php resources and use webmaster tools
alxik
Posts: 6
Joined: Mon Mar 11, 2024 2:57 pm

Re: [mod] different email sender for different category

Post by alxik »

Hi,

At the "test" enviroment, im using different domains on same hosting to send emails depending on category used for ticket (but all of them are allowed to send email via SPF note) and PHPMailer doing the job without any issue.. All the emails are delivering to inbox..

But yes, it will work only with PHPMailer as i understood, using SMTP will not work..
Post Reply