How To Send Mails Using SMTP Server in PHP Como enviar e-mails usando o servidor SMTP em PHP
In PHP on Microsoft Windows you have to simply configure two parameters to enable sending mails through SMTP server. Em PHP em Microsoft Windows que você tem que simplesmente configurar dois parâmetros a fim de permitir enviar mails através do servidor SMTP. In Unix / Linux it is slightly more complicated. Em Unix / Linux é um pouco mais complicada. The solution, however, is much more powerful and works also on Windows. A solução, porém, é muito mais poderosa e também funciona no Windows. Let’s first start with Windows. Vamos começar com o primeiro Windows.
In Microsoft Windows PHP installation you just have to change two variables in php.ini: No Microsoft Windows PHP instalação você só tem que mudar no php.ini duas variáveis:
SMTP = smtp.server.com SMTP = smtp.server.com
smtp_port = 25 smtp_port = 25
Replace smtp.server.com with your SMTP server name and 25 with your SMTP server port (normally 25). Substituir smtp.server.com com o servidor SMTP 25, com o seu nome e porta do servidor SMTP (normalmente 25).
You can also set the default sender information in Windows: Você também pode definir o padrão remetente informações no Windows:
sendmail_from = me@example.com sendmail_from = me@example.com
On Linux / Unix PHP relies on sendmail . Em Linux / Unix PHP assenta na sendmail. You can specify the sendmail path here: Você pode especificar o caminho sendmail aqui:
sendmail_path = /usr/sbin/sendmail -t -i sendmail_path = / usr / sbin / sendmail-t-i
Unfortunately this doesn’t work too well if your SMTP server is configured on a different machine or you are not using sendmail. Infelizmente isso não funcionar muito bem se o seu servidor SMTP é configurado em uma outra máquina ou você não está usando o sendmail.
Fortunately there is a much better solution in Felizmente há uma solução muito melhor em PHPMailer . The default mail capability provided by mail() function in PHP is very limited. O padrão capacidade mail fornecido pelo correio (), em função do PHP é muito limitada. PHPMailer is a full fledged mail API which can be used to do any kind of mailing tasks. PHPMailer é uma verdadeira mail API, que pode ser usado para fazer qualquer tipo de mailing tarefas.
Features of PHPMailer Características do PHPMailer
- Can send emails with multiple TOs, CCs, BCCs and REPLY-TOs Pode enviar e-mails com múltiplos OT, MCs, BCCs e responder-OT
- Redundant SMTP servers Redundante servidores SMTP
- Multipart/alternative emails for mail clients that do not read HTML email Multipart / alternative mail e-mails para clientes que não ler e-mails HTML
- Support for 8bit, base64, binary, and quoted-printable encoding Suporte para 8bit, base64, binário, e citou-printable encoding
- Uses the same methods as the very popular AspEmail active server (COM) component Utiliza os mesmos métodos como o muito popular servidor AspEmail activa (COM) componente
- SMTP authentication Autenticação SMTP
- Word wrap Palavra embrulhar
- Address reset functions Endereço redefinir funções
- HTML email HTML e-mail
- Tested on multiple SMTP servers: Sendmail, qmail, Postfix, Imail, Exchange, etc Testado em múltiplos servidores SMTP: Sendmail, qmail, Postfix, Imail, Exchange, etc
- Works on any platform Funciona em qualquer plataforma
- Flexible debugging Flexível depuração
- Custom mail headers Custom mail cabeçalhos
- Multiple fs, string, and binary attachments (those from database, string, etc) Múltiplas fs, corda, e os acessórios binários (aqueles a partir de banco de dados, string, etc)
- Embedded image support Embutidos imagem apoio
How to use PHPMailer Como usar PHPMailer
To use PHPMailer you need to first Para utilizar PHPMailer você precisa primeiro download the files download dos arquivos and save the relevant files (upload) on your server. e salvar os arquivos (upload) em seu servidor.
You need to upload class.phpmailer.php , class.smtp.php (for SMTP support) and language/phpmailer.lang-en.php . Você precisa fazer o upload class.phpmailer.php, class.smtp.php (SMTP para suporte) e de idioma / phpmailer.lang-en.php. You should download the lang file corresponding to the language of your blog. Você deve fazer o download do arquivo lang correspondente ao idioma do seu blog. For my english language sites I use language/phpmailer.lang- en .php , where en is the language code. Para o meu idioma Inglês sites eu uso language/phpmailer.lang- en. Php, onde é a língua en código.
In your PHP file include class.phpmailer.php as follows: Em seu arquivo PHP class.phpmailer.php incluem o seguinte:
if(!class_exists('PHPMailer')) { require(BASEPATH . '/class.phpmailer.php'); } if (! class_exists ( 'PHPMailer')) (exigir (BASEPATH '. / class.phpmailer.php');) Replace BASEPATH with the actual path of class-phpmailer.php file. Substituir BASEPATH com o próprio caminho de classe-phpmailer.php arquivo. You may also define BASEPATH to achieve the same result (preferred). Você também pode definir BASEPATH para atingir o mesmo resultado (de preferência).
Note: This check ensures only one copy of the class is loaded. Nota: Este controlo assegura apenas uma cópia da classe é carregada. This in turn loads other required classes. Este, por sua vez, carrega outros exigidos classes.
Now you can send a mail using any SMTP server. Agora você pode enviar um email usando qualquer servidor SMTP. Here is a simple example: Aqui está um exemplo simples:
$mail = new PHPMailer(); $mail->From = $senderemail; $mail->FromName = $sendername; $mail->AddAddress($receiveremail, $receivername); // Fill in Username and Password for servers requiring authentication $mail->Username = $smtp_username; $mail->Password = $smtp_password; // SMTP server name $mail->Host = $smtp_server; $mail->Mailer = "smtp"; $mail->Subject = $mail_subject; $mail->Body = $mail_body; if(!$mail->Send()) $results = 'Error message'; else $results = 'Success message'; $ mail = new PHPMailer (); $ mail-> De = $ senderemail; $ mail-> FromName = $ sendername; $ mail-> AddAddress (US $ receiveremail, US $ receivername) / / Preencha o nome de usuário e senha para servidores que exigem autenticação $ mail-> Username = $ smtp_username; $ mail-> Password = $ smtp_password; / / nome do servidor SMTP $ mail-> Host = $ smtp_server; $ mail-> Mailer = "smtp"; $ mail-> Subject = $ mail_subject ; $ Mail-> Body = $ mail_body; if (! US $ mail-> Envia ()) $ resultados = 'Mensagem de erro'; resto $ resultados = 'Sucesso mensagem'; You can read the Você pode ler o documentation Documentação , De advanced example avançadas exemplo or the ou o tutorial if you need further help. se precisar de mais ajuda.
Filed under Arquivado em Headline News Headline News , De How To How To , De Open Source Software Open Source Software , De PHP , De Tech Note Nota Tech , De Web , De Web Services Web Services | |
| |
RSS 2.0 RSS 2,0 | |
Trackback this Article | este artigo |
Email this Article E-mail este artigo
You may also like to read Você pode também gosta de ler |





October 9th, 2006 at 1:21 pm Oct 9, 2006, às 1:21 pm
Just a mistake : Basta um erro:
replace : substituir:
require(BASEPATH . ‘/class-phpmailer.php’); exigir (BASEPATH '. / aula-phpmailer.php');
by : por:
require(BASEPATH . ‘/class.phpmailer.php’); exigir (BASEPATH '. / class.phpmailer.php');
October 9th, 2006 at 7:40 pm Oct 9, 2006, às 7:40 pm
Though your comment didn’t come out correctly, I am guessing you were referring to normal single quotes. Embora o seu comentário não sai bem, estou a adivinhar que você estava referindo-se ao normal aspas simples. This problem is caused by WordPress. Este problema é causado por WordPress. I have corrected this post to Tenho corrigida para este post remove fancy quotes remover fantasia aspas .
Here’s how you can Veja como você pode remove fancy quotes remover fantasia aspas from your WordPress blogs or comments. a partir do seu WordPress blogs ou comentários.
November 7th, 2006 at 2:49 am 7 de novembro, 2006 em 2:49 am
He was actually referring to the fact that the file is named class.phpmailer.php and not class-phpmailer.php as in the original article. Ele era realmente referindo-se ao fato de que o ficheiro tem o nome class.phpmailer.php e não-classe phpmailer.php como no artigo original.
November 7th, 2006 at 6:41 am 7 de novembro, 2006 em 6:41 am
Ah, thanks. Ah, obrigado. Corrected the typo. Corrigido o erro tipográfico.
January 29th, 2007 at 3:00 am 29 de janeiro de 2007 em 3:00 am
It’s good. É bom.
February 4th, 2007 at 11:09 pm 4 de fevereiro de 2007 em 11:09 pm
hi… oi…
im very new to this field…i want something to be done like,if i submit a form ,i should get a mail to im muito nova para esse campo… eu quero algo a ser feito como, se eu apresentar um formulário, gostaria de obter um e-mail para intelevents@kestone.in ….to do tjhis i have followed thw following steps…. …. Tjhis eu tenho que fazer thw seguintes passos seguidos….
1..i have uploaded my php file and html file on to server through winSCP… 1 .. i ter carregado o meu arquivo PHP e arquivo html com o servidor através winSCP…
2.in browser i opend the file by giving the url kestone.in/reg1.htm.. 2.in navegador i opend o arquivo, dando a url kestone.in/reg1.htm ..
but im not getting the mail… im, mas não recebe o correio…
here is my php file aqui é o meu arquivo PHP
Registration Confirmed Registro Confirmado
Registration Page Registro Page
Registration Inscrição
Salutation: Saudações:
‘.$salutation.’ '. $ Saudação'.
FName: Fname:
‘.$fname.’ '. $ Fname'.
Lname : Lname:
‘.$lname.’ '. $ Lname'.
Email-id: Email-ID:
‘. '. $mail.’ $ mail '.
Company: Empresa:
‘. '. $company.’ $ companhia. "
Designation: Designação:
‘. '. $designation.’ $ designação '.
Address1: Endereço1:
‘. '. $Add1.’ ADD1 $ '.
Address2: Endereço2:
‘. '. $Add2.’ $ ADD 2 '.
Address3:
‘. '. $Add3.’ $ Add3 '.
City: Cidade:
‘. '. $City.’ $ Cidade '.
State: Estado:
‘. '. $state.’ $ estado '.
Pincode: Código pin:
‘. '. $pincode.’ $ código pin ".
Phone: Telefone:
‘. '. $phone.’ $ telefone '.
Fax:
‘. '. $fax.’ $ fax. "
Mobile: Celular:
‘. '. $Mobile.’ $ Mobile. "
‘;/* To send HTML mail, you can set the Content-type header. '; / * Para enviar email HTML, você pode definir o cabeçalho do tipo de conteúdo. */ * /
$headers = “MIME-Version: 1.0\r\n”; $ headers = "MIME-Version: 1,0 \ r \ n";
$headers .= “Content-type: text/html; charset=iso-8859-1\r\n”; $ headers .= "Content-type: text / html; charset = ISO-8859-1 \ r \ n";
/* additional headers */ / * Headers adicionais * /
$headers .= “From: “.$mail; $ headers .= "From:". $ mail;
/* and now mail it */ / * E-mail agora * /
mail($to, $subject, $message, $headers); mail ($ para, $ assunto, $ mensagem, $ headers);
echo ”; echo ";
?>
and html e HTML
Salutation Saudações
table td.title{ (tabela td.title
text-align:center;font-family:arial;font-weight:normal;font-size:12px} text-align: center; font-family: arial; font-weight: normal; font-size: 12px)
function validation() função validação ()
{ (
valid = true; válidos = true;
objform=document.forms["regform"]; objform = document.forms [ "regform"];
if(objform.Fname.value ==”") if (objform.Fname.value =="")
{ (
alert(”Please enter the ‘First Name’”); Alerta ( "Digite o" Nome ");
objform.Fname.focus(); objform.Fname.focus ();
valid=false; válidos = false;
} )
else diferente
if(objform.email.value==”") if (objform.email.value =="")
{ (
alert(”Please enter the Email address”); Alerta ( "digite o endereço de email");
objform.email.focus(); objform.email.focus ();
valid=false; válidos = false;
} )
else diferente
if(objform.company.value==”") if (objform.company.value =="")
{ (
alert(”Please enter the ‘Company’”); Alerta ( "Por favor introduza a 'Companhia'");
objform.company.focus(); objform.company.focus ();
valid=false; válidos = false;
} )
else diferente
if(objform.designation.value==”") if (objform.designation.value =="")
{ (
alert(”Please enter the designation”); Alerta ( "Por favor, introduza a designação");
objform.designation.focus(); objform.designation.focus ();
valid=false; válidos = false;
} )
else diferente
if(objform.add1.value==”") if (objform.add1.value =="")
{ (
alert(”Please fill the ‘Address’”); Alerta ( "Por favor, preencha o 'Endereço'");
objform.add1.focus(); objform.add1.focus ();
valid=false; válidos = false;
} )
else diferente
if(objform.city.value==”") if (objform.city.value =="")
{ (
alert(”Please enter the ‘City’”); Alerta ( "Por favor introduza a 'City'");
objform.city.focus(); objform.city.focus ();
valid=false; válidos = false;
} )
else diferente
if(objform.pin.value==”") if (objform.pin.value =="")
{ (
alert(”Please enter the ‘Pin’”); Alerta ( "Por favor introduza o" Pin "");
objform.pin.focus(); objform.pin.focus ();
valid=false; válidos = false;
} )
else diferente
if(objform.mobile.value==”") if (objform.mobile.value =="")
{ (
alert(”Please enter the ‘mobile number’”); Alerta ( "Por favor, introduza o 'número do celular'");
objform.mobile.focus(); objform.mobile.focus ();
valid=false; válidos = false;
} )
return valid; retorno válidos;
} )
Registration Form Registration Form
Salutation: Saudações:
Dr
Mr Senhor
Mrs Deputada
Ms
Miss Perder
*First Name: * Nome:
Last Name: Último Nome:
*Email : * Email:
*Company : * Empresa:
*Designation: * Designação:
*Address1: * Endereço1:
Address2: Endereço2:
Address3 : Address3:
*City: * Cidade:
State: Estado:
*Pin : * Pin:
Phone: Telefone:
Fax:
*Mobile: * Celular:
can anybody help in this issue….its very very very urgent…ill be very thanful to u… Alguém pode ajudar nesta questão…. seu muito muito muito urgente… ser muito doente para thanful u…
February 4th, 2007 at 11:11 pm 4 de fevereiro de 2007 em 11:11 pm
Registration Confirmed Registro Confirmado
Registration Page Registro Page
Registration Inscrição
Salutation: Saudações:
‘.$salutation.’ '. $ Saudação'.
FName: Fname:
‘.$fname.’ '. $ Fname'.
Lname : Lname:
‘.$lname.’ '. $ Lname'.
Email-id: Email-ID:
‘. '. $mail.’ $ mail '.
Company: Empresa:
‘. '. $company.’ $ companhia. "
Designation: Designação:
‘. '. $designation.’ $ designação '.
Address1: Endereço1:
‘. '. $Add1.’ ADD1 $ '.
Address2: Endereço2:
‘. '. $Add2.’ $ ADD 2 '.
Address3:
‘. '. $Add3.’ $ Add3 '.
City: Cidade:
‘. '. $City.’ $ Cidade '.
State: Estado:
‘. '. $state.’ $ estado '.
Pincode: Código pin:
‘. '. $pincode.’ $ código pin ".
Phone: Telefone:
‘. '. $phone.’ $ telefone '.
Fax:
‘. '. $fax.’ $ fax. "
Mobile: Celular:
‘. '. $Mobile.’ $ Mobile. "
‘;/* To send HTML mail, you can set the Content-type header. '; / * Para enviar email HTML, você pode definir o cabeçalho do tipo de conteúdo. */ * /
$headers = “MIME-Version: 1.0\r\n”; $ headers = "MIME-Version: 1,0 \ r \ n";
$headers .= “Content-type: text/html; charset=iso-8859-1\r\n”; $ headers .= "Content-type: text / html; charset = ISO-8859-1 \ r \ n";
/* additional headers */ / * Headers adicionais * /
$headers .= “From: “.$mail; $ headers .= "From:". $ mail;
/* and now mail it */ / * E-mail agora * /
mail($to, $subject, $message, $headers); mail ($ para, $ assunto, $ mensagem, $ headers);
echo ”; echo ";
?>
August 1st, 2007 at 11:29 am 1 de agosto de 2007 em 11:29
Realy nice, but is this same for sending email using arabic languages, mean if format is arabic. Realmente agradável, mas é isso mesmo para o envio de e-mail usando árabe, quer dizer, se formato é árabe.