Tuesday , 30 September 2014
Home » PHP Programming » POP3/IMAP Email with attachment-Read & Forwarding with PHP
Do you know how we can read, forward or transfer the POP3/IMAP email to another email address ? I came across this situation. I need to read the email from one account and need to forward that mail to another email account.

POP3/IMAP Email with attachment-Read & Forwarding with PHP

Hello Friends,

Do you know how we can read, forward or transfer the POP3/IMAP email to another email address ? I came across this situation. I need to read the email from one account and need to forward that mail to another email account. I searched google for such a script but did not get it. Finally i went through IMAP PHP functions and here i am sharing a script using which you can read, forward or delete the email. Email can be simple or with attachment.

Note: I was working with Zend Framework, so i used the Zend library for sending email(forwarding email). You can use simple mail function also.

<?php
  // Change to your mail server
  $host = "mail.programmingfacts.com";
 
  // Connecting to POP3 email server.
  $connection = imap_open("{" . $host . ":110/pop3/notls}", 'rakshit@programmingfacts.com', 'password');
 
  // Total number of messages in Inbox
  $count = imap_num_msg($connection);
  echo $count . " messages found<br />";
 
  // Read Messages in Loop, Forward it to Actual User email and than delete it from current email account.
  for ($i = 1; $i <= $count; $i++) {
      $headers = imap_headerinfo($connection, $i);
      
      $subject = $headers->subject;
      
      $from = $headers->from[0]->mailbox . '@' . $headers->from[0]->host;
      if ($headers->cc[0]->mailbox)
          $cc = $headers->cc[0]->mailbox . '@' . $headers->cc[0]->host;
      $subject = $headers->subject;
      
      $structure = imap_fetchstructure($connection, $i);
      $type = $this->get_mime_type($structure);
      
      // GET HTML BODY
      $body = $this->get_part($connection, $i, "");
      
      //$raw_body = imap_body($connection, $i);
      
      $attachments = array();
      
      if (isset($structure->parts) && count($structure->parts)) {
          for ($e = 0; $e < count($structure->parts); $e++) {
              $attachments[$e] = array('is_attachment' => false, 'filename' => '', 'name' => '', 'attachment' => '');
              
              if ($structure->parts[$e]->ifdparameters) {
                  foreach ($structure->parts[$e]->dparameters as $object) {
                      if (strtolower($object->attribute) == 'filename') {
                          $attachments[$e]['is_attachment'] = true;
                          $attachments[$e]['filename'] = $object->value;
                      } //if (strtolower($object->attribute) == 'filename')
                  } //foreach ($structure->parts[$e]->dparameters as $object)
              } //if ($structure->parts[$e]->ifdparameters)
              
              if ($structure->parts[$e]->ifparameters) {
                  foreach ($structure->parts[$e]->parameters as $object) {
                      if (strtolower($object->attribute) == 'name') {
                          $attachments[$e]['is_attachment'] = true;
                          $attachments[$e]['name'] = $object->value;
                      } //if (strtolower($object->attribute) == 'name')
                  } //foreach ($structure->parts[$e]->parameters as $object)
              } //if ($structure->parts[$e]->ifparameters)
              
              if ($attachments[$e]['is_attachment']) {
                  $attachments[$e]['attachment'] = @imap_fetchbody($connection, $i, $e + 1);
                  if ($structure->parts[$e]->encoding == 3) {
                      // 3 = BASE64
                      $attachments[$e]['attachment'] = base64_decode($attachments[$e]['attachment']);
                  } //if ($structure->parts[$e]->encoding == 3)
                  elseif ($structure->parts[$e]->encoding == 4) {
                      // 4 = QUOTED-PRINTABLE
                      $attachments[$e]['attachment'] = quoted_printable_decode($attachments[$e]['attachment']);
                  } //elseif ($structure->parts[$e]->encoding == 4)
              } //if ($attachments[$e]['is_attachment'])
              
              if ($attachments[$e]['is_attachment']) {
                  $filename = $attachments[$e]['filename'];
                  $filename = $attachments[$e]['name'];
                  $filecontent = $attachments[$e]['attachment'];
              } //if ($attachments[$e]['is_attachment'])
          } //for ($e = 0; $e < count($structure->parts); $e++)
      } //if (isset($structure->parts) && count($structure->parts))
      /**** ****/
      
      
      /*echo "<pre>";
      echo "From: " . $headers->Unseen . "<br />";
      echo "From: " . $from . "<br />";
      echo "Cc: " . $cc . "<br />";
      echo "Subject: " . $subject . "<br />";
      echo "Content Type: " . $type . "<br />";
      echo "Body: " . $body . "<br />";*/
      $mail = new Zend_Mail();
      
      $mail->settype(Zend_Mime::MULTIPART_MIXED);
      
      for ($k = 0; $k < count($attachments); $k++) {
          $filename = $attachments[$k]['name'];
          $filecontent = $attachments[$k]['attachment'];
          
          if ($filename && $filecontent) {
              $file = $mail->createAttachment($filecontent);
              $file->filename = $filename;
          } //if ($filename && $filecontent)
      } //for ($k = 0; $k < count($attachments); $k++)
      
      
      $mail->setFrom($from);
      $mail->addTo('rakshit@programmingfacts.com');
      if ($cc)
          $mail->addCc($cc);
      $mail->setSubject($subject);
      $mail->setBodyHtml($body);
      $mail->send();
      
      // Mark the email messages once read
      //imap_delete($mbox, 1);
  } //for ($i = 1; $i <= $count; $i++)
  // Delete all marked message from current email account.
  imap_expunge($mbox);
?>

About Rakshit Patel

I am PHP Freelancer, Rakshit Patel AKA WordPress Freelancer working as PHP Programmer India. I am here to share all my developing knowledge, quick coding techniques, quick solutions to save your time and help you guys for any issue or bug fixing. If you have any PHP, WordPress, Magento related work, please contact me. I am interested for the work.

19 comments

  1. Hi

    I have tried this and it works for me, but i can seem to get it to Forward the email and then delete it from the server.

    Can you help

  2. Hi

    I have tried this and it works for me, but i can seem to get it to Forward the email and then delete it from the server.

    Can you help

  3. Hi,

    // Mark the email messages once read
    //imap_delete($mbox, 1);
    } //for ($i = 1; $i <= $count; $i++)
    // Delete all marked message from current email account.
    imap_expunge($mbox);

    This are the lines used to delete Email messages from server. I gave comment in imap_delete($mbox, 1); line.

    Please check it out.

    Thanks.

  4. Hi,

    // Mark the email messages once read
    //imap_delete($mbox, 1);
    } //for ($i = 1; $i <= $count; $i++)
    // Delete all marked message from current email account.
    imap_expunge($mbox);

    This are the lines used to delete Email messages from server. I gave comment in imap_delete($mbox, 1); line.

    Please check it out.

    Thanks.

  5. And how to i get it to Forward it? I have tried it but its still not Forwarding it.

    Thank you

  6. And how to i get it to Forward it? I have tried it but its still not Forwarding it.

    Thank you

  7. For forwarding mail, i have already written code. You can debug the code and check wheres the problem is.

  8. For forwarding mail, i have already written code. You can debug the code and check wheres the problem is.

  9. Hey, I was wondering how I would implement a filter to only forward emails sent to a specific email address. For example gmail can receive emails from multiple addresses ie support@company.com and admin@company.com

    How could I get this script to only forward emails where to = support@company.com to say the support guy?

    This is the most efficient way I can think of setting forwarding addresses for multiple inboxes using the gmail SMTP servers in a php script short of opening a gmail account for each email address. Unless you can think of another way? (I want admins to be able to change the forwarding addresses without having access to the actual gmail page)

  10. Hey, I was wondering how I would implement a filter to only forward emails sent to a specific email address. For example gmail can receive emails from multiple addresses ie support@company.com and admin@company.com

    How could I get this script to only forward emails where to = support@company.com to say the support guy?

    This is the most efficient way I can think of setting forwarding addresses for multiple inboxes using the gmail SMTP servers in a php script short of opening a gmail account for each email address. Unless you can think of another way? (I want admins to be able to change the forwarding addresses without having access to the actual gmail page)

  11. This is the best tutorial on the web I have found on this subject,

  12. If attachment is a Image, how to show it?

  13. Hello, I am getting output as “messages found” but emails are not forwarded to my email server. Can I know where the error is at? And what is Zend do I need to install something called as Zend to forward my email?

  14. HI same problem is with me .. do rpl
    on
    findjassi@gmail.com

    Hello, I am getting output as “messages found” but emails are not forwarded to my email server. Can I know where the error is at? And what is Zend do I need to install something called as Zend to forward my email?

  15. Hi
    I’ve tried your script but it has an error which clearly I can’t resolve by myself
    If you search in your code $this you will see it ;)
    What’s the class of $this or if possible provide the methods used with $this
    Thanks

  16. Doesn’t work with $this->get_mime_type??

  17. what does the “get_part” function do?

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>