07 July 2013

Forward email to a predefined email address using PHP


Few days ago, I was looking for a script for my CRM (Customer Relationship Management) software that will simply forward all the emails received at a common address to their respective sales agent.

After few hrs I had successfully managed to write this script using PHP

In this script i am using PHPMAILER class in order to send emails and imap utility to fetch and read emails



<?php
 
/*  
    Author:Devi Techno Solutions
    Email : manish@devitechnosolutions.com
*/

require_once('class.phpmailer.php');

/* connect to Mailer Server to Read Emails */
$inbox = imap_open($imap_host_name,$imap_user_name,$imap_password) or die('Cannot connect to IMAP: ' . imap_last_error());

// Connect with SMTP to Send Emails
$mail = new PHPMailer();
$mail->IsSMTP(); 
$mail->SMTPDebug  = 0;
$mail->SMTPAuth   = true;
$mail->Host  = $smtp_host;

// Change these settings according to needs
$mail->Port  = $smtp_port;  
$mail->SMTPSecure = "ssl";

$mail->Username  = $smtp_username; 
$mail->Password  = $smtp_password;  

//Read all the Emails
$emails = imap_search($inbox,'UNSEEN');

if($emails) {
 
 rsort($emails);
 
 foreach($emails as $email_number) {
  
  $overview = imap_fetch_overview($inbox,$email_number,0);
  $message = imap_fetchbody($inbox,$email_number,1.2);
  $structure = imap_fetchstructure($inbox,$email_number);
  $header = imap_headerinfo($inbox, $email_number);
  
  $attachments = array();
  
  if(isset($structure->parts) && count($structure->parts)) {
   
   for($i = 0; $i < count($structure->parts); $i++) {
    
    $attachments[$i] = array(
      'is_attachment' => false,
      'filename' => '',
      'name' => '',
      'attachment' => ''
     );
    
    if($structure->parts[$i]->ifdparameters) {
     foreach($structure->parts[$i]->dparameters as $object) {
      if(strtolower($object->attribute) == 'filename') {
       $attachments[$i]['is_attachment'] = true;
       $attachments[$i]['filename'] = $object->value;
      }
     }
    }

    if($structure->parts[$i]->ifparameters) {
     foreach($structure->parts[$i]->parameters as $object) {
      if(strtolower($object->attribute) == 'name') {
       $attachments[$i]['is_attachment'] = true;
       $attachments[$i]['name'] = $object->value;
      }
     }
    }
    
    if($attachments[$i]['is_attachment']) {
     $attachments[$i]['attachment'] = imap_fetchbody($inbox, $email_number, $i+1);
     if($structure->parts[$i]->encoding == 3) { // 3 = BASE64
      $attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
     } elseif($structure->parts[$i]->encoding == 4) { // 4 = QUOTED-PRINTABLE
      $attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
     }
    }
   } 
  } 
  
  $file_attachments = array();
  if(count($attachments) != 0){
   foreach($attachments as $at){
    if($at[is_attachment]==1){
     $fname = $at['filename'];
     $file_attachments[] = "attachments/$fname";
     $fp = fopen("attachments/$fname","w");
     fwrite($fp, $at['attachment']);
     fclose($fp);
    }
            }
  }
  
  $subject = $overview[0]->subject;
  $from = $overview[0]->from;
  $fromEmail = $header->from[0]->mailbox . "@" . $header->from[0]->host;
  
  $mail->SetFrom($fromEmail, $from);
  $mail->Subject  = $subject;
  $body = $message;
  $mail->MsgHTML($body);
  
  $mail->AddAddress($recepeint_email_address, $recepeint_name);
  if(!empty($file_attachments)){
   foreach($file_attachments as $file){
    $mail->AddAttachment($file);
   }
  }
  $mail->Send();
 }
} 

?>

Replace the following variables with their respective values

$imap_host_name = '{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX'; // eg '{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX';
 $imap_user_name = '';
 $imap_password = ''; 
 
 $smtp_host = 'smtp.gmail.com';
 $smtp_username = '';
 $smtp_password = '';
 $smtp_port = '465';
 
 
 $recepeint_email_address = 'goyalmanish47@gmail.com';
 $recepeint_name = 'Manish Goyal';

Note: When you run this Script, Create a folder named attachment where all the attachments are downloaded and attach to email again

No comments:

Post a Comment