(PHP 5 >= 5.1.3, PHP 7)

imap_savebodySave a specific body section to a file


bool imap_savebody ( resource $imap_stream , mixed $file , int $msg_number [, string $part_number = "" [, int $options = 0 ]] )

Saves a part or the whole body of the specified message.



An IMAP stream returned by imap_open().


The path to the saved file as a string, or a valid file descriptor returned by fopen().


The message number


The part number. It is a string of integers delimited by period which index into a body part list as per the IMAP4 specification


A bitmask with one or more of the following:

  • FT_UID - The msg_number is a UID
  • FT_PEEK - Do not set the \Seen flag if not already set
  • FT_INTERNAL - The return string is in internal format, will not canonicalize to CRLF.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

add a note add a note

User Contributed Notes 4 notes

5 years ago
By using imap_fetchbody() you may run in trouble by using too much memory. Using imap_savebody() may prevent this.

But the content will be encoded, in other words it is useless. Adding a filter can help here.

= fopen('./incomming/tmp.tif','w');


imap_savebody ($mbox, $whandle, $i, $partcounter++);


NOTE: To find the proper filter you need to check the encoding given by the structure of the body.
stupergenius at gmail dot com
10 years ago
This function will save ALL information from the email if the part number is left out. Pretty handy for archiving.
janus at forty-seven dot info
9 years ago
It seems that imap_savebody saves attachments with special characters above ascii 127 as quoted printable.
But if you need it in utf8, you may use the imap_qprint function after the attachment is saved:

= "/path/to/attachment";
$tFileHandle = fopen($tFile, "r");

//get the content of the file into a string
$tFileOutput = $tFileOutput . fgets($tFileHandle, 4096);

fclose ($tFileHandle);
$tFileHandle = fopen($tFile, "w");
//write the new 8Bit string to the file
fwrite($tFileHandle, imap_qprint($tFileOutput));
fclose ($tFileHandle);
technocraze at gmail dot com
10 years ago
I tried to use this function. But it seems it requires php_zip.dll to be load..  i got the php errror like below.

[20-Dec-2007 13:38:17] PHP Warning:  PHP Startup: Unable to load dynamic library './php_zip.dll' - ./php_zip.dll: cannot open shared object file: No such file or directory in Unknown on line 0
[20-Dec-2007 13:38:17] PHP Fatal error:  Call to undefined function imap_savebody() in /opt/oss/share/apache2/htdocs/blogtest/wp-inst/batch/pop3_mail.php on line 153
To Top