How to save the attachments of a email in php?

2019-07-19 15:17发布

I am retrieving the emails and then parsing into the database.

But the problem is i am able to retrieve the email but the attachment part is also shown on the browser.I need to save this attachment part to the some location .The format of attachment is text/plain.

here is my code

<?php
    $inbox=imap_open("{xyz.com:995/pop3/ssl/novalidate-cert}INBOX", "username", "password");
    $count = imap_num_msg($inbox);

    for($i = 1; $i <= 1; $i++) {
     $raw_body = imap_body($inbox, $i);
     echo $raw_body;
     imap_delete($inbox, 1);
    }
    imap_expunge ($inbox);
?>

here i have retrievd a email

But i dont know how to save the attachment . The attachment is also shown below the body of the email when i am using the imap_body.

So how should i separate these two..

标签: php email imap
2条回答
ゆ 、 Hurt°
2楼-- · 2019-07-19 15:46

by analysing the mail with imap_fetchstructure() you can get a list to the different parts of the mail. With a imap_fetchstructure(), you actually take the parts interesting to you. Have a look at the latter documentation for an example code in the comments.

查看更多
疯言疯语
3楼-- · 2019-07-19 15:54

Well now you know how to extract the attachments from the email source from Lars response. I think you might also need to decode the attachment. To do that you need to know how it was coded. 1. base64_encode() 2. chunk_split()

The code to encode a file looks like this:

<?php
$body .= "--".$boundary1 . $this->line;
$body .= "Content-Type: " . $file_type . "; name=\"" . $file_name . "\"" . $this->line;
$body .= "Content-Transfer-Encoding: base64" . $this->line;
$body .= "Content-Disposition: attachment; filename=\"" . $file_name . "\"; size=" . $file_size . ";" . $this->line;
$body .= $this->line; // empty line

$fp = fopen($file_url, 'r');
do {
  $data = fread($fp, 8192);
  if (strlen($data) == 0) break;
  $content .= $data;
}
while (true);

$body .= chunk_split(base64_encode($content));
$body .= $this->line;
$body .= $this->line;
?>

The result is something like this:

--ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ
Content-Type: text/plain; name="sample.txt"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="sample.txt"; size=123;

AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==

Now to decode it you need to do the 2 things again in reverse. 1. take the encoded part and strip all lines so you have a single line string 2. decode it .. and of course save file to disk :)

查看更多
登录 后发表回答