Email (Imap) Addon
Moderator: mkoch227
-
- Posts: 4
- Joined: Wed Jan 16, 2008 12:40 am
-
- Posts: 48
- Joined: Wed Jun 16, 2010 2:52 pm
exchange server help
Hi there,
we use an internal exchange server and i keep getting cannot connect to the mailbox errors, however when i telnet the server with the details which are listed in the imap.php script it works and i can login but the imap.php wont login.
ANy ideas?
we use an internal exchange server and i keep getting cannot connect to the mailbox errors, however when i telnet the server with the details which are listed in the imap.php script it works and i can login but the imap.php wont login.
ANy ideas?
Re: Email (Imap) Addon
I have a Problem !
The Addon works perfect, but only with ONE mail
and it dosnt delet the first mail. So at the next call it will take the first mail again
in to hesk.
whats going wrong with it ?
here my code:
Hope anyone can help.
The Addon works perfect, but only with ONE mail
and it dosnt delet the first mail. So at the next call it will take the first mail again
in to hesk.
whats going wrong with it ?
here my code:
Code: Select all
(PRIVATE)
$delete = "Y"; // if delete is Y then processed mail will be deleted
$debug = 1; // Display Notices about in/outgoing emails 1 = on | 0 = off
$category = 1; // Hesk Category ID to trow all emails in
$priority = 1; // 3=Low 2=Medium 1=High
/////////////////////////////////////////////////////////////////////////////////////////////
define('IN_SCRIPT',1);
define('HESK_PATH','');
if (!function_exists('imap_open')) die("IMAP functions are not available.");
if ($debug==1) error_reporting(E_ALL); else error_reporting(0);
// Get all the required files and functions
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
// Connect to database
require(HESK_PATH . 'inc/database.inc.php');
hesk_dbConnect() or hesk_error("$hesklang[cant_connect_db] $hesklang[contact_webmsater] $hesk_settings[webmaster_mail]!");
// Functions
function getHeader($msgStream, $msgNumber) {
// strips the mail header and places everything in an array .. like from name, from email, date and subject
$mailheader = imap_headerinfo($msgStream, $msgNumber);
$headerArray = array();
$headerArray[0] = $mailheader->subject;
$from = $mailheader->from;
foreach ($from as $id => $object) {
$headerArray[1] = $object->personal; // from personal
$headerArray[2] = $object->mailbox . "@" . $object->host; // from address
}
$headerArray[3] = $mailheader->Date;
return $headerArray;
}
$host = "{".$server.":143"."}"."INBOX";
//connect to inbox and check for new msgs
$msgStream = imap_open($host, $user, $password) or die("<br><br><b>Error: Can't connect to mailbox</b>");
$check = imap_mailboxmsginfo($msgStream);
$number = $check->Nmsgs;
if ($debug==1) {
echo "<b>Notices (".date("H:i:s")."):</b><br>";
if ($number>0) {
echo "<b> - ".$number." email(s)</b><br>";
} else {
echo "<b> - No Email in Inbox</b><br>";
}
$mbox = imap_open("{".$server.":143}", $user, $password);
echo "<h1>Mailboxes</h1>\n";
$folders = imap_listmailbox($mbox, "{".$server."}", "*");
if ($folders == false) {
echo "imap_listmailbox failed<br />\n";
} else {
foreach ($folders as $val) {
echo $val . "<br />\n";
}
}
echo "<h1>Headers in INBOX</h1>\n";
$headers = imap_headers($mbox);
if ($headers == false) {
echo "imap_headers failed<br />\n";
} else {
foreach ($headers as $val) {
echo $val . "<br />\n";
}
}
imap_close($mbox);
}
$msgStream = imap_open($host, $user, $password) or die("<br><br><b>Error: Can't connect to mailbox</b>");
$msgNumber = "1";
while ($msgNumber <= $number) {
$headerArray = getHeader($msgStream, $msgNumber);
$message = htmlentities(addslashes(imap_body($msgStream, $msgNumber)));
$subject = htmlentities(addslashes($headerArray[0]));
$name = htmlentities(addslashes($headerArray[1]));
$email = htmlentities($headerArray[2]);
$date = htmlentities($headerArray[3]);
// Generate tracking ID
$useChars='AEUYBDGHJLMNPQRSTVWXZ123456789';
$trackingID = $useChars{mt_rand(0,29)};
for($i=1;$i<10;$i++) $trackingID .= $useChars{mt_rand(0,29)};
$trackingURL=$hesk_settings['hesk_url'].'/ticket.php?track='.$trackingID;
// End Generate tracking ID
$sql = "
INSERT INTO `hesk_tickets` (
`trackid`,`name`,`email`,`category`,`priority`,`subject`,`message`,`dt`,`lastchange`,`ip`,`status`,`attachments`,`custom1`,`custom2`,`custom3`,`custom4`,`custom5`
)
VALUES (
'$trackingID','$name','$email','$category','$priority','$subject','$message',NOW(),NOW(),'email','0','','','','','',''
)
";
$result = hesk_dbQuery($sql) or hesk_error("$hesklang[cant_sql]: $sql</p><p>$hesklang[mysql_said]:<br>".mysql_error()."</p><p>$hesklang[contact_webmsater] $hesk_settings[webmaster_mail]");
// Get e-mail message for customer
$fp=fopen('language/'.$hesk_settings['languages'][$hesk_settings['language']]['folder'].'/emails/new_ticket.txt','r');
$message=fread($fp,filesize('language/'.$hesk_settings['languages'][$hesk_settings['language']]['folder'].'/emails/new_ticket.txt'));
fclose($fp);
$message=str_replace('%%NAME%%',$name,$message);
$message=str_replace('%%SUBJECT%%',$subject,$message);
$message=str_replace('%%TRACK_ID%%',$trackingID,$message);
$message=str_replace('%%TRACK_URL%%',$trackingURL,$message);
$message=str_replace('%%SITE_TITLE%%',$hesk_settings['site_title'] ,$message);
$message=str_replace('%%SITE_URL%%',$hesk_settings['site_url'] ,$message);
// Send e-mail
$headers="From: $hesk_settings[noreply_mail]\n";
$headers.="Reply-to: $hesk_settings[noreply_mail]\n";
@mail($email,$hesklang['ticket_received'],$message,$headers);
// Need to notify any admins?
$admins=array();
$sql = "SELECT `email`,`isadmin`,`categories` FROM `hesk_users` WHERE `notify`='1'";
$result = hesk_dbQuery($sql) or hesk_error("$hesklang[cant_sql]: $sql</p><p>$hesklang[mysql_said]:<br>".mysql_error()."</p><p>$hesklang[contact_webmsater] $hesk_settings[webmaster_mail]");
while ($myuser=hesk_dbFetchAssoc($result)) {
// Is this an administrator?
if ($myuser['isadmin']) {$admins[]=$myuser['email']; continue;}
// Not admin, is he allowed this category?
$cat=substr($myuser['categories'], 0, -1);
$myuser['categories']=explode(',',$cat);
if (in_array($category,$myuser['categories'])) {
$admins[]=$myuser['email']; continue;
}
}
if (count($admins)>0) {
$trackingURL_admin=$hesk_settings['hesk_url'].'/admin/admin_ticket.php?track='.$trackingID;
// Get e-mail message for customer
$fp=fopen('language/'.$hesk_settings['languages'][$hesk_settings['language']]['folder'].'/emails/new_ticket_staff.txt','r');
$message=fread($fp,filesize('language/'.$hesk_settings['languages'][$hesk_settings['language']]['folder'].'/emails/new_ticket_staff.txt'));
fclose($fp);
$message=str_replace('%%NAME%%',$name,$message);
$message=str_replace('%%SUBJECT%%',$subject,$message);
$message=str_replace('%%TRACK_ID%%',$trackingID,$message);
$message=str_replace('%%TRACK_URL%%',$trackingURL_admin,$message);
$message=str_replace('%%SITE_TITLE%%',$hesk_settings['site_title'] ,$message);
$message=str_replace('%%SITE_URL%%',$hesk_settings['site_url'] ,$message);
// Send e-mail to staff
$email=implode(',',$admins);
$headers="From: $hesk_settings[noreply_mail]\n";
$headers.="Reply-to: $hesk_settings[noreply_mail]\n";
@mail($email,$hesklang['new_ticket_submitted'],$message,$headers);
} // End if
if ($delete == "Y") imap_delete($msgStream, $msgNumber); // mark the current message for deletion
$msgNumber++;
}
if ($delete == "Y") imap_expunge($msgStream); // delete all messages marked for deletion
imap_close($msgStream);
?>
Re: Email (Imap) Addon
OK I was getting problems where it was only entering 1 mail into the system and throwing a MySQL error. So I checkout out the code and a column name is incorrect, I don't know if there is a version issue.
Anyway, new code is here ...
Anyway, new code is here ...
Code: Select all
<?php
////////////////////////////////////////// Settings //////////////////////////////////////////
$server = "mail.mailserver.com"; //mail server.
$user = "username"; // Mail Username
$password = "password"; // Mail Password
$delete = "Y"; // if delete is Y then processed mail will be deleted
$debug = 0; // Display Notices about in/outgoing emails 1 = on | 0 = off
$category = 1; // Hesk Category ID to trow all emails in
$priority = 3; // 3=Low 2=Medium 1=High
/////////////////////////////////////////////////////////////////////////////////////////////
define('IN_SCRIPT',1);
define('HESK_PATH','');
if (!function_exists('imap_open')) die("IMAP functions are not available.");
if ($debug==1) error_reporting(E_ALL); else error_reporting(0);
// Get all the required files and functions
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
// Connect to database
require(HESK_PATH . 'inc/database.inc.php');
hesk_dbConnect() or hesk_error("$hesklang[cant_connect_db] $hesklang[contact_webmsater] $hesk_settings[webmaster_mail]!");
$host = "{".$server.":143/imap/novalidate-cert}"."INBOX";
$msgStream = imap_open($host, $user, $password) or die("<br><br><b>Error: Can't connect to mailbox</b>");
$check = imap_mailboxmsginfo($msgStream);
$number = $check->Nmsgs;
$msgNumber = "1";
if (!$number) echo "<h1>No hay nuevos mensajes</h1>";
while ($msgNumber <= $number) {
list($subject, $name, $email, $date, $message, $trackingID) = getMessage($msgStream, $msgNumber);
if (!$trackingID) {
$trackingID = createNewTicket($subject, $name, $email, $date, $message);
} else {
createNewReply($subject, $name, $email, $date, $message, $trackingID);
}
if ($delete == "Y") imap_delete($msgStream, $msgNumber); // mark the current message for deletion
$msgNumber++;
}
if ($delete == "Y") imap_expunge($msgStream); // delete all messages marked for deletion
imap_close($msgStream);
// Functions
function getHeader($msgStream, $msgNumber) {
// strips the mail header and places everything in an array .. like from name, from email, date and subject
$mailheader = imap_headerinfo($msgStream, $msgNumber);
$headerArray = array();
$headerArray[0] = $mailheader->subject;
$from = $mailheader->from;
foreach ($from as $id => $object) {
$headerArray[1] = $object->personal; // from personal
$headerArray[2] = $object->mailbox . "@" . $object->host; // from address
}
$headerArray[3] = $mailheader->Date;
return $headerArray;
}
function extractPlain($msgStream, $msgNumber, $st = null, $num = "")
{
// pull the plain text for message $n
if (!$st) $st = imap_fetchstructure($msgStream, $msgNumber);
if (!empty($st->parts)) {
for ($i = 0, $j = count($st->parts); $i < $j; $i++) {
$part = $st->parts[$i];
if ($part->subtype == 'PLAIN') {
return imap_fetchbody($msgStream, $msgNumber, $num.($i+1));
}
if (!empty($part->parts)) {
$body = extractPlain($msgStream, $msgNumber, $part, ($i+1).".");
if ($body) return $body;
}
}
} else {
return imap_body($msgStream, $msgNumber);
}
}
function getMessage($msgStream, $msgNumber)
{
// pull the plain text for message $n
$message = nl2br(extractPlain($msgStream, $msgNumber));
$headerArray = getHeader($msgStream, $msgNumber);
$subject = htmlentities(addslashes($headerArray[0]));
$name = htmlentities(addslashes($headerArray[1]));
$email = htmlentities($headerArray[2]);
$date = htmlentities($headerArray[3]);
$txt = "";
if (preg_match("/- TrackingID: (.*)/", $subject, $matches)) {
$trackingID = $matches[1];
}
foreach (imap_mime_header_decode($name) as $item) $txt .= $item->text;
$name = $txt;
return array($subject, $name, $email, $date, $message, $trackingID);
}
function generateTrackingID()
{
// Generate tracking ID
$useChars='AEUYBDGHJLMNPQRSTVWXZ123456789';
$trackingID = $useChars{mt_rand(0,29)};
for($i=1;$i<10;$i++) $trackingID .= $useChars{mt_rand(0,29)};
return $trackingID;
}
function createNewTicket($subject, $name, $email, $date, $message)
{
global $category, $priority, $hesk_settings, $hesklang;
$trackingID = generateTrackingID();
$trackingURL = $hesk_settings['hesk_url'].'/ticket.php?track='.$trackingID;
$sql = "
INSERT INTO `hesk_tickets` (
`trackid`,`name`,`email`,`category`,`priority`,`subject`,`message`,`dt`,`lastchange`,`ip`,`status`,`attachments`,`custom1`,`custom2`,`custom3`,`custom4`,`custom5`
)
VALUES (
'$trackingID','$name','$email','$category','$priority','$subject','$message',NOW(),NOW(),'email','0','','','','','',''
)";
$result = hesk_dbQuery($sql);
/* Get e-mail message for customer */
$msg = hesk_getEmailMessage('new_ticket');
$msg = str_replace('%%NAME%%',hesk_msgToPlain($name,1),$msg);
$msg = str_replace('%%SUBJECT%%',hesk_msgToPlain($subject,1),$msg);
$msg = str_replace('%%TRACK_ID%%',$trackingID,$msg);
$msg = str_replace('%%TRACK_URL%%',$trackingURL,$msg);
$msg = str_replace('%%SITE_TITLE%%',$hesk_settings['site_title'],$msg);
$msg = str_replace('%%SITE_URL%%',$hesk_settings['site_url'],$msg);
$msg = str_replace('%%MESSAGE%%',hesk_msgToPlain($message,1),$msg);
/* Send e-mail */
$headers = "From: $hesk_settings[noreply_mail]\n";
$headers.= "Reply-to: $hesk_settings[noreply_mail]\n";
$headers.= "Return-Path: $hesk_settings[webmaster_mail]\n";
$headers.= "Content-type: text/plain; charset=".$hesklang['ENCODING'];
@mail($email,$hesklang['ticket_received']." - TrackingID: $trackingID",$msg,$headers);
/* Need to notify any admins? */
$admins=array();
$sql = "SELECT `email`,`isadmin`,`categories` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `notify_new_unassigned`='1'";
$result = hesk_dbQuery($sql);
while ($myuser=hesk_dbFetchAssoc($result))
{
/* Is this an administrator? */
if ($myuser['isadmin']) {$admins[]=$myuser['email']; continue;}
/* Not admin, is he allowed this category? */
$cat=substr($myuser['categories'], 0, -1);
$myuser['categories']=explode(',',$cat);
if (in_array($category,$myuser['categories']))
{
$admins[]=$myuser['email']; continue;
}
}
if (count($admins)>0)
{
$trackingURL_admin=$hesk_settings['hesk_url'].'/admin/admin_ticket.php?track='.$trackingID;
$msg = hesk_getEmailMessage('new_ticket_staff');
$msg = str_replace('%%NAME%%',hesk_msgToPlain($name,1),$msg);
$msg = str_replace('%%SUBJECT%%',hesk_msgToPlain($subject,1),$msg);
$msg = str_replace('%%TRACK_ID%%',$trackingID,$msg);
$msg = str_replace('%%TRACK_URL%%',$trackingURL_admin,$msg);
$msg = str_replace('%%SITE_TITLE%%',$hesk_settings['site_title'],$msg);
$msg = str_replace('%%SITE_URL%%',$hesk_settings['site_url'],$msg);
$msg = str_replace('%%MESSAGE%%',hesk_msgToPlain($message,1),$msg);
/* Send e-mail to staff */
$email=implode(',',$admins);
$headers = "From: $hesk_settings[noreply_mail]\n";
$headers.= "Reply-to: $hesk_settings[noreply_mail]\n";
$headers.= "Return-Path: $hesk_settings[webmaster_mail]\n";
$headers.= "Content-type: text/plain; charset=".$hesklang['ENCODING'];
@mail($email,$hesklang['new_ticket_submitted'],$msg,$headers);
}
echo "<h3>Creando nuevo ticked: $trackingID</h3>";
}
function createNewReply($subject, $name, $email, $date, $message, $trackingID)
{
global $hesk_settings, $hesklang;
$trackingID = trim($trackingID);
$trackingURL = $hesk_settings['hesk_url'].'/ticket.php?track='.$trackingID;
$sql = "SELECT id FROM `hesk_tickets` WHERE trackid='$trackingID'";
$result = hesk_dbQuery($sql) or hesk_error("$hesklang[cant_sql]: $sql</p><p>$hesklang[mysql_said]:<br>".mysql_error()."</p><p>$hesklang[contact_webmsater] $hesk_settings[webmaster_mail]");
$data = hesk_dbFetchAssoc($result);
$replyto = $data["id"];
/* Make sure the ticket is open */
$sql = "UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `status`='1',`lastreplier`='0',`lastchange`=NOW() WHERE `id`=".hesk_dbEscape($replyto)." LIMIT 1";
$result = hesk_dbQuery($sql);
/* Add reply */
$sql = "
INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` (
`replyto`,`name`,`message`,`dt`
)
VALUES (
'".hesk_dbEscape($replyto)."',
'".hesk_dbEscape($name)."',
'".hesk_dbEscape($message)."',
NOW()
)
";
$result = hesk_dbQuery($sql);
/* Need to notify any admins? */
$admins=array();
$sql = "SELECT `email`,`isadmin`,`categories` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `notify`='1'";
$result = hesk_dbQuery($sql);
while ($myuser=hesk_dbFetchAssoc($result))
{
/* Is this an administrator? */
if ($myuser['isadmin']) {$admins[]=$myuser['email']; continue;}
/* Not admin, is he allowed this category? */
$cat=substr($myuser['categories'], 0, -1);
$myuser['categories']=explode(",",$cat);
if (in_array($category,$myuser['categories']))
{
$admins[]=$myuser['email']; continue;
}
}
if (count($admins)>0)
{
/* Prepare ticket message for the e-mail */
$message = hesk_msgToPlain($message,1);
$trackingURL_admin = $hesk_settings['hesk_url'].'/admin/admin_ticket.php?track='.$trackingID;
$msg = hesk_getEmailMessage('new_reply_by_customer');
$msg = str_replace('%%NAME%%',$name,$msg);
$msg = str_replace('%%SUBJECT%%',$subject,$msg);
$msg = str_replace('%%TRACK_ID%%',$trackingID,$msg);
$msg = str_replace('%%TRACK_URL%%',$trackingURL_admin,$msg);
$msg = str_replace('%%SITE_TITLE%%',$hesk_settings['site_title'],$msg);
$msg = str_replace('%%SITE_URL%%',$hesk_settings['site_url'],$msg);
$msg = str_replace('%%MESSAGE%%',$message,$msg);
/* Send e-mail to staff */
$email=implode(',',$admins);
$headers = "From: $hesk_settings[noreply_mail]\n";
$headers.= "Reply-to: $hesk_settings[noreply_mail]\n";
$headers.= "Return-Path: $hesk_settings[webmaster_mail]\n";
$headers.= "Content-type: text/plain; charset=".$hesklang['ENCODING'];
@mail($email,$hesklang['new_reply_ticket'],$msg,$headers);
}
echo "<h3>Creando respuesta para: $trackingID</h3>";
}
Re: Email (Imap) Addon
Somebody know how to implement Imap? For connecting to a Exchange box?
Re: Email (Imap) Addon
The Gmail fix:
/*
$host = "{".$server.":143/imap/novalidate-cert}"."INBOX";
*/
$host = "{".$server.":993/imap/ssl/novalidate-cert}"."INBOX";
Other Question,
The email to the customer and staff doesent contain the tracking number, and extra info, what could be the problem, why it issent copyed into the mail?
attributed that doesent work:
1. %%TRACK_URL%%
2. %%TRACK_ID%%
3. %%NAME%%
4. %%MESSAGE%%
/*
$host = "{".$server.":143/imap/novalidate-cert}"."INBOX";
*/
$host = "{".$server.":993/imap/ssl/novalidate-cert}"."INBOX";
Other Question,
The email to the customer and staff doesent contain the tracking number, and extra info, what could be the problem, why it issent copyed into the mail?
attributed that doesent work:
1. %%TRACK_URL%%
2. %%TRACK_ID%%
3. %%NAME%%
4. %%MESSAGE%%
Re: Email (Imap) Addon
I am experiencing the exact same issue regarding the e-mail variables. Anybody got a fix yet?lupolo wrote:The Gmail fix:
/*
$host = "{".$server.":143/imap/novalidate-cert}"."INBOX";
*/
$host = "{".$server.":993/imap/ssl/novalidate-cert}"."INBOX";
Other Question,
The email to the customer and staff doesent contain the tracking number, and extra info, what could be the problem, why it issent copyed into the mail?
attributed that doesent work:
1. %%TRACK_URL%%
2. %%TRACK_ID%%
3. %%NAME%%
4. %%MESSAGE%%
Re: exchange server help
ruffmeister wrote:Hi there,
we use an internal exchange server and i keep getting cannot connect to the mailbox errors, however when i telnet the server with the details which are listed in the imap.php script it works and i can login but the imap.php wont login.
ANy ideas?
I also have this issue. I might add that our exchange server uses SSL connections... Any help would be appreciated.
Thanks
Re: Email (Imap) Addon
also trying to connect to exchange 2003 still with no luck:
http://php.net/manual/en/function.imap-open.php
How do i remove the html from a mail before storing it into the Hesk Database?
Working script for Gmail and Hesk 2.3:
knowed problems:
- Email doesen't contain a valid tracking ID and URL, exept the subject
- Html emails
http://php.net/manual/en/function.imap-open.php
How do i remove the html from a mail before storing it into the Hesk Database?
Working script for Gmail and Hesk 2.3:
knowed problems:
- Email doesen't contain a valid tracking ID and URL, exept the subject
- Html emails
Code: Select all
<?php
////////////////////////////////////////// Settings //////////////////////////////////////////
$server = "imap.gmail.com"; // mail server.
$user = "xxxxxxxx@gmail.com"; // Mail Username
$password = "xxxxxxxx"; // Mail Password
$delete = "Y"; // if delete is Y then processed mail will be deleted
$debug = "1"; // Display Notices about in/outgoing emails 1 = on | 0 = off
$category = "19"; // Hesk Category ID to trow all emails in
$priority = "3"; // 3=Low 2=Medium 1=High
/////////////////////////////////////////////////////////////////////////////////////////////
define('IN_SCRIPT',1);
define('HESK_PATH','');
if (!function_exists('imap_open')) die("IMAP functions are not available.");
if ($debug==1) error_reporting(E_ALL); else error_reporting(0);
// Get all the required files and functions
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/email_functions.inc.php');
// Connect to database
require(HESK_PATH . 'inc/database.inc.php');
hesk_dbConnect() or hesk_error("$hesklang[cant_connect_db] $hesklang[contact_webmsater] $hesk_settings[webmaster_mail]!");
$host = "{".$server.":993/imap/ssl/novalidate-cert}"."INBOX";
$msgStream = imap_open($host, $user, $password) or die("<br><br><b>Error: Can't connect to mailbox</b>");
$check = imap_mailboxmsginfo($msgStream);
$number = $check->Nmsgs;
$msgNumber = "1";
if (!$number) echo "<h1>No hay nuevos mensajes</h1>";
while ($msgNumber <= $number) {
list($subject, $name, $email, $date, $message, $trackingID) = getMessage($msgStream, $msgNumber);
if (!$trackingID) {
$trackingID = createNewTicket($subject, $name, $email, $date, $message);
} else {
createNewReply($subject, $name, $email, $date, $message, $trackingID);
}
if ($delete == "Y") imap_delete($msgStream, $msgNumber); // mark the current message for deletion
$msgNumber++;
}
if ($delete == "Y") imap_expunge($msgStream); // delete all messages marked for deletion
imap_close($msgStream);
// Functions
function getHeader($msgStream, $msgNumber) {
// strips the mail header and places everything in an array .. like from name, from email, date and subject
$mailheader = imap_headerinfo($msgStream, $msgNumber);
$headerArray = array();
$headerArray[0] = $mailheader->subject;
$from = $mailheader->from;
foreach ($from as $id => $object) {
$headerArray[1] = $object->personal; // from personal
$headerArray[2] = $object->mailbox . "@" . $object->host; // from address
}
$headerArray[3] = $mailheader->Date;
return $headerArray;
}
function extractPlain($msgStream, $msgNumber, $st = null, $num = "")
{
// pull the plain text for message $n
if (!$st) $st = imap_fetchstructure($msgStream, $msgNumber);
if (!empty($st->parts)) {
for ($i = 0, $j = count($st->parts); $i < $j; $i++) {
$part = $st->parts[$i];
if ($part->subtype == 'PLAIN') {
return imap_fetchbody($msgStream, $msgNumber, $num.($i+1));
}
if (!empty($part->parts)) {
$body = extractPlain($msgStream, $msgNumber, $part, ($i+1).".");
if ($body) return $body;
}
}
} else {
return imap_body($msgStream, $msgNumber);
}
}
function getMessage($msgStream, $msgNumber)
{
// pull the plain text for message $n
$message = nl2br(extractPlain($msgStream, $msgNumber));
$headerArray = getHeader($msgStream, $msgNumber);
$subject = htmlentities(addslashes($headerArray[0]));
$name = htmlentities(addslashes($headerArray[1]));
$email = htmlentities($headerArray[2]);
$date = htmlentities($headerArray[3]);
$txt = "";
if (preg_match("/- TrackingID: (.*)/", $subject, $matches)) {
$trackingID = $matches[1];
}
foreach (imap_mime_header_decode($name) as $item) $txt .= $item->text;
$name = $txt;
return array($subject, $name, $email, $date, $message, $trackingID);
}
function generateTrackingID()
{
// Generate tracking ID
$useChars='AEUYBDGHJLMNPQRSTVWXZ123456789';
$trackingID = $useChars{mt_rand(0,29)};
for($i=1;$i<10;$i++) $trackingID .= $useChars{mt_rand(0,29)};
return $trackingID;
}
function createNewTicket($subject, $name, $email, $date, $message)
{
global $category, $priority, $hesk_settings, $hesklang;
$trackingID = generateTrackingID();
$trackingURL = $hesk_settings['hesk_url'].'/ticket.php?track='.$trackingID;
if (get_magic_quotes_gpc()) {$message = stripslashes($message);};
$sql = "INSERT INTO `hesk_tickets` (`trackid`,`name`,`email`,`category`,`priority`,`subject`,`message`,`dt`,`lastchange`,`ip`,`status`,`attachments`,`custom1`,`custom2`,`custom3`,`custom4`,`custom5`) VALUES ('$trackingID','$name','$email','$category','$priority','$subject','".mysql_real_escape_string($message)."',NOW(),NOW(),'email','0','','','','','','')";
$result = hesk_dbQuery($sql);
/* Get e-mail message for customer */
$msg = hesk_getEmailMessage('new_ticket');
$msg = str_replace('%%NAME%%',hesk_msgToPlain($name,1),$msg);
$msg = str_replace('%%SUBJECT%%',hesk_msgToPlain($subject,1),$msg);
$msg = str_replace('%%TRACK_ID%%',$trackingID,$msg);
$msg = str_replace('%%TRACK_URL%%',$trackingURL,$msg);
$msg = str_replace('%%SITE_TITLE%%',$hesk_settings['site_title'],$msg);
$msg = str_replace('%%SITE_URL%%',$hesk_settings['site_url'],$msg);
$msg = str_replace('%%MESSAGE%%',hesk_msgToPlain($message,1),$msg);
/* Send e-mail */
$headers = "From: $hesk_settings[noreply_mail]\n";
$headers.= "Reply-to: $hesk_settings[noreply_mail]\n";
$headers.= "Return-Path: $hesk_settings[webmaster_mail]\n";
$headers.= "Content-type: text/plain; charset=".$hesklang['ENCODING'];
@mail($email,$hesklang['ticket_received']." - TrackingID: $trackingURL",$msg,$headers);
/* Need to notify any admins? */
$admins=array();
$sql = "SELECT `email`,`isadmin`,`categories` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `notify_new_unassigned`='1'";
$result = hesk_dbQuery($sql);
while ($myuser=hesk_dbFetchAssoc($result))
{
/* Is this an administrator? */
if ($myuser['isadmin']) {$admins[]=$myuser['email']; continue;}
/* Not admin, is he allowed this category? */
$cat=substr($myuser['categories'], 0, -1);
$myuser['categories']=explode(',',$cat);
if (in_array($category,$myuser['categories']))
{
$admins[]=$myuser['email']; continue;
}
}
if (count($admins)>0)
{
$trackingURL_admin=$hesk_settings['hesk_url'].'/admin/admin_ticket.php?track='.$trackingID;
$msg = hesk_getEmailMessage('new_ticket_staff');
$msg = str_replace('%%NAME%%',hesk_msgToPlain($name,1),$msg);
$msg = str_replace('%%SUBJECT%%',hesk_msgToPlain($subject,1),$msg);
$msg = str_replace('%%TRACK_ID%%',$trackingID,$msg);
$msg = str_replace('%%TRACK_URL%%',$trackingURL_admin,$msg);
$msg = str_replace('%%SITE_TITLE%%',$hesk_settings['site_title'],$msg);
$msg = str_replace('%%SITE_URL%%',$hesk_settings['site_url'],$msg);
$msg = str_replace('%%MESSAGE%%',hesk_msgToPlain($message,1),$msg);
/* Send e-mail to staff */
$email=implode(',',$admins);
$headers = "From: $hesk_settings[noreply_mail]\n";
$headers.= "Reply-to: $hesk_settings[noreply_mail]\n";
$headers.= "Return-Path: $hesk_settings[webmaster_mail]\n";
$headers.= "Content-type: text/plain; charset=".$hesklang['ENCODING'];
@mail($email,$hesklang['new_ticket_submitted'],$msg,$headers);
}
echo "<h3>Nieuwe ticket aangemaakt met Tracking ID: $trackingID</h3>";
}
function createNewReply($subject, $name, $email, $date, $message, $trackingID)
{
global $hesk_settings, $hesklang;
$trackingID = trim($trackingID);
$trackingURL = $hesk_settings['hesk_url'].'/ticket.php?track='.$trackingID;
$sql = "SELECT id FROM `hesk_tickets` WHERE trackid='$trackingID'";
$result = hesk_dbQuery($sql) or hesk_error("$hesklang[cant_sql]: $sql</p><p>$hesklang[mysql_said]:<br>".mysql_error()."</p><p>$hesklang[contact_webmsater] $hesk_settings[webmaster_mail]");
$data = hesk_dbFetchAssoc($result);
$replyto = $data["id"];
/* Make sure the ticket is open */
$sql = "UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `status`='1',`lastreplier`='0',`lastchange`=NOW() WHERE `id`=".hesk_dbEscape($replyto)." LIMIT 1";
$result = hesk_dbQuery($sql);
/* Add reply */
$sql = "
INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` (
`replyto`,`name`,`message`,`dt`
)
VALUES (
'".hesk_dbEscape($replyto)."',
'".hesk_dbEscape($name)."',
'".hesk_dbEscape($message)."',
NOW()
)
";
$result = hesk_dbQuery($sql);
/* Need to notify any admins? */
$admins=array();
$sql = "SELECT `email`,`isadmin`,`categories` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `notify`='1'";
$result = hesk_dbQuery($sql);
while ($myuser=hesk_dbFetchAssoc($result))
{
/* Is this an administrator? */
if ($myuser['isadmin']) {$admins[]=$myuser['email']; continue;}
/* Not admin, is he allowed this category? */
$cat=substr($myuser['categories'], 0, -1);
$myuser['categories']=explode(",",$cat);
if (in_array($category,$myuser['categories']))
{
$admins[]=$myuser['email']; continue;
}
}
if (count($admins)>0)
{
/* Prepare ticket message for the e-mail */
$message = hesk_msgToPlain($message,1);
$trackingURL_admin = $hesk_settings['hesk_url'].'/admin/admin_ticket.php?track='.$trackingID;
$msg = hesk_getEmailMessage('new_reply_by_customer');
$msg = str_replace('%%NAME%%',$name,$msg);
$msg = str_replace('%%SUBJECT%%',$subject,$msg);
$msg = str_replace('%%TRACK_ID%%',$trackingID,$msg);
$msg = str_replace('%%TRACK_URL%%',$trackingURL_admin,$msg);
$msg = str_replace('%%SITE_TITLE%%',$hesk_settings['site_title'],$msg);
$msg = str_replace('%%SITE_URL%%',$hesk_settings['site_url'],$msg);
$msg = str_replace('%%MESSAGE%%',$message,$msg);
/* Send e-mail to staff */
$email=implode(',',$admins);
$headers = "From: $hesk_settings[noreply_mail]\n";
$headers.= "Reply-to: $hesk_settings[noreply_mail]\n";
$headers.= "Return-Path: $hesk_settings[webmaster_mail]\n";
$headers.= "Content-type: text/plain; charset=".$hesklang['ENCODING'];
@mail($email,$hesklang['new_reply_ticket'],$msg,$headers);
}
echo "<h3>Creando respuesta para: $trackingID</h3>";
}
Re: Email (Imap) Addon
Hi,
I just found out yesterday HESK and I set up here. I bought the license also supported the work.
I set up IMAP but many bugs were still present.
Here is a corrected version for HESK 2.3 that merges the text in emails.
I added the addition of email attachments to tickets.
Is it works with the accents here in France.
I added an option to read only the unread emails to allow them to leave in the inbox.
Sorry for the Google translation.
--8<----French--8<----
Bonjour,
Je viens de découvrir hier HESK et je l'ai mis en place chez nous. J'ai acheté la licence également pour supporté le travail.
j'ai mis en place IMAP mais beaucoup de bogues étaient encore présent.
Voici une version corrigé pour "HESK 2.3" qui fusionne les textes dans les emails.
J'ai ajouté l'ajout des pièces jointes des emails aux tickets.
Est elle fonctionne avec les accents ici en France.
J'ai ajouté également une option pour ne lire que les emails non lu pour permettre de les laisser dans la boite mail.
--8<----
I just found out yesterday HESK and I set up here. I bought the license also supported the work.
I set up IMAP but many bugs were still present.
Here is a corrected version for HESK 2.3 that merges the text in emails.
I added the addition of email attachments to tickets.
Is it works with the accents here in France.
I added an option to read only the unread emails to allow them to leave in the inbox.
Sorry for the Google translation.
--8<----French--8<----
Bonjour,
Je viens de découvrir hier HESK et je l'ai mis en place chez nous. J'ai acheté la licence également pour supporté le travail.
j'ai mis en place IMAP mais beaucoup de bogues étaient encore présent.
Voici une version corrigé pour "HESK 2.3" qui fusionne les textes dans les emails.
J'ai ajouté l'ajout des pièces jointes des emails aux tickets.
Est elle fonctionne avec les accents ici en France.
J'ai ajouté également une option pour ne lire que les emails non lu pour permettre de les laisser dans la boite mail.
--8<----
Code: Select all
<?php
////////////////////////////////////////// Settings //////////////////////////////////////////
$server = "pop.domaine.com"; //mail server.
$user = "mail@domaine.com"; // Mail Username
$password = STRONGPASSWORD"; // Mail Password
$unreadonly = "N"; // if unreadonly is Y then process unread mail only
$delete = "Y"; // if delete is Y then processed mail will be deleted
$debug = "0"; // Display Notices about in/outgoing emails 1 = on | 0 = off
$category = "1"; // Hesk Category ID to trow all emails in
$priority = "3"; // 3=Low 2=Medium 1=High
/////////////////////////////////////////////////////////////////////////////////////////////
define('IN_SCRIPT',1);
define('HESK_PATH','');
if (!function_exists('imap_open')) die("IMAP functions are not available.");
if ($debug==1) error_reporting(E_ALL); else error_reporting(0);
// Get all the required files and functions
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/email_functions.inc.php');
// Connect to database
require(HESK_PATH . 'inc/database.inc.php');
hesk_dbConnect() or hesk_error("$hesklang[cant_connect_db] $hesklang[contact_webmsater] $hesk_settings[webmaster_mail]!");
// $host = "{".$server.":143}"."INBOX";
$host = "{".$server.":993/imap/ssl/novalidate-cert}"."INBOX";
$conn = imap_open($host, $user, $password) or die("<br><br><b>Error: Can't connect to mailbox</b>");
$check = imap_mailboxmsginfo($conn);
if ($unreadonly == "Y") {
$msgnos = imap_search($conn, 'UNSEEN');
} else {
$msgnos = imap_search($conn, 'ALL');
}
foreach ($msgnos as $msgno) {
list($subject, $name, $email, $date, $message, $trackingID) = getMessage($conn, $msgno);
if (!$trackingID) {
$trackingID = hesk_createID(); // create new trackingID
$myattachments = create_attachment($conn, $msgno, $trackingID ); // create attachement
$trackingID = createNewTicket($subject, $name, $email, $date, $message, $trackingID ,$myattachments );
} else {
$myattachments = create_attachment($conn, $msgno, $trackingID );
createNewReply($subject, $name, $email, $date, $message, $trackingID, $myattachments);
}
if ($delete == "Y") imap_delete($conn, $msgno); // mark the current message for deletion
}
if ($delete == "Y") imap_expunge($conn); // delete all messages marked for deletion
imap_close($conn);
function extract_attachments($connection, $message_number) {
$structure = imap_fetchstructure($connection, $message_number);
$attachments = array();
if(isset($structure->parts) && count($structure->parts)) {
for($i = 0; $i < count($structure->parts); $i++) {
$attachments[$i] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => ''
);
if($structure->parts[$i]->ifdparameters) {
foreach($structure->parts[$i]->dparameters as $object) {
if(strtolower($object->attribute) == 'filename') {
$attachments[$i]['is_attachment'] = true;
$tmpfrom = imap_mime_header_decode($object->value);
$attachments[$i]['filename'] = quoted_printable_decode($tmpfrom[0]->text);
}
}
}
if($structure->parts[$i]->ifparameters) {
foreach($structure->parts[$i]->parameters as $object) {
if(strtolower($object->attribute) == 'name') {
$attachments[$i]['is_attachment'] = true;
$tmpfrom = imap_mime_header_decode($object->value);
$attachments[$i]['name'] = quoted_printable_decode($tmpfrom[0]->text);
}
}
}
if($attachments[$i]['is_attachment']) {
$attachments[$i]['attachment'] = imap_fetchbody($connection, $message_number, $i+1);
if($structure->parts[$i]->encoding == 3) { // 3 = BASE64
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
}
elseif($structure->parts[$i]->encoding == 4) { // 4 = QUOTED-PRINTABLE
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
}
}
}
return $attachments;
}
// Functions
function getHeader($msgStream, $msgNumber) {
// strips the mail header and places everything in an array .. like from name, from email, date and subject
$mailheader = imap_headerinfo($msgStream, $msgNumber);
$headerArray = array();
$headerArray[0] = $mailheader->subject;
$from = $mailheader->from;
foreach ($from as $id => $object) {
$headerArray[1] = $object->personal; // from personal
$headerArray[2] = $object->mailbox . "@" . $object->host; // from address
}
$headerArray[3] = $mailheader->Date;
return $headerArray;
}
function extractPlain($msgStream, $msgNumber, $st = null, $num = "")
{
// pull the plain text for message $n
if (!$st) $st = imap_fetchstructure($msgStream, $msgNumber);
if (!empty($st->parts)) {
for ($i = 0, $j = count($st->parts); $i < $j; $i++) {
$part = $st->parts[$i];
if ($part->subtype == 'PLAIN') {
return imap_fetchbody($msgStream, $msgNumber, $num.($i+1));
}
if (!empty($part->parts)) {
$body = extractPlain($msgStream, $msgNumber, $part, ($i+1).".");
if ($body) return $body;
}
}
} else {
return imap_body($msgStream, $msgNumber);
}
}
function getMessage($msgStream, $msgNumber)
{
// pull the plain text for message $n
$message = mimeDecode(nl2br(extractPlain($msgStream, $msgNumber)));
$headerArray = getHeader($msgStream, $msgNumber);
$subject = mimeDecode(htmlentities(addslashes($headerArray[0])));
$name = mimeDecode(htmlentities(addslashes($headerArray[1])));
$email = htmlentities($headerArray[2]);
$date = htmlentities($headerArray[3]);
$txt = "";
if (preg_match("/- TrackingID: (.*)/", $subject, $matches)) {
$trackingID = $matches[1];
}
return array($subject, $name, $email, $date, $message, $trackingID);
}
function mimeDecode($string)
{
$tmpfrom = imap_mime_header_decode($string);
return quoted_printable_decode($tmpfrom[0]->text);
}
function createNewTicket($subject, $name, $email, $date, $message, $trackingID, $attachments)
{
global $category, $priority, $hesk_settings, $hesklang;
$trackingURL = $hesk_settings['hesk_url'].'/ticket.php?track='.$trackingID;
if (get_magic_quotes_gpc()) {$message = stripslashes($message);};
$sql = "INSERT INTO `hesk_tickets` (`trackid`,`name`,`email`,`category`,`priority`,`subject`,`message`,`dt`,`lastchange`,`ip`,`status`,`attachments`,`custom1`,`custom2`,`custom3`,`custom4`,`custom5`) VALUES ('$trackingID','$name','$email','$category','$priority','$subject','".mysql_real_escape_string($message)."',NOW(),NOW(),'email','0','$attachments','','','','','')";
$result = hesk_dbQuery($sql);
/* Get e-mail message for customer */
$ticket = array(
'name' => hesk_msgToPlain($name,1),
'subject' => hesk_msgToPlain($subject,1),
'trackid' => $trackingID,
'category' => $category,
'priority' => $priority,
'message' => hesk_msgToPlain($message,1)
);
$msg = hesk_getEmailMessage('new_ticket',$ticket);
/* Send e-mail */
$headers = "From: $hesk_settings[noreply_mail]\n";
$headers.= "Reply-to: $hesk_settings[noreply_mail]\n";
$headers.= "Return-Path: $hesk_settings[webmaster_mail]\n";
$headers.= "Content-type: text/plain; charset=".$hesklang['ENCODING'];
@mail($email,$hesklang['ticket_received']." - TrackingID: $trackingID",$msg,$headers);
/* Need to notify any admins? */
$admins=array();
$sql = "SELECT `email`,`isadmin`,`categories` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `notify_new_unassigned`='1'";
$result = hesk_dbQuery($sql);
while ($myuser=hesk_dbFetchAssoc($result))
{
/* Is this an administrator? */
if ($myuser['isadmin']) {$admins[]=$myuser['email']; continue;}
/* Not admin, is he allowed this category? */
$cat=substr($myuser['categories'], 0, -1);
$myuser['categories']=explode(',',$cat);
if (in_array($category,$myuser['categories']))
{
$admins[]=$myuser['email']; continue;
}
}
if (count($admins)>0)
{
$trackingURL_admin=$hesk_settings['hesk_url'].'/admin/admin_ticket.php?track='.$trackingID;
$ticket = array(
'name' => hesk_msgToPlain($name,1),
'subject' => hesk_msgToPlain($subject,1),
'trackid' => $trackingID,
'category' => $category,
'priority' => $priority,
'message' => hesk_msgToPlain($message,1)
);
$msg = hesk_getEmailMessage('new_ticket_staff',$ticket);
/* Send e-mail to staff */
$email=implode(',',$admins);
$headers = "From: $hesk_settings[noreply_mail]\n";
$headers.= "Reply-to: $hesk_settings[noreply_mail]\n";
$headers.= "Return-Path: $hesk_settings[webmaster_mail]\n";
$headers.= "Content-type: text/plain; charset=".$hesklang['ENCODING'];
@mail($email,$hesklang['new_ticket_submitted'],$msg,$headers);
}
echo "<h3>New ticket : $trackingID</h3>";
return $trackingID;
}
function createNewReply($subject, $name, $email, $date, $message, $trackingID, $attachments)
{
global $hesk_settings, $hesklang;
$trackingID = trim($trackingID);
$trackingURL = $hesk_settings['hesk_url'].'/ticket.php?track='.$trackingID;
$sql = "SELECT id FROM `hesk_tickets` WHERE trackid='$trackingID'";
$result = hesk_dbQuery($sql) or hesk_error("$hesklang[cant_sql]: $sql</p><p>$hesklang[mysql_said]:<br>".mysql_error()."</p><p>$hesklang[contact_webmsater] $hesk_settings[webmaster_mail]");
$data = hesk_dbFetchAssoc($result);
$replyto = $data["id"];
/* Make sure the ticket is open */
$sql = "UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `status`='1',`lastreplier`='0',`lastchange`=NOW() WHERE `id`=".hesk_dbEscape($replyto)." LIMIT 1";
$result = hesk_dbQuery($sql);
/* Add reply */
$sql = "
INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` (
`replyto`,`name`,`message`,`dt`,`attachments`
)
VALUES (
'".hesk_dbEscape($replyto)."',
'".hesk_dbEscape($name)."',
'".hesk_dbEscape($message)."',
NOW(),
'".hesk_dbEscape($attachments)."'
)
";
$result = hesk_dbQuery($sql);
/* Need to notify any admins? */
$admins=array();
$sql = "SELECT `email`,`isadmin`,`categories` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `notify_reply_my`='1'";
$result = hesk_dbQuery($sql);
while ($myuser=hesk_dbFetchAssoc($result))
{
/* Is this an administrator? */
if ($myuser['isadmin']) {$admins[]=$myuser['email']; continue;}
/* Not admin, is he allowed this category? */
$cat=substr($myuser['categories'], 0, -1);
$myuser['categories']=explode(",",$cat);
if (in_array($category,$myuser['categories']))
{
$admins[]=$myuser['email']; continue;
}
}
if (count($admins)>0)
{
/* Prepare ticket message for the e-mail */
$message = hesk_msgToPlain($message,1);
$trackingURL_admin = $hesk_settings['hesk_url'].'/admin/admin_ticket.php?track='.$trackingID;
$ticket = array(
'name' => hesk_msgToPlain($name,1),
'subject' => hesk_msgToPlain($subject,1),
'trackid' => $trackingID,
'category' => $category,
'priority' => $priority,
'message' => hesk_msgToPlain($message,1)
);
$msg = hesk_getEmailMessage('new_reply_by_customer', $ticket);
/* Send e-mail to staff */
$email=implode(',',$admins);
$headers = "From: $hesk_settings[noreply_mail]\n";
$headers.= "Reply-to: $hesk_settings[noreply_mail]\n";
$headers.= "Return-Path: $hesk_settings[webmaster_mail]\n";
$headers.= "Content-type: text/plain; charset=".$hesklang['ENCODING'];
@mail($email,$hesklang['new_reply_ticket'],$msg,$headers);
}
echo "<h3>new answer for ticket : $trackingID</h3>";
}
/*
* Extract Attachment from mail
* and create in Hesk Database
*/
function create_attachment($conn, $uid, $trackingID)
{
global $hesk_settings, $hesklang;
$trackingID = trim($trackingID);
$myattachments = '';
$attachments = extract_attachments($conn, $uid);
for($i = 0; $i < count($attachments); $i++) {
if ($attachments[$i]['is_attachment'] == true) {
$attachment = save_file($attachments[$i]);
if (!empty($attachment))
{
$sql = "INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."attachments` (`ticket_id`,`saved_name`,`real_name`,`size`) VALUES (
'".hesk_dbEscape($trackingID)."',
'".hesk_dbEscape($attachment['saved_name'])."',
'".hesk_dbEscape($attachment['real_name'])."',
'".hesk_dbEscape($attachment['size'])."'
)";
$result = hesk_dbQuery($sql);
$myattachments .= hesk_dbInsertID() . '#' . $attachment['real_name'] .',';
}
}
}
return $myattachments;
}
/*
* Save Attachment to disk
*/
function save_file($attachement)
{
global $hesk_settings, $hesklang, $trackingID, $hesk_error_buffer;
#$hesk_error_buffer .= '<br>BBBBBBBBBB';
/* Return if name is empty */
if (empty($attachement['name'])) {return '';}
/* Check file extension */
$ext = strtolower(strrchr($attachement['name'], "."));
if ( ! in_array($ext,$hesk_settings['attachments']['allowed_types']))
{
return hesk_fileError(sprintf($hesklang['type_not_allowed'],$attachement['name'][$i]));
}
/* Check file size */
if (strlen($attachement['attachment']) > ($hesk_settings['attachments']['max_size']*1024))
{
return hesk_fileError(sprintf($hesklang['file_too_large'],$attachement['name']));
}
else
{
$file_size = strlen($attachement['attachment']);
}
/* Generate a random file name */
$file_realname = str_replace(array('/','\\','#',',',' '), array('','','','','_'),$attachement['name']);
$useChars='AEUYBDGHJLMNPQRSTVWXZ123456789';
$tmp = $useChars{mt_rand(0,29)};
for($j=1;$j<10;$j++)
{
$tmp .= $useChars{mt_rand(0,29)};
}
if (defined('KB'))
{
$file_name = substr(md5($tmp . $file_realname), 0, 200) . $ext;
}
else
{
$file_name = substr($trackingID . '_' . md5($tmp . $file_realname), 0, 200) . $ext;
}
/* Save file */
$fh = fopen($hesk_settings['server_path'].'/attachments/'.$file_name, 'w') or die("<br><br><b>can't open file</b>");
fwrite($fh, $attachement['attachment']);
fclose($fh);
$info = array(
'saved_name'=> $file_name,
'real_name' => $file_realname,
'size' => $file_size
);
return $info;
}
?>
Last edited by Atoo Next on Mon Oct 10, 2011 7:04 pm, edited 2 times in total.
Re: Email (Imap) Addon
Thank you Atoo Next!
It works well!
I have a couple of quick questions.
1. How can I have it email my staff when a new ticket is opened by email?
2. When a customer emails with attachment and html email - it shows a lot of this kind of thing inside the ticket like below - can this be prevented?
------=_NextPart_002_0380_01CC87C5.B59C53D0
Content-Type: text/html;
charset="us-ascii"
Content-Transfer-Encoding: quoted-printable
xmlns:o="urn:schemas-microsoft-com
office" =
xmlns:w="urn:schemas-microsoft-com
word" =
xmlns:x="urn:schemas-microsoft-com
excel" =
xmlns:p="urn:schemas-microsoft-com
powerpoint" =
xmlns:a="urn:schemas-microsoft-com
access" =
xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" =
xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882" =
xmlns:rs="urn:schemas-microsoft-com:rowset" xmlns:z="#RowsetSchema" =
xmlns:b="urn:schemas-microsoft-com
publisher" =
xmlns:ss="urn:schemas-microsoft-com
spreadsheet" =
xmlns:c="urn:schemas-microsoft-com
component:spreadsheet" =
xmlns:odc="urn:schemas-microsoft-com
odc" =
It works well!
I have a couple of quick questions.
1. How can I have it email my staff when a new ticket is opened by email?
2. When a customer emails with attachment and html email - it shows a lot of this kind of thing inside the ticket like below - can this be prevented?
------=_NextPart_002_0380_01CC87C5.B59C53D0
Content-Type: text/html;
charset="us-ascii"
Content-Transfer-Encoding: quoted-printable
xmlns:o="urn:schemas-microsoft-com
xmlns:w="urn:schemas-microsoft-com
xmlns:x="urn:schemas-microsoft-com
xmlns:p="urn:schemas-microsoft-com
xmlns:a="urn:schemas-microsoft-com
xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" =
xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882" =
xmlns:rs="urn:schemas-microsoft-com:rowset" xmlns:z="#RowsetSchema" =
xmlns:b="urn:schemas-microsoft-com
xmlns:ss="urn:schemas-microsoft-com
xmlns:c="urn:schemas-microsoft-com
xmlns:odc="urn:schemas-microsoft-com
Frank
Re: Email (Imap) Addon
Hi,
1) Check 'A new ticket is submitted with owner: Unassigned' in Users profile Notifications.
2) I have no problem here with HTML attachment.
The HTML attachments was removed on import
Maybe it's a character encoding problem.
Sorry.
1) Check 'A new ticket is submitted with owner: Unassigned' in Users profile Notifications.
Code: Select all
in function createNewTicket()
/* Need to notify any admins? */
$admins=array();
$sql = "SELECT `email`,`isadmin`,`categories` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `notify_new_unassigned`='1'";
$result = hesk_dbQuery($sql);
while ($myuser=hesk_dbFetchAssoc($result))
The HTML attachments was removed on import
Maybe it's a character encoding problem.
Sorry.
Re: Email (Imap) Addon
hm, there must be a bug in that code - it sends an email to the admin if they have that box ticked but not to staff who have that box ticked.
In relation to the html - html emails work perfectly when there is no attachment.
When there is an attachment - you get the above code throughout the message (at least when sent via outlook)
Thank you so much for your time and your bug fixes so far!
In relation to the html - html emails work perfectly when there is no attachment.
When there is an attachment - you get the above code throughout the message (at least when sent via outlook)
Thank you so much for your time and your bug fixes so far!

Frank
Re: Email (Imap) Addon
@Atoo Next
Have tested the tweaked script, and workes oke for me, also with the attachment!
Other question's:
1. How can i modify that wenn i put someone in the CC this email adres will be used ass second mail into my ticket? Like if a customer mail me his question i will reply to the ticket system with the customer in to the CC?
2. How can i modify that the emaul adres from the sender will be related to a group in Hesk?
Have tested the tweaked script, and workes oke for me, also with the attachment!
Other question's:
1. How can i modify that wenn i put someone in the CC this email adres will be used ass second mail into my ticket? Like if a customer mail me his question i will reply to the ticket system with the customer in to the CC?
2. How can i modify that the emaul adres from the sender will be related to a group in Hesk?
Re: Email (Imap) Addon
@Atoo Next,
thanks a lot,
it worked for me after I fixed a typo in line 5 and
line 172 an 249 for installations with non standard hesk_ table prefix
thanks a lot,
it worked for me after I fixed a typo in line 5 and
line 172 an 249 for installations with non standard hesk_ table prefix
Code: Select all
<?php
////////////////////////////////////////// Settings //////////////////////////////////////////
$server = "pop.domaine.com"; //mail server.
$user = "mail@domaine.com"; // Mail Username
$password = "STRONGPASSWORD"; // Mail Password
$unreadonly = "N"; // if unreadonly is Y then process unread mail only
$delete = "Y"; // if delete is Y then processed mail will be deleted
$debug = "0"; // Display Notices about in/outgoing emails 1 = on | 0 = off
$category = "1"; // Hesk Category ID to trow all emails in
$priority = "3"; // 3=Low 2=Medium 1=High
/////////////////////////////////////////////////////////////////////////////////////////////
define('IN_SCRIPT',1);
define('HESK_PATH','');
if (!function_exists('imap_open')) die("IMAP functions are not available.");
if ($debug==1) error_reporting(E_ALL); else error_reporting(0);
// Get all the required files and functions
require(HESK_PATH . 'hesk_settings.inc.php');
require(HESK_PATH . 'inc/common.inc.php');
require(HESK_PATH . 'inc/email_functions.inc.php');
// Connect to database
require(HESK_PATH . 'inc/database.inc.php');
hesk_dbConnect() or hesk_error("$hesklang[cant_connect_db] $hesklang[contact_webmsater] $hesk_settings[webmaster_mail]!");
// $host = "{".$server.":143}"."INBOX";
$host = "{".$server.":993/imap/ssl/novalidate-cert}"."INBOX";
$conn = imap_open($host, $user, $password) or die("<br><br><b>Error: Can't connect to mailbox</b>");
$check = imap_mailboxmsginfo($conn);
if ($unreadonly == "Y") {
$msgnos = imap_search($conn, 'UNSEEN');
} else {
$msgnos = imap_search($conn, 'ALL');
}
foreach ($msgnos as $msgno) {
list($subject, $name, $email, $date, $message, $trackingID) = getMessage($conn, $msgno);
if (!$trackingID) {
$trackingID = hesk_createID(); // create new trackingID
$myattachments = create_attachment($conn, $msgno, $trackingID ); // create attachement
$trackingID = createNewTicket($subject, $name, $email, $date, $message, $trackingID ,$myattachments );
} else {
$myattachments = create_attachment($conn, $msgno, $trackingID );
createNewReply($subject, $name, $email, $date, $message, $trackingID, $myattachments);
}
if ($delete == "Y") imap_delete($conn, $msgno); // mark the current message for deletion
}
if ($delete == "Y") imap_expunge($conn); // delete all messages marked for deletion
imap_close($conn);
function extract_attachments($connection, $message_number) {
$structure = imap_fetchstructure($connection, $message_number);
$attachments = array();
if(isset($structure->parts) && count($structure->parts)) {
for($i = 0; $i < count($structure->parts); $i++) {
$attachments[$i] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => ''
);
if($structure->parts[$i]->ifdparameters) {
foreach($structure->parts[$i]->dparameters as $object) {
if(strtolower($object->attribute) == 'filename') {
$attachments[$i]['is_attachment'] = true;
$tmpfrom = imap_mime_header_decode($object->value);
$attachments[$i]['filename'] = quoted_printable_decode($tmpfrom[0]->text);
}
}
}
if($structure->parts[$i]->ifparameters) {
foreach($structure->parts[$i]->parameters as $object) {
if(strtolower($object->attribute) == 'name') {
$attachments[$i]['is_attachment'] = true;
$tmpfrom = imap_mime_header_decode($object->value);
$attachments[$i]['name'] = quoted_printable_decode($tmpfrom[0]->text);
}
}
}
if($attachments[$i]['is_attachment']) {
$attachments[$i]['attachment'] = imap_fetchbody($connection, $message_number, $i+1);
if($structure->parts[$i]->encoding == 3) { // 3 = BASE64
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
}
elseif($structure->parts[$i]->encoding == 4) { // 4 = QUOTED-PRINTABLE
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
}
}
}
return $attachments;
}
// Functions
function getHeader($msgStream, $msgNumber) {
// strips the mail header and places everything in an array .. like from name, from email, date and subject
$mailheader = imap_headerinfo($msgStream, $msgNumber);
$headerArray = array();
$headerArray[0] = $mailheader->subject;
$from = $mailheader->from;
foreach ($from as $id => $object) {
$headerArray[1] = $object->personal; // from personal
$headerArray[2] = $object->mailbox . "@" . $object->host; // from address
}
$headerArray[3] = $mailheader->Date;
return $headerArray;
}
function extractPlain($msgStream, $msgNumber, $st = null, $num = "")
{
// pull the plain text for message $n
if (!$st) $st = imap_fetchstructure($msgStream, $msgNumber);
if (!empty($st->parts)) {
for ($i = 0, $j = count($st->parts); $i < $j; $i++) {
$part = $st->parts[$i];
if ($part->subtype == 'PLAIN') {
return imap_fetchbody($msgStream, $msgNumber, $num.($i+1));
}
if (!empty($part->parts)) {
$body = extractPlain($msgStream, $msgNumber, $part, ($i+1).".");
if ($body) return $body;
}
}
} else {
return imap_body($msgStream, $msgNumber);
}
}
function getMessage($msgStream, $msgNumber)
{
// pull the plain text for message $n
$message = mimeDecode(nl2br(extractPlain($msgStream, $msgNumber)));
$headerArray = getHeader($msgStream, $msgNumber);
$subject = mimeDecode(htmlentities(addslashes($headerArray[0])));
$name = mimeDecode(htmlentities(addslashes($headerArray[1])));
$email = htmlentities($headerArray[2]);
$date = htmlentities($headerArray[3]);
$txt = "";
if (preg_match("/- TrackingID: (.*)/", $subject, $matches)) {
$trackingID = $matches[1];
}
return array($subject, $name, $email, $date, $message, $trackingID);
}
function mimeDecode($string)
{
$tmpfrom = imap_mime_header_decode($string);
return quoted_printable_decode($tmpfrom[0]->text);
}
function createNewTicket($subject, $name, $email, $date, $message, $trackingID, $attachments)
{
global $category, $priority, $hesk_settings, $hesklang;
$trackingURL = $hesk_settings['hesk_url'].'/ticket.php?track='.$trackingID;
if (get_magic_quotes_gpc()) {$message = stripslashes($message);};
$sql = "INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` (`trackid`,`name`,`email`,`category`,`priority`,`subject`,`message`,`dt`,`lastchange`,`ip`,`status`,`attachments`,`custom1`,`custom2`,`custom3`,`custom4`,`custom5`) VALUES ('$trackingID','$name','$email','$category','$priority','$subject','".mysql_real_escape_string($message)."',NOW(),NOW(),'email','0','$attachments','','','','','')";
$result = hesk_dbQuery($sql);
/* Get e-mail message for customer */
$ticket = array(
'name' => hesk_msgToPlain($name,1),
'subject' => hesk_msgToPlain($subject,1),
'trackid' => $trackingID,
'category' => $category,
'priority' => $priority,
'message' => hesk_msgToPlain($message,1)
);
$msg = hesk_getEmailMessage('new_ticket',$ticket);
/* Send e-mail */
$headers = "From: $hesk_settings[noreply_mail]\n";
$headers.= "Reply-to: $hesk_settings[noreply_mail]\n";
$headers.= "Return-Path: $hesk_settings[webmaster_mail]\n";
$headers.= "Content-type: text/plain; charset=".$hesklang['ENCODING'];
@mail($email,$hesklang['ticket_received']." - TrackingID: $trackingID",$msg,$headers);
/* Need to notify any admins? */
$admins=array();
$sql = "SELECT `email`,`isadmin`,`categories` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `notify_new_unassigned`='1'";
$result = hesk_dbQuery($sql);
while ($myuser=hesk_dbFetchAssoc($result))
{
/* Is this an administrator? */
if ($myuser['isadmin']) {$admins[]=$myuser['email']; continue;}
/* Not admin, is he allowed this category? */
$cat=substr($myuser['categories'], 0, -1);
$myuser['categories']=explode(',',$cat);
if (in_array($category,$myuser['categories']))
{
$admins[]=$myuser['email']; continue;
}
}
if (count($admins)>0)
{
$trackingURL_admin=$hesk_settings['hesk_url'].'/admin/admin_ticket.php?track='.$trackingID;
$ticket = array(
'name' => hesk_msgToPlain($name,1),
'subject' => hesk_msgToPlain($subject,1),
'trackid' => $trackingID,
'category' => $category,
'priority' => $priority,
'message' => hesk_msgToPlain($message,1)
);
$msg = hesk_getEmailMessage('new_ticket_staff',$ticket);
/* Send e-mail to staff */
$email=implode(',',$admins);
$headers = "From: $hesk_settings[noreply_mail]\n";
$headers.= "Reply-to: $hesk_settings[noreply_mail]\n";
$headers.= "Return-Path: $hesk_settings[webmaster_mail]\n";
$headers.= "Content-type: text/plain; charset=".$hesklang['ENCODING'];
@mail($email,$hesklang['new_ticket_submitted'],$msg,$headers);
}
echo "<h3>New ticket : $trackingID</h3>";
return $trackingID;
}
function createNewReply($subject, $name, $email, $date, $message, $trackingID, $attachments)
{
global $hesk_settings, $hesklang;
$trackingID = trim($trackingID);
$trackingURL = $hesk_settings['hesk_url'].'/ticket.php?track='.$trackingID;
$sql = "SELECT id FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` WHERE trackid='$trackingID'";
$result = hesk_dbQuery($sql) or hesk_error("$hesklang[cant_sql]: $sql</p><p>$hesklang[mysql_said]:<br>".mysql_error()."</p><p>$hesklang[contact_webmsater] $hesk_settings[webmaster_mail]");
$data = hesk_dbFetchAssoc($result);
$replyto = $data["id"];
/* Make sure the ticket is open */
$sql = "UPDATE `".hesk_dbEscape($hesk_settings['db_pfix'])."tickets` SET `status`='1',`lastreplier`='0',`lastchange`=NOW() WHERE `id`=".hesk_dbEscape($replyto)." LIMIT 1";
$result = hesk_dbQuery($sql);
/* Add reply */
$sql = "
INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."replies` (
`replyto`,`name`,`message`,`dt`,`attachments`
)
VALUES (
'".hesk_dbEscape($replyto)."',
'".hesk_dbEscape($name)."',
'".hesk_dbEscape($message)."',
NOW(),
'".hesk_dbEscape($attachments)."'
)
";
$result = hesk_dbQuery($sql);
/* Need to notify any admins? */
$admins=array();
$sql = "SELECT `email`,`isadmin`,`categories` FROM `".hesk_dbEscape($hesk_settings['db_pfix'])."users` WHERE `notify_reply_my`='1'";
$result = hesk_dbQuery($sql);
while ($myuser=hesk_dbFetchAssoc($result))
{
/* Is this an administrator? */
if ($myuser['isadmin']) {$admins[]=$myuser['email']; continue;}
/* Not admin, is he allowed this category? */
$cat=substr($myuser['categories'], 0, -1);
$myuser['categories']=explode(",",$cat);
if (in_array($category,$myuser['categories']))
{
$admins[]=$myuser['email']; continue;
}
}
if (count($admins)>0)
{
/* Prepare ticket message for the e-mail */
$message = hesk_msgToPlain($message,1);
$trackingURL_admin = $hesk_settings['hesk_url'].'/admin/admin_ticket.php?track='.$trackingID;
$ticket = array(
'name' => hesk_msgToPlain($name,1),
'subject' => hesk_msgToPlain($subject,1),
'trackid' => $trackingID,
'category' => $category,
'priority' => $priority,
'message' => hesk_msgToPlain($message,1)
);
$msg = hesk_getEmailMessage('new_reply_by_customer', $ticket);
/* Send e-mail to staff */
$email=implode(',',$admins);
$headers = "From: $hesk_settings[noreply_mail]\n";
$headers.= "Reply-to: $hesk_settings[noreply_mail]\n";
$headers.= "Return-Path: $hesk_settings[webmaster_mail]\n";
$headers.= "Content-type: text/plain; charset=".$hesklang['ENCODING'];
@mail($email,$hesklang['new_reply_ticket'],$msg,$headers);
}
echo "<h3>new answer for ticket : $trackingID</h3>";
}
/*
* Extract Attachment from mail
* and create in Hesk Database
*/
function create_attachment($conn, $uid, $trackingID)
{
global $hesk_settings, $hesklang;
$trackingID = trim($trackingID);
$myattachments = '';
$attachments = extract_attachments($conn, $uid);
for($i = 0; $i < count($attachments); $i++) {
if ($attachments[$i]['is_attachment'] == true) {
$attachment = save_file($attachments[$i]);
if (!empty($attachment))
{
$sql = "INSERT INTO `".hesk_dbEscape($hesk_settings['db_pfix'])."attachments` (`ticket_id`,`saved_name`,`real_name`,`size`) VALUES (
'".hesk_dbEscape($trackingID)."',
'".hesk_dbEscape($attachment['saved_name'])."',
'".hesk_dbEscape($attachment['real_name'])."',
'".hesk_dbEscape($attachment['size'])."'
)";
$result = hesk_dbQuery($sql);
$myattachments .= hesk_dbInsertID() . '#' . $attachment['real_name'] .',';
}
}
}
return $myattachments;
}
/*
* Save Attachment to disk
*/
function save_file($attachement)
{
global $hesk_settings, $hesklang, $trackingID, $hesk_error_buffer;
#$hesk_error_buffer .= '<br>BBBBBBBBBB';
/* Return if name is empty */
if (empty($attachement['name'])) {return '';}
/* Check file extension */
$ext = strtolower(strrchr($attachement['name'], "."));
if ( ! in_array($ext,$hesk_settings['attachments']['allowed_types']))
{
return hesk_fileError(sprintf($hesklang['type_not_allowed'],$attachement['name'][$i]));
}
/* Check file size */
if (strlen($attachement['attachment']) > ($hesk_settings['attachments']['max_size']*1024))
{
return hesk_fileError(sprintf($hesklang['file_too_large'],$attachement['name']));
}
else
{
$file_size = strlen($attachement['attachment']);
}
/* Generate a random file name */
$file_realname = str_replace(array('/','\\','#',',',' '), array('','','','','_'),$attachement['name']);
$useChars='AEUYBDGHJLMNPQRSTVWXZ123456789';
$tmp = $useChars{mt_rand(0,29)};
for($j=1;$j<10;$j++)
{
$tmp .= $useChars{mt_rand(0,29)};
}
if (defined('KB'))
{
$file_name = substr(md5($tmp . $file_realname), 0, 200) . $ext;
}
else
{
$file_name = substr($trackingID . '_' . md5($tmp . $file_realname), 0, 200) . $ext;
}
/* Save file */
$fh = fopen($hesk_settings['server_path'].'/attachments/'.$file_name, 'w') or die("<br><br><b>can't open file</b>");
fwrite($fh, $attachement['attachment']);
fclose($fh);
$info = array(
'saved_name'=> $file_name,
'real_name' => $file_realname,
'size' => $file_size
);
return $info;
}
?>