Encaminhamento automático de e-mails com PHP
10/07/2016
0
Pessoal, hoje me deparei coma necessidade de um grupo de e-mail e encaminhar todas a mensagens que chegassem para uma determinada conta, porém minha os hospedagam não oferece este tipo de serviço.
Diante de deste problemas gastaria saber se á possível criar algum script em PHP para isso? Pois preciso apenas que verifique de tempo em tempo se há novas mensagens na caixa postal e faça faça o encaminhamento automaticamente para um grupo x de e-mail.
Moisés
Posts
10/07/2016
Raylan Zibel
O processo pra você seria ler a caixa de entrada e encaminhar cada e-mail pra conta que quiser. Verifique se sua hospedagem fornece tarefas agendadas (Cron Job) pra automatizar a execução.
// receivemail.class.php
<?php error_reporting(0); class receiveMail { var $server=''''; var $username=''''; var $password=''''; var $marubox=''''; var $email=''''; function receiveMail($username,$password,$EmailAddress,$mailserver=''localhost'',$servertype=''pop'',$port=''110'',$ssl = false, $marcar_como_lida = false) //Constructure { if($marcar_como_lida){ $so_ler = ""; } else { $so_ler = "/readonly"; } if($servertype==''imap'') { if($port=='''') { $port=''143''; } $strConnect=''{''.$mailserver.'':''.$port. ''/novalidate-cert/imap''.$so_ler.($ssl ? "/ssl" : "").''}INBOX''; } else { $strConnect=''{''.$mailserver.'':''.$port. ''/novalidate-cert/pop3''.$so_ler.($ssl ? "/ssl" : "").''}INBOX''; } $this->server = $strConnect; $this->username = $username; $this->password = $password; $this->email = $EmailAddress; } function connect() //Connect To the Mail Box { $this->marubox = imap_open($this->server,$this->username,$this->password); if(!$this->marubox) { echo "Error: Problemas ao se conectar no servidor"; exit; } else { /* $check = imap_mailboxmsginfo($this->marubox); if ($check) { echo "Date: " . $check->Date . "<br />\n" ; echo "Driver: " . $check->Driver . "<br />\n" ; echo "Mailbox: " . $check->Mailbox . "<br />\n" ; echo "Messages: " . $check->Nmsgs . "<br />\n" ; echo "Recent: " . $check->Recent . "<br />\n" ; echo "Unread: " . $check->Unread . "<br />\n" ; echo "Deleted: " . $check->Deleted . "<br />\n" ; echo "Size: " . $check->Size . "<br />\n" ; } else { echo "imap_mailboxmsginfo() failed: " . imap_last_error() . "<br />\n"; } */ } } function getHeaders($mid) // Capturar os cabeçalhos da mensagem { if(!$this->marubox) return false; $mail_header=imap_header($this->marubox,$mid); $sender=$mail_header->from[0]; $sender_replyto=$mail_header->reply_to[0]; if(strtolower($sender->mailbox)!=''mailer-daemon'' && strtolower($sender->mailbox)!=''postmaster'') { $mail_details=array( ''from''=>strtolower($sender->mailbox).''@''.$sender->host, ''fromName''=>$sender->personal, ''toOth''=>strtolower($sender_replyto->mailbox).''@''.$sender_replyto->host, ''toNameOth''=>$sender_replyto->personal, ''subject''=>$mail_header->subject, ''to''=>strtolower($mail_header->toaddress), ''date''=>strtolower($mail_header->date) ); } return $mail_details; } function get_mime_type(&$structure) //Capturando o mime type dos arquivos { $primary_mime_type = array("TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER"); if($structure->subtype) { return $primary_mime_type[(int) $structure->type] . ''/'' . $structure->subtype; } return "TEXT/PLAIN"; } function get_part($stream, $msg_number, $mime_type, $structure = false, $part_number = false) //Capturando as partes internas das mensagens { if(!$structure) { $structure = imap_fetchstructure($stream, $msg_number); } if($structure) { if($mime_type == $this->get_mime_type($structure)) { if(!$part_number) { $part_number = "1"; } $text = imap_fetchbody($stream, $msg_number, $part_number); if($structure->encoding == 3) { return imap_base64($text); } else if($structure->encoding == 4) { return imap_qprint($text); } else { return $text; } } if($structure->type == 1) /* multipart */ { while(list($index, $sub_structure) = each($structure->parts)) { $prefix = ""; if($part_number) { $prefix = $part_number . ''.''; } $data = $this->get_part($stream, $msg_number, $mime_type, $sub_structure, $prefix . ($index + 1)); if($data) { return $data; } } } } return false; } function getTotalMails() //Obtendo o total de emails da caixa de entrada { if(!$this->marubox) return false; $headers=imap_headers($this->marubox); return count($headers); } function GetAttach($mid,$path) // Obtendo os arquivos anexos. { if(!$this->marubox) return false; $struckture = imap_fetchstructure($this->marubox,$mid); $ar=""; if($struckture->parts) { foreach($struckture->parts as $key => $value) { $enc=$struckture->parts[$key]->encoding; if($struckture->parts[$key]->ifdparameters) { $name=$struckture->parts[$key]->dparameters[0]->value; $message = imap_fetchbody($this->marubox,$mid,$key+1); if ($enc == 0) $message = imap_8bit($message); if ($enc == 1) $message = imap_8bit ($message); if ($enc == 2) $message = imap_binary ($message); if ($enc == 3) $message = imap_base64 ($message); if ($enc == 4) $message = quoted_printable_decode($message); if ($enc == 5) $message = $message; $fp=fopen($path.$name,"w"); fwrite($fp,$message); fclose($fp); $ar=$ar.$name.","; } if($struckture->parts[$key]->parts) { foreach($struckture->parts[$key]->parts as $keyb => $valueb) { $enc=$struckture->parts[$key]->parts[$keyb]->encoding; if($struckture->parts[$key]->parts[$keyb]->ifdparameters) { $name=$struckture->parts[$key]->parts[$keyb]->dparameters[0]->value; $partnro = ($key+1).".".($keyb+1); $message = imap_fetchbody($this->marubox,$mid,$partnro); if ($enc == 0) $message = imap_8bit($message); if ($enc == 1) $message = imap_8bit ($message); if ($enc == 2) $message = imap_binary ($message); if ($enc == 3) $message = imap_base64 ($message); if ($enc == 4) $message = quoted_printable_decode($message); if ($enc == 5) $message = $message; $fp=fopen($path.$name,"w"); fwrite($fp,$message); fclose($fp); $ar=$ar.$name.","; } } } } } $ar=substr($ar,0,(strlen($ar)-1)); return $ar; } function getBody($mid) // Capturando o corpo da mensagem { if(!$this->marubox) return false; $body = $this->get_part($this->marubox, $mid, "TEXT/HTML"); if ($body == "") $body = $this->get_part($this->marubox, $mid, "TEXT/PLAIN"); if ($body == "") { return ""; } return $body; } function deleteMails($mid) // Deletando um email { if(!$this->marubox) return false; imap_delete($this->marubox,$mid); } function close_mailbox() //Fechando a conexão com o servidor { if(!$this->marubox) return false; imap_close($this->marubox, CL_EXPUNGE); } } ?>
// exibe_emails.php
<html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> </head> <body> <?php include_once("receivemail.class.php"); //criando o objeto com os parametros solicitados pelo método da classe receiveMail $obj = new receiveMail('''','''','''','''',''imap'','''', true, false); //fazendo a conexão $obj->connect(); //recuperando com um laço as mensagens e seus anexos. $headers = imap_headers($obj->marubox); $naolidos = 0; for($i=sizeof($headers); $i>0; $i--){ $flags = substr($headers[$i-1], 0, 4); $isunr = true;//(strpos($flags, "U") != false); if ($isunr){ $naolidos++; echo "<div style=''background-color:#E6E6E6;margin:50px;padding:50px;''>"; $head=$obj->getHeaders($i); $elements = imap_mime_header_decode($head[''subject'']); $assunto = ""; $caracteres = strtolower(imap_utf8($elements[0]->charset)); foreach($elements as $ele){ if(($caracteres != ''default'') and (($caracteres != ''utf-8'')) and ($caracteres != ''windows-1252'')) $assunto .= utf8_encode(imap_utf8($ele->text)) . " "; else $assunto .= (imap_utf8($ele->text)) . " "; } echo "<b>Assunto :: </b>" . $assunto; echo "<br>"; echo "<b>Destinos ::</b> ".$head[''to'']."<br>"; echo "<b>Origem ::</b> ".$head[''from'']."<br>"; echo "<b>Data ::</b> ".$head[''date'']."<br>"; echo "<b>Caracteres ::</b> ".$elements[0]->charset."<br>"; echo "<b>Mensagem ::</b><br>"; //obtendo o corpo de cada mnensagem echo "<blockquote>"; if(($caracteres != ''default'') and (($caracteres != ''utf-8'')) and ($caracteres != ''windows-1252'')){ echo utf8_encode(imap_utf8($obj->getBody($i))); } else{ echo (imap_utf8($obj->getBody($i))); } echo "</blockquote>"; echo "<b>Anexos ::</b><br>" ; //recuperando o anexo de cada mensagem e salvando na pasta anexos ou outro diretório qualquer. $str=$obj->GetAttach($i,"anexos/"); // verificando o array de anexos da mensagem no laço e listando cada um. $ar=explode(",",$str); foreach($ar as $key=>$value){ echo ($value=="")?"":"Arquivo :: ".$value."<br>"; } echo "<br><hr>"; echo "</div>"; } } if($naolidos == 0){ echo "Sem emails novos."; } //fechando a conexão $obj->close_mailbox(); ?> </body> </html>
O código pra enviar e-mail você pega com a sua hospedagem.
10/07/2016
Moisés
O processo pra você seria ler a caixa de entrada e encaminhar cada e-mail pra conta que quiser. Verifique se sua hospedagem fornece tarefas agendadas (Cron Job) pra automatizar a execução.
// receivemail.class.php
<?php error_reporting(0); class receiveMail { var $server=''''; var $username=''''; var $password=''''; var $marubox=''''; var $email=''''; function receiveMail($username,$password,$EmailAddress,$mailserver=''localhost'',$servertype=''pop'',$port=''110'',$ssl = false, $marcar_como_lida = false) //Constructure { if($marcar_como_lida){ $so_ler = ""; } else { $so_ler = "/readonly"; } if($servertype==''imap'') { if($port=='''') { $port=''143''; } $strConnect=''{''.$mailserver.'':''.$port. ''/novalidate-cert/imap''.$so_ler.($ssl ? "/ssl" : "").''}INBOX''; } else { $strConnect=''{''.$mailserver.'':''.$port. ''/novalidate-cert/pop3''.$so_ler.($ssl ? "/ssl" : "").''}INBOX''; } $this->server = $strConnect; $this->username = $username; $this->password = $password; $this->email = $EmailAddress; } function connect() //Connect To the Mail Box { $this->marubox = imap_open($this->server,$this->username,$this->password); if(!$this->marubox) { echo "Error: Problemas ao se conectar no servidor"; exit; } else { /* $check = imap_mailboxmsginfo($this->marubox); if ($check) { echo "Date: " . $check->Date . "<br />\n" ; echo "Driver: " . $check->Driver . "<br />\n" ; echo "Mailbox: " . $check->Mailbox . "<br />\n" ; echo "Messages: " . $check->Nmsgs . "<br />\n" ; echo "Recent: " . $check->Recent . "<br />\n" ; echo "Unread: " . $check->Unread . "<br />\n" ; echo "Deleted: " . $check->Deleted . "<br />\n" ; echo "Size: " . $check->Size . "<br />\n" ; } else { echo "imap_mailboxmsginfo() failed: " . imap_last_error() . "<br />\n"; } */ } } function getHeaders($mid) // Capturar os cabeçalhos da mensagem { if(!$this->marubox) return false; $mail_header=imap_header($this->marubox,$mid); $sender=$mail_header->from[0]; $sender_replyto=$mail_header->reply_to[0]; if(strtolower($sender->mailbox)!=''mailer-daemon'' && strtolower($sender->mailbox)!=''postmaster'') { $mail_details=array( ''from''=>strtolower($sender->mailbox).''@''.$sender->host, ''fromName''=>$sender->personal, ''toOth''=>strtolower($sender_replyto->mailbox).''@''.$sender_replyto->host, ''toNameOth''=>$sender_replyto->personal, ''subject''=>$mail_header->subject, ''to''=>strtolower($mail_header->toaddress), ''date''=>strtolower($mail_header->date) ); } return $mail_details; } function get_mime_type(&$structure) //Capturando o mime type dos arquivos { $primary_mime_type = array("TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER"); if($structure->subtype) { return $primary_mime_type[(int) $structure->type] . ''/'' . $structure->subtype; } return "TEXT/PLAIN"; } function get_part($stream, $msg_number, $mime_type, $structure = false, $part_number = false) //Capturando as partes internas das mensagens { if(!$structure) { $structure = imap_fetchstructure($stream, $msg_number); } if($structure) { if($mime_type == $this->get_mime_type($structure)) { if(!$part_number) { $part_number = "1"; } $text = imap_fetchbody($stream, $msg_number, $part_number); if($structure->encoding == 3) { return imap_base64($text); } else if($structure->encoding == 4) { return imap_qprint($text); } else { return $text; } } if($structure->type == 1) /* multipart */ { while(list($index, $sub_structure) = each($structure->parts)) { $prefix = ""; if($part_number) { $prefix = $part_number . ''.''; } $data = $this->get_part($stream, $msg_number, $mime_type, $sub_structure, $prefix . ($index + 1)); if($data) { return $data; } } } } return false; } function getTotalMails() //Obtendo o total de emails da caixa de entrada { if(!$this->marubox) return false; $headers=imap_headers($this->marubox); return count($headers); } function GetAttach($mid,$path) // Obtendo os arquivos anexos. { if(!$this->marubox) return false; $struckture = imap_fetchstructure($this->marubox,$mid); $ar=""; if($struckture->parts) { foreach($struckture->parts as $key => $value) { $enc=$struckture->parts[$key]->encoding; if($struckture->parts[$key]->ifdparameters) { $name=$struckture->parts[$key]->dparameters[0]->value; $message = imap_fetchbody($this->marubox,$mid,$key+1); if ($enc == 0) $message = imap_8bit($message); if ($enc == 1) $message = imap_8bit ($message); if ($enc == 2) $message = imap_binary ($message); if ($enc == 3) $message = imap_base64 ($message); if ($enc == 4) $message = quoted_printable_decode($message); if ($enc == 5) $message = $message; $fp=fopen($path.$name,"w"); fwrite($fp,$message); fclose($fp); $ar=$ar.$name.","; } if($struckture->parts[$key]->parts) { foreach($struckture->parts[$key]->parts as $keyb => $valueb) { $enc=$struckture->parts[$key]->parts[$keyb]->encoding; if($struckture->parts[$key]->parts[$keyb]->ifdparameters) { $name=$struckture->parts[$key]->parts[$keyb]->dparameters[0]->value; $partnro = ($key+1).".".($keyb+1); $message = imap_fetchbody($this->marubox,$mid,$partnro); if ($enc == 0) $message = imap_8bit($message); if ($enc == 1) $message = imap_8bit ($message); if ($enc == 2) $message = imap_binary ($message); if ($enc == 3) $message = imap_base64 ($message); if ($enc == 4) $message = quoted_printable_decode($message); if ($enc == 5) $message = $message; $fp=fopen($path.$name,"w"); fwrite($fp,$message); fclose($fp); $ar=$ar.$name.","; } } } } } $ar=substr($ar,0,(strlen($ar)-1)); return $ar; } function getBody($mid) // Capturando o corpo da mensagem { if(!$this->marubox) return false; $body = $this->get_part($this->marubox, $mid, "TEXT/HTML"); if ($body == "") $body = $this->get_part($this->marubox, $mid, "TEXT/PLAIN"); if ($body == "") { return ""; } return $body; } function deleteMails($mid) // Deletando um email { if(!$this->marubox) return false; imap_delete($this->marubox,$mid); } function close_mailbox() //Fechando a conexão com o servidor { if(!$this->marubox) return false; imap_close($this->marubox, CL_EXPUNGE); } } ?>
// exibe_emails.php
<html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> </head> <body> <?php include_once("receivemail.class.php"); //criando o objeto com os parametros solicitados pelo método da classe receiveMail $obj = new receiveMail('''','''','''','''',''imap'','''', true, false); //fazendo a conexão $obj->connect(); //recuperando com um laço as mensagens e seus anexos. $headers = imap_headers($obj->marubox); $naolidos = 0; for($i=sizeof($headers); $i>0; $i--){ $flags = substr($headers[$i-1], 0, 4); $isunr = true;//(strpos($flags, "U") != false); if ($isunr){ $naolidos++; echo "<div style=''background-color:#E6E6E6;margin:50px;padding:50px;''>"; $head=$obj->getHeaders($i); $elements = imap_mime_header_decode($head[''subject'']); $assunto = ""; $caracteres = strtolower(imap_utf8($elements[0]->charset)); foreach($elements as $ele){ if(($caracteres != ''default'') and (($caracteres != ''utf-8'')) and ($caracteres != ''windows-1252'')) $assunto .= utf8_encode(imap_utf8($ele->text)) . " "; else $assunto .= (imap_utf8($ele->text)) . " "; } echo "<b>Assunto :: </b>" . $assunto; echo "<br>"; echo "<b>Destinos ::</b> ".$head[''to'']."<br>"; echo "<b>Origem ::</b> ".$head[''from'']."<br>"; echo "<b>Data ::</b> ".$head[''date'']."<br>"; echo "<b>Caracteres ::</b> ".$elements[0]->charset."<br>"; echo "<b>Mensagem ::</b><br>"; //obtendo o corpo de cada mnensagem echo "<blockquote>"; if(($caracteres != ''default'') and (($caracteres != ''utf-8'')) and ($caracteres != ''windows-1252'')){ echo utf8_encode(imap_utf8($obj->getBody($i))); } else{ echo (imap_utf8($obj->getBody($i))); } echo "</blockquote>"; echo "<b>Anexos ::</b><br>" ; //recuperando o anexo de cada mensagem e salvando na pasta anexos ou outro diretório qualquer. $str=$obj->GetAttach($i,"anexos/"); // verificando o array de anexos da mensagem no laço e listando cada um. $ar=explode(",",$str); foreach($ar as $key=>$value){ echo ($value=="")?"":"Arquivo :: ".$value."<br>"; } echo "<br><hr>"; echo "</div>"; } } if($naolidos == 0){ echo "Sem emails novos."; } //fechando a conexão $obj->close_mailbox(); ?> </body> </html>
O código pra enviar e-mail você pega com a sua hospedagem.
Rylan, muito obrigado.
Só esqueci de dizer sou bem leigo com php, estou tentando inseri as minha configurações seu arquivo tipo: $server=''mx.dominio.com.br'', var $username=''meu_email@dominio.com.br'', var $password=''minha_senha'', var $email='meu_email@dominio.com.br'', tem uma variável que não sei o que vai nela é var $marubox ="", vc poderia me ajudar?
tentei configurar sem inserir a informação da variável $marubox mas deu erro erro de conexão com o servidor.
10/07/2016
Raylan Zibel
Clique aqui para fazer login e interagir na Comunidade :)