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);
?>

20 Comments on POP3/IMAP Email with attachment-Read & Forwarding with PHP

  • Ge Vieira
    July 20, 2010 at 12:17 pm

    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

  • Ge Vieira
    July 20, 2010 at 5:47 pm

    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

  • Rakshit Patel
    July 20, 2010 at 3:36 pm

    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.

  • Rakshit Patel
    July 20, 2010 at 9:06 pm

    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.

  • Ge Vieira
    July 20, 2010 at 3:48 pm

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

    Thank you

  • Ge Vieira
    July 20, 2010 at 9:18 pm

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

    Thank you

  • Rakshit Patel
    July 21, 2010 at 5:47 am

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

  • Rakshit Patel
    July 21, 2010 at 11:17 am

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

  • Adrian
    August 11, 2010 at 12:50 pm

    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)

  • Adrian
    August 11, 2010 at 6:20 pm

    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)

  • Trump Network
    March 9, 2011 at 7:05 am

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

  • short code
    July 18, 2011 at 11:52 am

    If attachment is a Image, how to show it?

  • Karthik Malla
    August 13, 2011 at 9:44 am

    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?

  • Jaspreet
    April 19, 2012 at 2:29 pm

    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?

  • Moein
    May 31, 2012 at 3:22 am

    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

  • RS
    June 19, 2013 at 4:50 am

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

  • Stefan
    July 2, 2013 at 2:54 pm

    what does the “get_part” function do?

  • Anand
    February 7, 2015 at 11:41 am

    I am also getting the same error for $this out of context.

    Can you tell where i have done wrong.

Leave a Reply

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

Sponsors

Sponsors

Recommended

DHgate Computers
DHgate.com - Computers, Cell Phones & more
  • We find everbuying built in php and use css to control the style.

About Author

PHP Freelancer

PHP Freelancer I am PHP Freelancer, Rakshit Patel working as PHP Programmer India. I am here to share all my developing knowledge with you people. For Hire PHP Developer India, contact me.
Follow on twitter: @raxit4u2

Get Free Programming Tutorials:

Become a Fan

Popular Topics

Recent Posts

Most Popular

Recent Comments

Get a Free Quote
$
$
$
Security Question: 3 + 8 = ?
$