Email (Imap) Addon

Everything related to Hesk - helpdesk software

Moderator: mkoch227

Do you think this addon is usefull ?

Yes!
21
84%
No!
1
4%
Maybe
3
12%
Don't know what the hell this is
0
No votes
 
Total votes: 25

darksidebadman
Posts: 2
Joined: Wed Jan 07, 2009 7:48 pm

Email (Imap) Addon

Post by darksidebadman »

/*************************************
Title: Mail ADDON
Version: 1.0
Author: Joep Persoon djjoepwork-<[at]>-yahoo-<[dot]>-com
Demo: -
Download: -
Website: -

Description:
Addon to connect true imap a mailbox, extract the emails and create tickets for each one of them. The title will be the email subject, Conformation will be send to the admins & customer etc just like adding a ticket true the website
Script has to run with help of cronjob or something else you wanna use to run it every x minutes

*************************************/
What do you need to use this addon ?:
- an email account with imap support
- imap enabled in your webserver settings (script will tell you when its disabled)
- Cronjob or somethimg simular to run the script automatic every x minutes

How to use it:
- copy paste the code into a file and name it imap.php
- change the settings in imap.php
- upload it in your hesk root folder
- setup a cronjob to run the file http://YOURHESKURL/imap.php every x minutes ( I have setup every 10 minutes but its what you prefer)


Filename : imap.php (place it in your hesk root folder)

Code: Select all

<?php
// Settings /////////////////////////////////////////////////////////////////////////////////
$server               = "pop.yourdomain.com"; //mail server.
$user                 = "yourusername"; // Mail Username
$password             = "yourpassword"; // 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);
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_once('hesk_settings.inc.php');
require_once('language/'.$hesk_settings['language'].'.inc.php');
require_once('inc/common.inc.php');
// Connect to database
require_once('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;
}
function getBody($msgStream, $msgNumber){
   // gets email content
   $body=imap_body($msgStream,$msgNumber);
   return $body;
}

$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); 
}

$msgNumber = "1";
while ($msgNumber <= $number) {
   $headerArray = getHeader($msgStream, $msgNumber);
   $message = htmlentities(getBody($msgStream, $msgNumber));
   $subject = htmlentities($headerArray[0]);
   $name    = htmlentities($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('emails/new_ticket.txt','r');
   $message=fread($fp,filesize('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_ticket.php?track='.$trackingID;
      // Get e-mail message for customer
      $fp=fopen('emails/new_ticket_staff.txt','r');
      $message=fread($fp,filesize('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);
?>
[Edit] Changed debug info displayed when debug=1. With tnx to ictconsulting! [/Edit]
Last edited by darksidebadman on Fri Feb 06, 2009 10:10 pm, edited 2 times in total.
dlmcclou
Posts: 1
Joined: Sun Jan 25, 2009 4:08 am

Post by dlmcclou »

Hmm I'm getting a parse error at line 11. Thoughts?
Klemen
Site Admin
Posts: 10136
Joined: Fri Feb 11, 2005 4:04 pm

Post by Klemen »

There's a missing ";" after "$priority = 3" in line 9. So change line 9 to

Code: Select all

$priority         = 3;
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
ictconsulting
Posts: 21
Joined: Sun Feb 01, 2009 2:21 pm

Post by ictconsulting »

The script sounds cool but for me I wonder why it didn't work.

I still get the "Error: Can't connect to mailbox" ...

Here is my telnet output connecting via IMAP to my mailbox


. login MYMAIL@DOMAIN.COM PASSWORD
. OK LOGIN Ok.
. list "" "*"
* LIST (\HasNoChildren) "." "INBOX.CLIENTS"
* LIST (\HasNoChildren) "." "INBOX.Drafts"
* LIST (\HasNoChildren) "." "INBOX.Sent"
* LIST (\HasNoChildren) "." "INBOX.Trash"
* LIST (\Marked \HasChildren) "." "INBOX"
. OK LIST completed

What could be wrong in my settings?

My mailbox still on the same provider where hesk is hosted, could this cause the connection problem the mailserver?

How do I get mails from just one of the children folders?

What sholud I consider in state of cronjob to run the script automatically?

I really like your script and I'll probably buy you a pair of beers ;-)
ictconsulting
Posts: 21
Joined: Sun Feb 01, 2009 2:21 pm

imap connection problem solved

Post by ictconsulting »

I managed to fix it though, had to change it to:
{mail.server.com:143/imap/notls}INBOX
ictconsulting
Posts: 21
Joined: Sun Feb 01, 2009 2:21 pm

IMAP mails download

Post by ictconsulting »

I'm not able (anymore) to retrive any mail using the imap.php script.
I didn't change it and I don't know why it just stops working. In the beginning after solved the problem described in my above post I've been able to send the recived mails to hesk but non mails where deleted on the server (I modified the delete option to Y without success). Of course I colud live with it ;-). Is there a way to activate/introduce a flow check to see what's appening during the retriving process, like introducing some debug messages to find where the proces fails or when mails are found and correctly processed?

I actually use the following code to chek what's on the mailserver before run the imap.php and be sure there's something to retrive...



------------------------------------------------------------------------------------
<?php
$mbox = imap_open("{imap.server.com/imap/notls:143}", "mymail@mydomain.com", "password");

echo "<h1>Mailboxes</h1>\n";
$folders = imap_listmailbox($mbox, "{imap.mydomain.com/imap/notls:143}", "*");

if ($folders == false) {
echo "Call 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 "Call failed<br />\n";
} else {
foreach ($headers as $val) {
echo $val . "<br />\n";
}
}

imap_close($mbox);
?>

---------------------------------------------------------------------------------
darksidebadman
Posts: 2
Joined: Wed Jan 07, 2009 7:48 pm

Post by darksidebadman »

Tnx ictconsulting, i'll take this in the debug option and change it this weekend
YankeePicker
Posts: 16
Joined: Fri Mar 06, 2009 4:48 pm

Post by YankeePicker »

Great idea!

I'm having a problem with this though. Debug mode says that it is able to access the IMAP mail box just fine. It lists the number of emails as well. There seems to be a problem in the processing of the emails. Right now I have 3 messages in the box, all marked unread. After running the imap.php file only the first email is marked as read, the others appear to be untouched. Also no entries are made in the DB. Any ideas? Is there any other info I can post here that would help?


Listing of my Debug output:

Code: Select all

Notices (11:49:29):
- 3 email(s)

Mailboxes
{imapmail}INBOX
{imapmail}Sent Items
{imapmail}Deleted Items
{imapmail}Drafts

Headers in INBOX
1) 6-Mar-2009 User1 Help Ticket Test (7090 chars)
U 2) 6-Mar-2009 User2 Help Test !!! (1354 chars)
U 3) 6-Mar-2009 User1 Testing Email Ticket - (7166 chars)
jmelhus
Posts: 4
Joined: Mon Mar 02, 2009 11:12 pm

Need some help here :)

Post by jmelhus »

Hi,

I tried to set imap.php up, so far so good :) Nice script!

I've ran into one problem though, think it has something to do with the charset. My ticket in hesk looks like this after running imap.php:





Date: 2009-03-06 22:22:39
Name: =?ISO-8859-1?Q?J=F8rgen_Melhus?=
E-mail: jmelhus@xxxmailxxx.com
IP: email
Printer friendly version Edit post Delete this ticket

Message:

--001636c59549b81539046479e2c8 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit This is a test, wonder if it works -- mvh Jorgen --001636c59549b81539046479e2c8 Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit This is a test, wonder if it works<br clear="all"><br>-- <br>mvh<br><br>Jorgen<br> --001636c59549b81539046479e2c8--




Anyone knows whats wrong? I'm from norway, and it doesnt handle these letters any good: æøå. Could someone point me in the right direction, or a possible solution?

Thanks in advance!

Regards,

Jørgen :D
Julien
Posts: 2
Joined: Mon Mar 09, 2009 1:17 pm

Can't create ticket from IMAP

Post by Julien »

Hello!

When I start imap.php, there is the result:


Notices (14:15:04):
- 2 email(s)
Mailboxes
{imap.ocsa-data.net}INBOX.Sent
{imap.ocsa-data.net}INBOX.Trash
{imap.ocsa-data.net}INBOX.Drafts
{imap.ocsa-data.net}INBOX
Headers in INBOX
1) 9-Mar-2009 OUVATON [gloux] Activation de vot (3252 chars)
U 2) 9-Mar-2009 Association de Chant Aide (1872 chars)

but there is no ticket created...

Any idea?

Thanks

Julien
YankeePicker
Posts: 16
Joined: Fri Mar 06, 2009 4:48 pm

Post by YankeePicker »

Aye, same problem here. I'm trying to work through the code, but so far nothing is jumping out at me.
[color=red]Caution:[/color] YankeePicker may appear smarter than he really is. Advice not to be taken internally. Ask your Doctor if YankeePicker is right for you.
jmelhus
Posts: 4
Joined: Mon Mar 02, 2009 11:12 pm

Re: Need some help here :)

Post by jmelhus »

jmelhus wrote:I've ran into one problem though, think it has something to do with the charset. My ticket in hesk looks like this after running imap.php:

Date: 2009-03-06 22:22:39
Name: =?ISO-8859-1?Q?J=F8rgen_Melhus?=
E-mail: jmelhus@xxxmailxxx.com
IP: email
Printer friendly version Edit post Delete this ticket

Message:

--001636c59549b81539046479e2c8 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit This is a test, wonder if it works -- mvh Jorgen --001636c59549b81539046479e2c8 Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit This is a test, wonder if it works<br clear="all"><br>-- <br>mvh<br><br>Jorgen<br> --001636c59549b81539046479e2c8--

Anyone knows whats wrong? I'm from norway, and it doesnt handle these letters any good: æøå. Could someone point me in the right direction, or a possible solution?
Anyone who knows how I can change the charset so it allows æ ø å? That would be changing from default ISO-8859-1 to UTF-8.

Any help would be appreciated! :)

Regards,

Jørgen
YankeePicker
Posts: 16
Joined: Fri Mar 06, 2009 4:48 pm

Post by YankeePicker »

Is anyone actively working on this add on? Just curious
[color=red]Caution:[/color] YankeePicker may appear smarter than he really is. Advice not to be taken internally. Ask your Doctor if YankeePicker is right for you.
Leetoto
Posts: 4
Joined: Wed Apr 08, 2009 4:47 pm

Great

Post by Leetoto »

So far so good !
I had to spend a few hours but got it working

First of all, I had to contact my support because of some restrictions on imap and self-signed certificates ... but after that , with a few mods, it works perfectly.

Mod done :
host format : $host = "{mail.server.com:143/imap/notls}INBOX";
Insert : I removed custom fields
I removed all "or hesk_error(xxx " because producing some strange output errors. (line 20 and line 45)
I had to change sql statement to add " .$hesk_settings['db_pfix']." prefix


bug :
addedd "/admin" to traking url (line 129) : complete line is

Code: Select all

$trackingURL_admin=$hesk_settings['hesk_url'].'/admin/admin_ticket.php?track='.$trackingID;
Cheers
ictconsulting
Posts: 21
Joined: Sun Feb 01, 2009 2:21 pm

Re: Great

Post by ictconsulting »

Would you please be more clear about the mods you done or better, why not attach the full modified script? I don't know if you're using the original version or another one, better to play with the same one anyway... I didn't also understand why you had to change sql statement and most important where/how to apply this change ;-)
Post Reply