para formulario enviar ejemplo correos correo configurar con codigo php email wamp wampserver
GitHub

formulario - ¿Cómo enviar un correo electrónico usando PHP?



enviar correos con php y mysql (13)

Ejemplo de código completo ...

Inténtalo una vez ..

<?php // Multiple recipients $to = ''[email protected], [email protected]''; // note the comma // Subject $subject = ''Birthday Reminders for August''; // Message $message = '' <html> <head> <title>Birthday Reminders for August</title> </head> <body> <p>Here are the birthdays upcoming in August!</p> <table> <tr> <th>Person</th><th>Day</th><th>Month</th><th>Year</th> </tr> <tr> <td>Johny</td><td>10th</td><td>August</td><td>1970</td> </tr> <tr> <td>Sally</td><td>17th</td><td>August</td><td>1973</td> </tr> </table> </body> </html> ''; // To send HTML mail, the Content-type header must be set $headers[] = ''MIME-Version: 1.0''; $headers[] = ''Content-type: text/html; charset=iso-8859-1''; // Additional headers $headers[] = ''To: Mary <[email protected]>, Kelly <[email protected]>''; $headers[] = ''From: Birthday Reminder <[email protected]>''; $headers[] = ''Cc: [email protected]''; $headers[] = ''Bcc: [email protected]''; // Mail it mail($to, $subject, $message, implode("/r/n", $headers)); ?>

Estoy usando PHP en un sitio web y quiero agregar la funcionalidad de correo electrónico.

Tengo instalado WAMPSERVER.

¿Cómo envío un correo electrónico usando PHP?


Este es un método muy básico para enviar correos electrónicos de texto simple usando la función de correo.

<?php $to = ''[email protected]''; $subject = ''This is subject''; $message = ''This is body of email''; $from = "From: FirstName LastName <[email protected]>"; mail($to,$subject,$message,$from);


La forma principal de enviar correos electrónicos desde PHP es usar la función mail (), pero hay un par de SDK listos para usar que pueden facilitar la integración:

  1. Swiftmailer
  2. https://github.com/PHPMailer/PHPMailer
  3. Pepipost (funciona a través de HTTP, por lo que se puede evitar el problema del bloqueo de puertos SMTP)
  4. Sendmail

PS Estoy empleado con Pepipost.


La función nativa de PHP Mail() no funciona para mí. Emite el mensaje:

503 Este servidor de correo requiere autenticación al intentar enviar a una dirección de correo electrónico no local

Así que normalmente uso el paquete PHPMailer

He descargado la versión 5.2.23 en GitHub .

Acabo de seleccionar 2 archivos y los puse en mi raíz PHP de origen

class.phpmailer.php
class.smtp.php

En el archivo PHP hay que añadirlo.

require_once(''class.smtp.php''); require_once(''class.phpmailer.php'');

Después de esto, es sólo el código:

require_once(''class.smtp.php''); require_once(''class.phpmailer.php''); ... //---------------------------------------------- // Send an e-mail. Returns true if successful // // $to - destination // $nameto - destination name // $subject - e-mail subject // $message - HTML e-mail body // altmess - text alternative for HTML. //---------------------------------------------- function sendmail($to,$nameto,$subject,$message,$altmess) { $from = "[email protected]" $namefrom = "yourname"; $mail = new PHPMailer(); $mail->CharSet = ''UTF-8''; $mail->isSMTP(); // by SMTP $mail->SMTPAuth = true; // user and password $mail->Host = "localhost"; $mail->Port = 25; $mail->Username = $from; $mail->Password = "yourpassword"; $mail->SMTPSecure = ""; // options: ''ssl'', ''tls'' , '''' $mail->setFrom($from,$namefrom); // From (origin) $mail->addCC($from,$namefrom); // There is also addBCC $mail->Subject = $subject; $mail->AltBody = $altmess; $mail->Body = $message; $mail->isHTML(); // Set HTML type //$mail->addAttachment("attachment"); $mail->addAddress($to, $nameto); return $mail->send(); }

Funciona a las mil maravillas


Para la mayoría de los proyectos, utilizo Swift mailer en estos días. Es un enfoque muy flexible y elegante orientado a objetos para enviar correos electrónicos, creado por las mismas personas que nos dieron el popular framework Symfony y el motor de plantillas Twig .

Uso básico:

require ''mail/swift_required.php''; $message = Swift_Message::newInstance() // The subject of your email ->setSubject(''Jane Doe sends you a message'') // The from address(es) ->setFrom(array(''[email protected]'' => ''Jane Doe'')) // The to address(es) ->setTo(array(''[email protected]'' => ''Frank Stevens'')) // Here, you put the content of your email ->setBody(''<h3>New message</h3><p>Here goes the rest of my message</p>'', ''text/html''); if (Swift_Mailer::newInstance(Swift_MailTransport::newInstance())->send($message)) { echo json_encode([ "status" => "OK", "message" => ''Your message has been sent!'' ], JSON_PRETTY_PRINT); } else { echo json_encode([ "status" => "error", "message" => ''Oops! Something went wrong!'' ], JSON_PRETTY_PRINT); }

Consulte la documentación oficial para obtener más información sobre cómo usar Swift Mailer.




Si está interesado en un correo electrónico con formato html, asegúrese de pasar Content-type: text/html; en el encabezado. Ejemplo:

// multiple recipients $to = ''[email protected]'' . '', ''; // note the comma $to .= ''[email protected]''; // subject $subject = ''Birthday Reminders for August''; // message $message = '' <html> <head> <title>Birthday Reminders for August</title> </head> <body> <p>Here are the birthdays upcoming in August!</p> <table> <tr> <th>Person</th><th>Day</th><th>Month</th><th>Year</th> </tr> <tr> <td>Joe</td><td>3rd</td><td>August</td><td>1970</td> </tr> <tr> <td>Sally</td><td>17th</td><td>August</td><td>1973</td> </tr> </table> </body> </html> ''; // To send HTML mail, the Content-type header must be set $headers = ''MIME-Version: 1.0'' . "/r/n"; $headers .= ''Content-type: text/html; charset=iso-8859-1'' . "/r/n"; // Additional headers $headers .= ''To: Mary <[email protected]>, Kelly <[email protected]>'' . "/r/n"; $headers .= ''From: Birthday Reminder <[email protected]>'' . "/r/n"; $headers .= ''Cc: [email protected]'' . "/r/n"; $headers .= ''Bcc: [email protected]'' . "/r/n"; // Mail it mail($to, $subject, $message, $headers);

Para más detalles, verifique la función de mail() php.


También busque en el paquete de correo de PEAR Página de correo de Pear

Parece ser un poco más robusto que la función estándar de correo () que está incorporada (si la función estándar no es adecuada).

Aquí hay un extracto de esta página que muestra cómo se usa. PEAR Mail send () uso

<?php include(''Mail.php''); $recipients = ''[email protected]''; $headers[''From''] = ''[email protected]''; $headers[''To''] = ''[email protected]''; $headers[''Subject''] = ''Test message''; $body = ''Test message''; $smtpinfo["host"] = "smtp.server.com"; $smtpinfo["port"] = "25"; $smtpinfo["auth"] = true; $smtpinfo["username"] = "smtp_user"; $smtpinfo["password"] = "smtp_password"; // Create the mail object using the Mail::factory method $mail_object =& Mail::factory("smtp", $smtpinfo); $mail_object->send($recipients, $headers, $body); ?>


También puede usar la clase PHPMailer en https://github.com/PHPMailer/PHPMailer .

Le permite utilizar la función de correo o usar un servidor smtp de forma transparente. También maneja correos electrónicos y archivos adjuntos basados ​​en HTML para que no tenga que escribir su propia implementación.

La clase es estable y es utilizada por muchos otros proyectos como Drupal, SugarCRM, Yii y Joomla!

Aquí hay un ejemplo de la página de arriba:

<?php require ''PHPMailerAutoload.php''; $mail = new PHPMailer; $mail->isSMTP(); // Set mailer to use SMTP $mail->Host = ''smtp1.example.com;smtp2.example.com''; // Specify main and backup SMTP servers $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = ''[email protected]''; // SMTP username $mail->Password = ''secret''; // SMTP password $mail->SMTPSecure = ''tls''; // Enable encryption, ''ssl'' also accepted $mail->From = ''[email protected]''; $mail->FromName = ''Mailer''; $mail->addAddress(''[email protected]'', ''Joe User''); // Add a recipient $mail->addAddress(''[email protected]''); // Name is optional $mail->addReplyTo(''[email protected]'', ''Information''); $mail->addCC(''[email protected]''); $mail->addBCC(''[email protected]''); $mail->WordWrap = 50; // Set word wrap to 50 characters $mail->addAttachment(''/var/tmp/file.tar.gz''); // Add attachments $mail->addAttachment(''/tmp/image.jpg'', ''new.jpg''); // Optional name $mail->isHTML(true); // Set email format to HTML $mail->Subject = ''Here is the subject''; $mail->Body = ''This is the HTML message body <b>in bold!</b>''; $mail->AltBody = ''This is the body in plain text for non-HTML mail clients''; if(!$mail->send()) { echo ''Message could not be sent.''; echo ''Mailer Error: '' . $mail->ErrorInfo; } else { echo ''Message has been sent''; }


Envió el correo electrónico con este script

<h2>Test Mail</h2> <?php if (!isset($_POST["submit"])) { ?> <form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>"> From: <input type="text" name="from"><br> Subject: <input type="text" name="subject"><br> Message: <textarea rows="10" cols="40" name="message"></textarea><br> <input type="submit" name="submit" value="Click To send mail"> </form> <?php } else { if (isset($_POST["from"])) { $from = $_POST["from"]; // sender $subject = $_POST["subject"]; $message = $_POST["message"]; $message = wordwrap($message, 70); mail("[email protected]",$subject,$message,"From: $from/n"); echo "Thank you for sending an email"; } } ?>

Una vez que presione el botón Enviar correo electrónico, el correo electrónico se enviará a [email protected]


Usando la función mail() PHP es posible. Recuerde que la función de correo no funcionará en el servidor local.

<?php $to = ''[email protected]''; $subject = ''the subject''; $message = ''hello''; $headers = ''From: [email protected]'' . "/r/n" . ''Reply-To: [email protected]'' . "/r/n" . ''X-Mailer: PHP/'' . phpversion(); mail($to, $subject, $message, $headers); ?>

Referencia:


<?php include "db_conn.php";//connection file require "PHPMailerAutoload.php";// it will be in PHPMailer require "class.smtp.php";// it will be in PHPMailer require "class.phpmailer.php";// it will be in PHPMailer $response = array(); $params = json_decode(file_get_contents("php://input")); if(!empty($params->email_id)){ $email_id = $params->email_id; $flag=false; echo "something"; if(!filter_var($email_id, FILTER_VALIDATE_EMAIL)) { $response[''ERROR'']=''EMAIL address format error''; echo json_encode($response,JSON_UNESCAPED_SLASHES); return; } $sql="SELECT * from sales where email_id =''$email_id'' "; $result = mysqli_query($conn,$sql); $count = mysqli_num_rows($result); $to = "[email protected]"; $subject = "DEMO Subject"; $messageBody ="demo message ."; if($count ==0){ $response["valid"] = false; $response["message"] = "User is not registered yet"; echo json_encode($response); return; } else { $mail = new PHPMailer(); $mail->IsSMTP(); $mail->SMTPAuth = true; // authentication enabled $mail->IsHTML(true); $mail->SMTPSecure = ''ssl'';//turn on to send html email // $mail->Host = "ssl://smtp.zoho.com"; $mail->Host = "p3plcpnl0749.prod.phx3.secureserver.net";//you can use gmail $mail->Port = 465; $mail->Username = "[email protected]"; $mail->Password = "demopassword"; $mail->SetFrom("[email protected]", "Any demo alert"); $mail->Subject = $subject; $mail->Body = $messageBody; $mail->AddAddress($to); echo "yes"; if(!$mail->send()) { echo "Mailer Error: " . $mail->ErrorInfo; } else { echo "Message has been sent successfully"; } } } else{ $response["valid"] = false; $response["message"] = "Required field(s) missing"; echo json_encode($response); } ?>

El código anterior está funcionando para mí.