SlideShare ist ein Scribd-Unternehmen logo
1 von 21
Downloaden Sie, um offline zu lesen
Enviando e-mail que chega ao
    destino usando PHP
                                 Manuel Lemos
                          mlemos@acm.org
                   http://www.ManuelLemos.net/
               CoLAPHP – LatinoWare 2008
             http://www.latinoware.org/
   Foz de Iguaçu, 30 de outubro a 1 de novembro de 2008
       COLAPHP - Congresso Latino-Americano de PHP
            PHPBC – PHP Brasil Comunidades
               http://www.php.org.br/
                                        CoLAPHP - LatinoWare 2008
PHPBC – PHP Brasil Comunidades
                                        Congresso Latino-Americano de PHP
http://www.php.org.br/
Os problemas
    Enviar e-mail é fundamental
●



    Suporte nativo de envio de e-mail em PHP é
●

    deficiente
    Os padrões da Internet para composição e
●

    envio de e-mail são complicados
    Mensagens mal compostas são descartadas
●



    Mensagens bem compostas são confundidas
●

    com SPAM
                                 CoLAPHP - LatinoWare 2008
PHPBC – PHP Brasil Comunidades
                                 Congresso Latino-Americano de PHP
http://www.php.org.br/
A solução
 Componentes prontos em PHP para envio de e-
                    mail
    PHPMailer
●



    PEAR Mail
●



    SWIFT mailer
●



    MIME message
●



    Etc.
●



                                   CoLAPHP - LatinoWare 2008
PHPBC – PHP Brasil Comunidades
                                   Congresso Latino-Americano de PHP
http://www.php.org.br/
O que é MIME?
    Multipurpose Internet Mail Extensions
●




    Padrões para envio de mensagens de E-mail
●




    Definidos através de muitos documentos
●

    RFC: Request For Comments

    Novas versões dos documentos RFC
●

    compatíveis com versões passadas

                                 CoLAPHP - LatinoWare 2008
PHPBC – PHP Brasil Comunidades
                                 Congresso Latino-Americano de PHP
http://www.php.org.br/
Classe MIME message
    Classe em PHP para compôr e enviar e-mail
    Envia mensagens de texto e HTML com texto
●

    em qualquer alfabeto
    Embute arquivos relacionados: imagens, CSS,
●

    etc..
    Pode anexar múltiplos arquivos
●



    Otimizações para envio de newletters para
●

    muitos destinatários
                                 CoLAPHP - LatinoWare 2008
PHPBC – PHP Brasil Comunidades
                                 Congresso Latino-Americano de PHP
http://www.php.org.br/
Mensagem de texto
require('email_message.php');
$m = new email_message_class;
$m->SetEncodedHeader('Subject', 'Isto é o assunto');
$m->SetEmailEncodedHeader('From', 'jose@aqui.com.br',
  'João');
$m->SetEmailEncodedHeader('To', 'jose@ali.com.br', 'José');
$texto = “Olá José,nnEsta é a mensagem.”;
$m->AddQuotedPrintableTextPart($texto);
$m->Send();

                                 CoLAPHP - LatinoWare 2008
PHPBC – PHP Brasil Comunidades
                                 Congresso Latino-Americano de PHP
http://www.php.org.br/
Mensagem de HTML
$html =
  “<html><head><title>Mensagem</title></head><body>Olá
  José,<br />n<br />nEsta é a mensagem.</body></html>”;
$texto = strip_tags($html);
$m->CreateQuotedPrintableHTMLPart($html, '', $h);
$m->CreateQuotedPrintableTextPart($texto, '', $t);
$alternativas = array($t, $h);
$m->AddAlternativeMultipart($alternativas);
$m->Send()

                                 CoLAPHP - LatinoWare 2008
PHPBC – PHP Brasil Comunidades
                                 Congresso Latino-Americano de PHP
http://www.php.org.br/
Mensagem HTML com
             imagens embutidas
$imagem=array(                       $m->CreateQuotedPrintableHTMLPart
                                    ($html, '', $h);
 'FileName'=>'imagem.gif',
 'Content-Type' =>                  $texto = strip_tags($html);
   'automatic/name',
                                     $m->CreateQuotedPrintableTextPart
 'Disposition'=>'inline'            ($texto, '', $t);
);
                                    $alternativas = array($t, $h);
$e->CreateFilePart($imagem, $i);     $m->AddAlternativeMultipart
                                    ($alternativas);
$url = 'cid:'.                       $relacionadas = array(
                                      $alternativas,
$m->GetPartContentID($i);
                                      $i,
 $html = quot;<html>                     );
<head><title>Mensagem</title>
                                     $m->AddRelatedMultipart
</head><body><img src=”$url” />
                                    ($relacionadas);
Olá José,<br />n<br />nEsta é a
mensagem.</body></html>quot;;           $m->Send()

                                        CoLAPHP - LatinoWare 2008
PHPBC – PHP Brasil Comunidades
                                        Congresso Latino-Americano de PHP
http://www.php.org.br/
Mensagem com arquivos
              anexados
 $anexo=array(
  'Data'=>'Isto é um arquivo chamado anexo.txt',
  'Name'=>'anexo.txt',
  'Content-Type'=>'automatic/name',
  'Disposition'=>'attachment',
 );
 $m->AddFilePart($anexo);
 $anexo=array(
  'FileName'=>'anexo.zip',
  'Content-Type'=>'automatic/name',
  'Disposition'=>'attachment',
 );
 $m->AddFilePart($anexo);
 $m->Send();
                                  CoLAPHP - LatinoWare 2008
PHPBC – PHP Brasil Comunidades
                                  Congresso Latino-Americano de PHP
http://www.php.org.br/
Enviando por SMTP
 Suporta vários tipos de autenticação usando as
     classes SASL: LOGIN, MD5, NTLM, etc.
require('sasl.php'); require('smtp.php');
require('smtp_message.php');
$m = new smtp_message_class;
$m->smtp_host = 'smtp.gmail.com';
$m->smtp_port = 465;
$m->smtp_ssl = 1;
$m->smtp_user = 'usuario';
$m->smtp_password = 'senha';
$m->direct_delivery = 0;
                                     CoLAPHP - LatinoWare 2008
PHPBC – PHP Brasil Comunidades
                                     Congresso Latino-Americano de PHP
http://www.php.org.br/
Enviando via sendmail, qmail e
     Microsoft Exchange
   Envio mais rápido para fila de espera do MTA
require('sendmail_message.php');
$m = new sendmail_message_class;
$m->delivery_mode = SENDMAIL_DELIVERY_DEFERRED;

require('qmail_message.php');
$m = new qmail_message_class;

require('pickup_message.php');
$m = new pickup_message_class;



                                     CoLAPHP - LatinoWare 2008
PHPBC – PHP Brasil Comunidades
                                     Congresso Latino-Americano de PHP
http://www.php.org.br/
Alternativas à função mail()
      Quando a função mail() não funciona bem

    smtp_mail()
●




    sendmail_mail()
●




    qmail_mail()
●




    urgent_mail()
●




                                 CoLAPHP - LatinoWare 2008
PHPBC – PHP Brasil Comunidades
                                 Congresso Latino-Americano de PHP
http://www.php.org.br/
O caminho das mensagens

       SMTP local                    Fila local            Fila de destino

SMTP                      Pickup

     Script de PHP                      MTA               SMTP de destino
                                 mail()
                                       Direct



                                            CoLAPHP - LatinoWare 2008
PHPBC – PHP Brasil Comunidades
                                            Congresso Latino-Americano de PHP
http://www.php.org.br/
Melhores métodos de envio

1.Largar arquivo de mensagem na fila local

2.Passar para MTA com função mail (sendmail)

3.Passar para servidor de SMTP local

4.Enviar para direto para SMTP de destino
                                 CoLAPHP - LatinoWare 2008
PHPBC – PHP Brasil Comunidades
                                 Congresso Latino-Americano de PHP
http://www.php.org.br/
Otimização de envio de
newsletters não personalizadas
$lista = array(
 'pedro@la.com.br'=>'Pedro',
 'paulo@ali.com.br'=>'Paulo',
 'maria@acola.com.br'=>'Maria'
);
$m->SetBulkMail(1);
$m->cache_body = 1;
foreach($lista as $email => $nome) {
 $m->SetEncodedEmailHeader('To', $email, $nome);
 $m->Send();
}
$m->SetBulkMail(0);
                                       CoLAPHP - LatinoWare 2008
PHPBC – PHP Brasil Comunidades
                                       Congresso Latino-Americano de PHP
http://www.php.org.br/
Otimização de envio de
      newsletters personalizadas
$m->SetBulkMail(1);
$m->cache_body = 0;
$template = 'Olá {nome}, ...';
$m->CreateQuotedPrintableTextPart($template, '', $parte_template);
$m->AddPart($parte_template);
foreach($lista as $email => $nome) {
  $m->SetEncodedEmailHeader('To', $email, $nome);
  $texto = str_replace('{nome}', $nome, $template);
  $m->CreateQuotedPrintableTextPart($texto, '', $personalizada);
  $m->ReplacePart($parte_template, $personalizada);
  $m->Send();
}
$m->SetBulkMail(0);
                                     CoLAPHP - LatinoWare 2008
PHPBC – PHP Brasil Comunidades
                                     Congresso Latino-Americano de PHP
http://www.php.org.br/
Lidando com devoluções
1.Definir o cabeçalho Return-Path com o
  endereço associado a uma caixa POP3
2.Vigiar regularmente esse endereço usando
  uma classe de cliente POP3
3.Processar as mensagens recebidas com a
  classe MIME parser
4.Descadastrar das newsletters os endereços
  de e-mail que estão devolvendo
                                 CoLAPHP - LatinoWare 2008
PHPBC – PHP Brasil Comunidades
                                 Congresso Latino-Americano de PHP
http://www.php.org.br/
Saber quando a mensagem foi
          recebida
          Técnicas que nem sempre funcionam

1.Definir o cabeçalho Disposition-
  Notification-To com um endereço para
  onde serão enviados avisos de leitura

2.Inserir imagem espiã em mensagem de HTML
  com URL de script que contabiliza leituras
<img src=”http://www.meusite.com.br/conta.php?usuario=joao@ali.com.br”>


                                        CoLAPHP - LatinoWare 2008
PHPBC – PHP Brasil Comunidades
                                        Congresso Latino-Americano de PHP
http://www.php.org.br/
Evitar confusão com SPAM
        Que mensagens não se deve enviar?
    Enviadas a partir de IP sem reverso no DNS
●

    ou que consta de listas negras de SPAM
    Destinatários só em cabeçalho Bcc
●


    Só com HTML ou com HTML inválido
●


    Com imagens espiãs com parâmetros no URL
●


    URLs dos links não conferem com os textos
●


    Não passam nos testes do SpamAssassin
●

                                 CoLAPHP - LatinoWare 2008
PHPBC – PHP Brasil Comunidades
                                 Congresso Latino-Americano de PHP
http://www.php.org.br/
Perguntas?


                         Manuel Lemos
                        mlemos@acm.org

                        PHPBC – PHP Brasil Comunidades
                            http://www.php.org.br/




                                          CoLAPHP - LatinoWare 2008
PHPBC – PHP Brasil Comunidades
                                          Congresso Latino-Americano de PHP
http://www.php.org.br/
Referências
                         Classe MIME Message
                   ●


                         http://www.phpclasses.org/mimemessage
                         Classe SMTP
                   ●


                         http://www.phpclasses.org/smtpclass
                         Classe SASL
                   ●


                         http://www.phpclasses.org/sasl
                         Classe POP3
                   ●


                         http://www.phpclasses.org/pop3class
                         Classe MIME parser
                   ●


                         http://www.phpclasses.org/mimeparser
                         Verificação de IP em múltiplas listas negras
                   ●


                         http://openrbl.org/
                   SpamAssassin
                   ●


                   http://spamassassin.apache.org/
                                        CoLAPHP - LatinoWare 2008
PHPBC – PHP Brasil Comunidades
                                                   Congresso Latino-Americano de PHP
http://www.php.org.br/

Weitere ähnliche Inhalte

Empfohlen

Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at WorkGetSmarter
 
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...DevGAMM Conference
 
Barbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationBarbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationErica Santiago
 
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them wellGood Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them wellSaba Software
 

Empfohlen (20)

Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 
ChatGPT webinar slides
ChatGPT webinar slidesChatGPT webinar slides
ChatGPT webinar slides
 
More than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike RoutesMore than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike Routes
 
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
 
Barbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationBarbie - Brand Strategy Presentation
Barbie - Brand Strategy Presentation
 
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them wellGood Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
 

Enviando E-Mail Que Chega Ao Destino usando PHP

  • 1. Enviando e-mail que chega ao destino usando PHP Manuel Lemos mlemos@acm.org http://www.ManuelLemos.net/ CoLAPHP – LatinoWare 2008 http://www.latinoware.org/ Foz de Iguaçu, 30 de outubro a 1 de novembro de 2008 COLAPHP - Congresso Latino-Americano de PHP PHPBC – PHP Brasil Comunidades http://www.php.org.br/ CoLAPHP - LatinoWare 2008 PHPBC – PHP Brasil Comunidades Congresso Latino-Americano de PHP http://www.php.org.br/
  • 2. Os problemas Enviar e-mail é fundamental ● Suporte nativo de envio de e-mail em PHP é ● deficiente Os padrões da Internet para composição e ● envio de e-mail são complicados Mensagens mal compostas são descartadas ● Mensagens bem compostas são confundidas ● com SPAM CoLAPHP - LatinoWare 2008 PHPBC – PHP Brasil Comunidades Congresso Latino-Americano de PHP http://www.php.org.br/
  • 3. A solução Componentes prontos em PHP para envio de e- mail PHPMailer ● PEAR Mail ● SWIFT mailer ● MIME message ● Etc. ● CoLAPHP - LatinoWare 2008 PHPBC – PHP Brasil Comunidades Congresso Latino-Americano de PHP http://www.php.org.br/
  • 4. O que é MIME? Multipurpose Internet Mail Extensions ● Padrões para envio de mensagens de E-mail ● Definidos através de muitos documentos ● RFC: Request For Comments Novas versões dos documentos RFC ● compatíveis com versões passadas CoLAPHP - LatinoWare 2008 PHPBC – PHP Brasil Comunidades Congresso Latino-Americano de PHP http://www.php.org.br/
  • 5. Classe MIME message Classe em PHP para compôr e enviar e-mail Envia mensagens de texto e HTML com texto ● em qualquer alfabeto Embute arquivos relacionados: imagens, CSS, ● etc.. Pode anexar múltiplos arquivos ● Otimizações para envio de newletters para ● muitos destinatários CoLAPHP - LatinoWare 2008 PHPBC – PHP Brasil Comunidades Congresso Latino-Americano de PHP http://www.php.org.br/
  • 6. Mensagem de texto require('email_message.php'); $m = new email_message_class; $m->SetEncodedHeader('Subject', 'Isto é o assunto'); $m->SetEmailEncodedHeader('From', 'jose@aqui.com.br', 'João'); $m->SetEmailEncodedHeader('To', 'jose@ali.com.br', 'José'); $texto = “Olá José,nnEsta é a mensagem.”; $m->AddQuotedPrintableTextPart($texto); $m->Send(); CoLAPHP - LatinoWare 2008 PHPBC – PHP Brasil Comunidades Congresso Latino-Americano de PHP http://www.php.org.br/
  • 7. Mensagem de HTML $html = “<html><head><title>Mensagem</title></head><body>Olá José,<br />n<br />nEsta é a mensagem.</body></html>”; $texto = strip_tags($html); $m->CreateQuotedPrintableHTMLPart($html, '', $h); $m->CreateQuotedPrintableTextPart($texto, '', $t); $alternativas = array($t, $h); $m->AddAlternativeMultipart($alternativas); $m->Send() CoLAPHP - LatinoWare 2008 PHPBC – PHP Brasil Comunidades Congresso Latino-Americano de PHP http://www.php.org.br/
  • 8. Mensagem HTML com imagens embutidas $imagem=array( $m->CreateQuotedPrintableHTMLPart ($html, '', $h); 'FileName'=>'imagem.gif', 'Content-Type' => $texto = strip_tags($html); 'automatic/name', $m->CreateQuotedPrintableTextPart 'Disposition'=>'inline' ($texto, '', $t); ); $alternativas = array($t, $h); $e->CreateFilePart($imagem, $i); $m->AddAlternativeMultipart ($alternativas); $url = 'cid:'. $relacionadas = array( $alternativas, $m->GetPartContentID($i); $i, $html = quot;<html> ); <head><title>Mensagem</title> $m->AddRelatedMultipart </head><body><img src=”$url” /> ($relacionadas); Olá José,<br />n<br />nEsta é a mensagem.</body></html>quot;; $m->Send() CoLAPHP - LatinoWare 2008 PHPBC – PHP Brasil Comunidades Congresso Latino-Americano de PHP http://www.php.org.br/
  • 9. Mensagem com arquivos anexados $anexo=array( 'Data'=>'Isto é um arquivo chamado anexo.txt', 'Name'=>'anexo.txt', 'Content-Type'=>'automatic/name', 'Disposition'=>'attachment', ); $m->AddFilePart($anexo); $anexo=array( 'FileName'=>'anexo.zip', 'Content-Type'=>'automatic/name', 'Disposition'=>'attachment', ); $m->AddFilePart($anexo); $m->Send(); CoLAPHP - LatinoWare 2008 PHPBC – PHP Brasil Comunidades Congresso Latino-Americano de PHP http://www.php.org.br/
  • 10. Enviando por SMTP Suporta vários tipos de autenticação usando as classes SASL: LOGIN, MD5, NTLM, etc. require('sasl.php'); require('smtp.php'); require('smtp_message.php'); $m = new smtp_message_class; $m->smtp_host = 'smtp.gmail.com'; $m->smtp_port = 465; $m->smtp_ssl = 1; $m->smtp_user = 'usuario'; $m->smtp_password = 'senha'; $m->direct_delivery = 0; CoLAPHP - LatinoWare 2008 PHPBC – PHP Brasil Comunidades Congresso Latino-Americano de PHP http://www.php.org.br/
  • 11. Enviando via sendmail, qmail e Microsoft Exchange Envio mais rápido para fila de espera do MTA require('sendmail_message.php'); $m = new sendmail_message_class; $m->delivery_mode = SENDMAIL_DELIVERY_DEFERRED; require('qmail_message.php'); $m = new qmail_message_class; require('pickup_message.php'); $m = new pickup_message_class; CoLAPHP - LatinoWare 2008 PHPBC – PHP Brasil Comunidades Congresso Latino-Americano de PHP http://www.php.org.br/
  • 12. Alternativas à função mail() Quando a função mail() não funciona bem smtp_mail() ● sendmail_mail() ● qmail_mail() ● urgent_mail() ● CoLAPHP - LatinoWare 2008 PHPBC – PHP Brasil Comunidades Congresso Latino-Americano de PHP http://www.php.org.br/
  • 13. O caminho das mensagens SMTP local Fila local Fila de destino SMTP Pickup Script de PHP MTA SMTP de destino mail() Direct CoLAPHP - LatinoWare 2008 PHPBC – PHP Brasil Comunidades Congresso Latino-Americano de PHP http://www.php.org.br/
  • 14. Melhores métodos de envio 1.Largar arquivo de mensagem na fila local 2.Passar para MTA com função mail (sendmail) 3.Passar para servidor de SMTP local 4.Enviar para direto para SMTP de destino CoLAPHP - LatinoWare 2008 PHPBC – PHP Brasil Comunidades Congresso Latino-Americano de PHP http://www.php.org.br/
  • 15. Otimização de envio de newsletters não personalizadas $lista = array( 'pedro@la.com.br'=>'Pedro', 'paulo@ali.com.br'=>'Paulo', 'maria@acola.com.br'=>'Maria' ); $m->SetBulkMail(1); $m->cache_body = 1; foreach($lista as $email => $nome) { $m->SetEncodedEmailHeader('To', $email, $nome); $m->Send(); } $m->SetBulkMail(0); CoLAPHP - LatinoWare 2008 PHPBC – PHP Brasil Comunidades Congresso Latino-Americano de PHP http://www.php.org.br/
  • 16. Otimização de envio de newsletters personalizadas $m->SetBulkMail(1); $m->cache_body = 0; $template = 'Olá {nome}, ...'; $m->CreateQuotedPrintableTextPart($template, '', $parte_template); $m->AddPart($parte_template); foreach($lista as $email => $nome) { $m->SetEncodedEmailHeader('To', $email, $nome); $texto = str_replace('{nome}', $nome, $template); $m->CreateQuotedPrintableTextPart($texto, '', $personalizada); $m->ReplacePart($parte_template, $personalizada); $m->Send(); } $m->SetBulkMail(0); CoLAPHP - LatinoWare 2008 PHPBC – PHP Brasil Comunidades Congresso Latino-Americano de PHP http://www.php.org.br/
  • 17. Lidando com devoluções 1.Definir o cabeçalho Return-Path com o endereço associado a uma caixa POP3 2.Vigiar regularmente esse endereço usando uma classe de cliente POP3 3.Processar as mensagens recebidas com a classe MIME parser 4.Descadastrar das newsletters os endereços de e-mail que estão devolvendo CoLAPHP - LatinoWare 2008 PHPBC – PHP Brasil Comunidades Congresso Latino-Americano de PHP http://www.php.org.br/
  • 18. Saber quando a mensagem foi recebida Técnicas que nem sempre funcionam 1.Definir o cabeçalho Disposition- Notification-To com um endereço para onde serão enviados avisos de leitura 2.Inserir imagem espiã em mensagem de HTML com URL de script que contabiliza leituras <img src=”http://www.meusite.com.br/conta.php?usuario=joao@ali.com.br”> CoLAPHP - LatinoWare 2008 PHPBC – PHP Brasil Comunidades Congresso Latino-Americano de PHP http://www.php.org.br/
  • 19. Evitar confusão com SPAM Que mensagens não se deve enviar? Enviadas a partir de IP sem reverso no DNS ● ou que consta de listas negras de SPAM Destinatários só em cabeçalho Bcc ● Só com HTML ou com HTML inválido ● Com imagens espiãs com parâmetros no URL ● URLs dos links não conferem com os textos ● Não passam nos testes do SpamAssassin ● CoLAPHP - LatinoWare 2008 PHPBC – PHP Brasil Comunidades Congresso Latino-Americano de PHP http://www.php.org.br/
  • 20. Perguntas? Manuel Lemos mlemos@acm.org PHPBC – PHP Brasil Comunidades http://www.php.org.br/ CoLAPHP - LatinoWare 2008 PHPBC – PHP Brasil Comunidades Congresso Latino-Americano de PHP http://www.php.org.br/
  • 21. Referências Classe MIME Message ● http://www.phpclasses.org/mimemessage Classe SMTP ● http://www.phpclasses.org/smtpclass Classe SASL ● http://www.phpclasses.org/sasl Classe POP3 ● http://www.phpclasses.org/pop3class Classe MIME parser ● http://www.phpclasses.org/mimeparser Verificação de IP em múltiplas listas negras ● http://openrbl.org/ SpamAssassin ● http://spamassassin.apache.org/ CoLAPHP - LatinoWare 2008 PHPBC – PHP Brasil Comunidades Congresso Latino-Americano de PHP http://www.php.org.br/