1

I am trying to fetch emails from my Gmail account, and programmatically create nodes. I was able to create nodes with simple body text and title from subject but the problem is with attachments. Please have a look on my code & help me if you can.

function _mailreader_connect_mail(){
    $hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
    $username = '*****@gmail.com';
    $password = '******';

    $inbox = imap_open($hostname,$username,$password) or die(t('Cannot connect to Gmail: ' . imap_last_error()));
    $emails = imap_search($inbox,'UNREAD');
    dpm("Messages count: " . count($emails));
    $Msgcount = count($emails);
    //echo "Email :".$emails;
    for ($x = 1; $x <= $Msgcount; $x++){
        $overview = imap_fetch_overview($inbox, $x);
        $title = $overview[0]->subject;
        $struct = imap_fetchstructure($inbox,$x);
        $contentParts = count($struct->parts);
        if ($contentParts >= 2) {
            for ($i=2;$i<=$contentParts;$i++) {
                $att[$i-2] = imap_bodystruct($inbox,$x,$i);
            }
            for ($k=0;$k<sizeof($att);$k++) {
                if ($att[$k]->parameters[0]->value == "us-ascii" || $att[$k]->parameters[0]->value == "US-ASCII"){
                    if ($att[$k]->parameters[1]->value != "") {
                        $selectBoxDisplay[$k] = $att[$k]->parameters[1]->value;
                    }
                } 
                elseif ($att[$k]->parameters[0]->value != "iso-8859-1" && $att[$k]->parameters[0]->value != "ISO-8859-1"){
                    $selectBoxDisplay[$k] = $att[$k]->parameters[0]->value;
                }
            }
        }

        if (sizeof($selectBoxDisplay) > 0) {
            echo "<select name=\"attachments\" size=\"3\" class=\"tblContent\"    onChange=\"handleFile(this.value)\" style=\"width:170;\">";
            for ($j=0;$j<sizeof($selectBoxDisplay);$j++) {
                $filename = $selectBoxDisplay[$j];
                echo "\n<option value=\"$j\">". $selectBoxDisplay[$j] ."</option>";
            }
            echo "</select>";
        }

        $strFileName = $att[$file]->parameters[0]->value;
        $strFileType = strrev(substr(strrev($strFileName),0,4));
        $fileContent = imap_fetchbody($inbox, $x, $file+2);
        $ContentType = "application/octet-stream";
        /* 
        if ($strFileType == ".jpg" || $strFileType == "jpeg" || $strFileType == ".JPG")
        $ContentType = "image/jpeg";
        header ("Content-Type: $ContentType"); 
        header ("Content-Disposition: attachment; filename=$strFileName; size=$fileSize;"); 
        if (substr($ContentType,0,4) == "text") {
            echo imap_qprint($fileContent);
        } 
        else {
            echo imap_base64($fileContent);
        }           
        */

        if($title != ''){
            list($content_type, $title_text) = explode(', ', $title);
            //default for file
            $file = imap_base64($fileContent);              
            //$details = stat($file);
            //$filesize = $details['size'];
            //$mtime = $details['mtime'];
            //$date_value = date('Y-m-d\T00:00:00',$mtime);

            //Node Object
            $node = new stdClass();
            $node->type = $content_type;
            $node->uid = 1;
            $node->title = $title_text;
            $node->body = imap_fetchbody($inbox, $x, 1);
            $node->status = 1;
            $node->promote = 0;
            $node->language = 'en';

            //file handling code
            $dest = file_directory_path();
            // copy the file to the files directory 
            if(!file_copy($file, $dest)) {
                echo "Failed to move file: $file\n";
                continue;
            } 
            else {
                //file_move might change the name of the file
                $name = basename($file);
            }
            // build file object
            $file_obj = new stdClass();
            $file_obj->filename = $filename;
            $file_obj->filepath = $file;
            $file_obj->filemime =  file_get_mimetype($filename);
            $file_obj->filesize = $filesize;
            //$file_obj->filesource = $filename;
            $file_obj->uid = 1;
            $file_obj->status = FILE_STATUS_TEMPORARY;
            $file_obj->timestamp = time();
            $file_obj->list = 1;
            $file_obj->new = true;

            // save file to database
            drupal_write_record('files', $file_obj);

            // change file status to permanent (default is temporary)
            file_set_status($file_obj,1);

            $node->files[$file_obj->fid] = $file_obj;   
            node_object_prepare($node);
            $node = node_save($node);
            echo "Node Created Succesfully with Title : ".$title_text;
            echo "</br>";
            //imap_delete($inbox, $x);
        }
        else{
            echo "There is no mails to fetch";
        }
    }
    //imap_expunge($inbox);
    return $output;
}
  • What is the problem with attachments? We're not mind readers :) – Clive Jun 12 '12 at 9:57
  • why not file_save ? (are you in d6 ?) api.drupal.org/api/drupal/includes%21file.inc/function/… – mojzis Jun 12 '12 at 10:53
  • @Clive - When I am opening the created node, it is coming some things like - --047d7b15ab35c90e6704c2427b68 Content-Type: text/plain; charset=ISO-8859-1 This mail is with attachment. --047d7b15ab35c90e6704c2427b68 Content-Type: text/html; charset=ISO-8859-1 This mail is with attachment. --047d7b15ab35c90e6704c2427b68-- – RajeevK Jun 12 '12 at 13:10
  • @mojzis - Yes I am using D6...so this file_save() is irrelevant for my code.. – RajeevK Jun 12 '12 at 13:22
  • you might want to break up your function into a few smaller functions ... just a thought :). attachments are not necessarily base64 encoded, see this SO example stackoverflow.com/a/3347846 – tenken Jun 12 '12 at 16:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.