Go Back   CodingForums.com > :: Server side development > PHP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 06-16-2009, 04:16 AM   PM User | #1
kareems
New Coder

 
Join Date: May 2009
Posts: 22
Thanks: 1
Thanked 0 Times in 0 Posts
kareems is an unknown quantity at this point
PHP Email Attachment Help

Hello,

I'm trying to get an attachment from a gmail inbox and save it. However, all the code does is deletes the message from the inbox, but doesn't save it. If anyone can offer any help I'd really appreciate it. Thanks in advance!

Here's the code - I got it, didn't write it.

Code:
<?php
# Coded By Jijo Last Update Date [Jan/19/06] (http://www.phpclasses.org/browse/package/2964.html)
# Updated 2008-12-18 by Dustin Davis (http://nerdydork.com)
	# Utilized $savedirpath parameter
	# Added delete_emails parameter
	
class ReadAttachment
{
	function getdecodevalue($message,$coding) {
		switch($coding) {
			case 0:
			case 1:
				$message = imap_8bit($message);
				break;
			case 2:
				$message = imap_binary($message);
				break;
			case 3:
			case 5:
				$message=imap_base64($message);
				break;
			case 4:
				$message = imap_qprint($message);
				break;
		}
		return $message;
	}


	function getdata($host,$login,$password,$savedirpath,$delete_emails=false) {
		// make sure save path has trailing slash (/)
		$savedirpath = str_replace('\\', '/', $savedirpath);
		if (substr($savedirpath, strlen($savedirpath) - 1) != '/') {
			$savedirpath .= '/';
		}
		
		$mbox = imap_open ($host, $login, $password) or die("can't connect: " . imap_last_error());
		$message = array();
		$message["attachment"]["type"][0] = "text";
		$message["attachment"]["type"][1] = "multipart";
		$message["attachment"]["type"][2] = "message";
		$message["attachment"]["type"][3] = "application";
		$message["attachment"]["type"][4] = "audio";
		$message["attachment"]["type"][5] = "image";
		$message["attachment"]["type"][6] = "video";
		$message["attachment"]["type"][7] = "other";
		
		for ($jk = 1; $jk <= imap_num_msg($mbox); $jk++) {
			$structure = imap_fetchstructure($mbox, $jk , FT_UID);    
			$parts = $structure->parts;
			$fpos=2;
			for($i = 1; $i < count($parts); $i++) {
				$message["pid"][$i] = ($i);
				$part = $parts[$i];
				
				if($part->disposition == "ATTACHMENT") {
					$message["type"][$i] = $message["attachment"]["type"][$part->type] . "/" . strtolower($part->subtype);
					$message["subtype"][$i] = strtolower($part->subtype);
					$ext=$part->subtype;
					$params = $part->dparameters;
					$filename=$part->dparameters[0]->value;
					
					$mege="";
					$data="";
					$mege = imap_fetchbody($mbox,$jk,$fpos);  
					$filename="$filename";
					$fp=fopen($savedirpath.$filename,"w");
					$data=$this->getdecodevalue($mege,$part->type);	
					fputs($fp,$data);
					fclose($fp);
					$fpos+=1;
				}
			}
			if ($delete_emails) {
				// imap_delete tags a message for deletion
				imap_delete($mbox,$jk);
			}
		}
		// imap_expunge deletes all tagged messages
		if ($delete_emails) {
			imap_expunge($mbox);
		}
		imap_close($mbox);
	}
}

function getEmailFile($directory) {
	$attachment = new ReadAttachment;
	$attachment->getdata('{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX', 'address@gmail.com', 'password', 'xml/'.$directory.'/', 'false');
}

getEmailFile('visitors');
kareems is offline   Reply With Quote
Old 06-16-2009, 08:47 PM   PM User | #2
Fumigator
UE Antagonizer


 
Fumigator's Avatar
 
Join Date: Dec 2005
Location: Utah, USA, Northwestern hemisphere, Earth, Solar System, Milky Way Galaxy, Alpha Quadrant
Posts: 7,687
Thanks: 42
Thanked 637 Times in 625 Posts
Fumigator is a glorious beacon of lightFumigator is a glorious beacon of lightFumigator is a glorious beacon of lightFumigator is a glorious beacon of lightFumigator is a glorious beacon of light
Make sure you turn on all error reporting:

PHP Code:
error_reporting(E_ALL);
ini_set("display_errors"1); 
And then add error checking to the fopen() function call, and the fputs() calls too while you're at it.

Check folder and file permissions as well.
__________________
Fumigator is offline   Reply With Quote
Old 06-16-2009, 09:08 PM   PM User | #3
kareems
New Coder

 
Join Date: May 2009
Posts: 22
Thanks: 1
Thanked 0 Times in 0 Posts
kareems is an unknown quantity at this point
Thanks.

Error reporting is on in the file that implements the class. I will turn it on in all other places and report back.

PHP log on my local server reported no errors.

Permissions are all 777.


Quote:
Originally Posted by Fumigator View Post
Make sure you turn on all error reporting:

PHP Code:
error_reporting(E_ALL);
ini_set("display_errors"1); 
And then add error checking to the fopen() function call, and the fputs() calls too while you're at it.

Check folder and file permissions as well.
kareems is offline   Reply With Quote
Old 06-16-2009, 11:25 PM   PM User | #4
kareems
New Coder

 
Join Date: May 2009
Posts: 22
Thanks: 1
Thanked 0 Times in 0 Posts
kareems is an unknown quantity at this point
Okay, I enabled errors. I have:

Warning: imap_fetchstructure() [function.imap-fetchstructure]: Bad message number in /var/www/vhosts/my-domain.com/httpdocs/_inactive/analytics/includes/class.emailattachment.php on line 52

Notice: Trying to get property of non-object in /var/www/vhosts/my-domain.com/httpdocs/_inactive/analytics/includes/class.emailattachment.php on line 53

Any ideas?
kareems is offline   Reply With Quote
Old 06-16-2009, 11:37 PM   PM User | #5
Fumigator
UE Antagonizer


 
Fumigator's Avatar
 
Join Date: Dec 2005
Location: Utah, USA, Northwestern hemisphere, Earth, Solar System, Milky Way Galaxy, Alpha Quadrant
Posts: 7,687
Thanks: 42
Thanked 637 Times in 625 Posts
Fumigator is a glorious beacon of lightFumigator is a glorious beacon of lightFumigator is a glorious beacon of lightFumigator is a glorious beacon of lightFumigator is a glorious beacon of light
For some reason the message number is bad when trying to fetch a message. Echo the message number just before the fetch and see what the value is.
__________________
Fumigator is offline   Reply With Quote
Old 06-16-2009, 11:41 PM   PM User | #6
kareems
New Coder

 
Join Date: May 2009
Posts: 22
Thanks: 1
Thanked 0 Times in 0 Posts
kareems is an unknown quantity at this point
Okay, done. Message number is 1.

There's only one message in the inbox at any time. Do IMAP message numbers start at 1 or 0?

Edit: A google search says 1.

Last edited by kareems; 06-16-2009 at 11:43 PM..
kareems is offline   Reply With Quote
Old 06-16-2009, 11:47 PM   PM User | #7
Fumigator
UE Antagonizer


 
Fumigator's Avatar
 
Join Date: Dec 2005
Location: Utah, USA, Northwestern hemisphere, Earth, Solar System, Milky Way Galaxy, Alpha Quadrant
Posts: 7,687
Thanks: 42
Thanked 637 Times in 625 Posts
Fumigator is a glorious beacon of lightFumigator is a glorious beacon of lightFumigator is a glorious beacon of lightFumigator is a glorious beacon of lightFumigator is a glorious beacon of light
I'll be honest, I've not done IMAP crap with PHP before so I'm just flying by the seat of my pants and what I can glean off the manual.

http://us2.php.net/manual/en/functio...hstructure.php

But I must say, your thought is quite insightful, and looking at the condition of the "for" loop, $jk <= imap_num_msg($mbox), it would indeed read past the end of the message queue if the message numbers start at 0. Try making that $jk < imap_num_msg($mbox), which in your case should read the one message and then drop out of the loop.

(edit) 1? Oh.
__________________
Fumigator is offline   Reply With Quote
Old 06-16-2009, 11:50 PM   PM User | #8
kareems
New Coder

 
Join Date: May 2009
Posts: 22
Thanks: 1
Thanked 0 Times in 0 Posts
kareems is an unknown quantity at this point
Well, I appreciate the effort regardless, thanks for your help!

The weird thing I grabbed this class from a blog, and all comments say it worked for them... I've gotta have a bad setting somewhere. Maybe in my gmail.
kareems is offline   Reply With Quote
Old 06-17-2009, 02:28 AM   PM User | #9
kareems
New Coder

 
Join Date: May 2009
Posts: 22
Thanks: 1
Thanked 0 Times in 0 Posts
kareems is an unknown quantity at this point
I've found the problem.

Gmail doesn't support the disposition object in its messages, so the part that strips the attachment never executes. Unfortunately, disposition is also how you tell that an object is an attachment. Does anyone know any other way to tell what is an attachment??
kareems is offline   Reply With Quote
Old 07-10-2009, 11:52 AM   PM User | #10
cymex
New to the CF scene

 
Join Date: Jul 2009
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
cymex is an unknown quantity at this point
Are you sure Gmail doesn't support it at all?

The Script looks for
Code:
if($part->disposition == "ATTACHMENT") {
Now have a look at the parts Array:

Code:
 
[bytes] => 1478548
            [ifdisposition] => 1
            [disposition] => attachment
            [ifdparameters] => 1
            [dparameters] => Array
                (
                    [0] => stdClass Object
                        (
                            [attribute] => filename
                            [value] => technews.pdf
                        )

                )
Some Mail-Servers call it attachment, others ATTACHMENT.

Replace
Code:
if($part->disposition == "ATTACHMENT")
With
Code:
if($part->disposition == "attachment")
If there is no disposition object at all in the parts array you should find a similar structure with the needed data.



Regards,
Cy

Last edited by cymex; 07-10-2009 at 11:58 AM..
cymex is offline   Reply With Quote
Old 07-20-2012, 08:05 PM   PM User | #11
meenashah
New to the CF scene

 
Join Date: Jul 2012
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
meenashah is an unknown quantity at this point
fetching gmail attachment using php is not working

hello,

I am having problems while fetching gmail inbox attachment, i am nt able to fetch it...the code that i am using is give below.....pls help me......



<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.mainbox
{
width:1180px;
padding:10px;
border:5px solid gray;
margin:0px;
}
.main{
width:1180px;
padding:20px;

float:left;
}

</style>
</head>
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Welcome extends CI_Controller
{
var $dirPath,$deleteEmails=false;
var $imapInBox;

function __construct($mailHost,$emailLogin,$pass) {
parent::__construct($mailHost,$emailLogin,$pass);

$this->imapInBox=imap_open($mailHost,$emailLogin,$pass) or die("Unable to connect:".imap_last_error());
}

function getdecodevalue($msg,$bodyType) {
if($bodyType==0 || $bodyType==1) {
$msg = imap_base64($msg);
}
if($bodyType==2) {
$msg = imap_binary($msg);
}
if($bodyType==3 || $bodyType==5) {
$msg = imap_base64($msg);
}
if($bodyType==4) {
$msg = imap_qprint($msg);
}
return $msg;
}

function downLoadAttachment($dirPath,$deleteEmails=false) {
$nAttachment = 0;
$dirPath = str_replace('\\', '/', $dirPath);
if (substr($dirPath, strlen($dirPath) - 1) != '/') {
$dirPath .= '/';
}
$message = array();
$message["attachment"]["type"][0] = "text";
$message["attachment"]["type"][1] = "multipart";
$message["attachment"]["type"][2] = "message";
$message["attachment"]["type"][3] = "application";
$message["attachment"]["type"][4] = "audio";
$message["attachment"]["type"][5] = "image";
$message["attachment"]["type"][6] = "video";
$message["attachment"]["type"][7] = "other";


$nEmails = imap_search($this->imapInBox, 'ALL', SE_UID);

$j=-1;
echo "<div class = 'mainbox'>";
for ($j = 0; $j < 4;$j++){ //count($nEmails); $j++) {
$j++;
$messStructure = imap_fetchstructure($this->imapInBox, $nEmails[$j] , FT_UID);

$overview = imap_fetch_overview($this->imapInBox,$j ,0);
echo '<div class="main"><h1>Read/Unread : '.($overview[0]->seen ? 'read' : 'unread').'</h1>';
echo '<h2>Subject:: '.$overview[0]->subject.'</h2> ';
echo '<h3>From:: '.$overview[0]->from.'</h3>';
echo '<h4>On:: '.$overview[0]->date.'</h4>';
$structure = imap_fetchstructure($this->imapInBox,$j);

$body = imap_fetchbody($this->imapInBox,$j ,2);


if($structure->encoding == 3) {
$body = imap_base64($body);

} else if($structure->encoding == 4) {
$body = imap_qprint($body);

}
else{
$body = imap_base64($body);
}

//echo $body;
echo '</div>';


if(isset($messStructure->parts)) {
//$parts = $messStructure->parts;
$fpos=2;

for($i = 1; $i < 15;$i++){//count($parts); $i++) {
$message["pid"][$i] = ($i);

/* if($messStructure->parts[$i]->ifdisposition == '1'){
$part = $messStructure->parts[$i];

if(isset($messStructure->parts[$i]->ifdisposition) && $messStructure->parts[$i]->disposition == "ATTACHMENT") {
//$message["type"][$i] = $message["attachment"]["type"][$part->type] . "/" . strtolower($parts[i]->subtype);
// $message["subtype"][$i] = strtolower($part->subtype);
//$fileName=$part->parameters[0]->value;
//$mess = imap_fetchbody($this->imapInBox,$j+1,$fpos);
//$fp=fopen($dirPath.$fileName, 'w');
//$data=$this->getdecodevalue($mess,$part->type);
//fwrite($fp,$data);
//fclose($fp);
//$nAttachment++;
//$fpos+=1;
}
}
else{

echo "<h3>"."No Attachement with this Email"."</h3>";
} */

}

}

}
echo "</div>";

imap_close($this->imapInBox);
return ("Completed ($nAttachment attachment(s) downloaded into $dirPath)");
}
}

$mailHost="{imap.gmail.com:993/imap/ssl}INBOX";
$emailLogin="username";
$pass="password";
$dirPath=$_SERVER['DOCUMENT_ROOT']."/test/gmail/";
$deleteEmails=false;
$mailObj=new Welcome($mailHost,$emailLogin,$pass);
?>
<div class="box"><?php

echo $mailObj->downLoadAttachment($dirPath,$deleteEmails=false);
echo $mailHost;
echo $emailLogin;
echo $pass;

?>
</div>
meenashah is offline   Reply With Quote
Reply

Bookmarks

Tags
attachment, email, imap, php

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 03:00 AM.


Advertisement
Log in to turn off these ads.