Как отправить электронное письмо с помощью PHP?

Я использую PHP на веб-сайте, и я хочу добавить функциональность электронной почты.

У меня установлен WAMPSERVER.

Как отправить электронное письмо с помощью PHP?

Используя функцию PHP mail() это возможно. Помните, что функция почты не будет работать на локальном сервере.

 <?php $to = 'nobody@example.com'; $subject = 'the subject'; $message = 'hello'; $headers = 'From: webmaster@example.com' . "\r\n" . 'Reply-To: webmaster@example.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); mail($to, $subject, $message, $headers); ?> 

Справка:

Вы также можете использовать класс PHPMailer на странице https://github.com/PHPMailer/PHPMailer .

Он позволяет использовать почтовую функцию или прозрачно использовать SMTP-сервер. Он также обрабатывает электронные письма и вложения на основе HTML, поэтому вам не нужно писать собственную реализацию.

Класс стабилен и используется многими другими проектами, такими как Drupal, SugarCRM, Yii и Joomla!

Вот пример со страницы выше:

 <?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 = 'user@example.com'; // SMTP username $mail->Password = 'secret'; // SMTP password $mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted $mail->From = 'from@example.com'; $mail->FromName = 'Mailer'; $mail->addAddress('joe@example.net', 'Joe User'); // Add a recipient $mail->addAddress('ellen@example.com'); // Name is optional $mail->addReplyTo('info@example.com', 'Information'); $mail->addCC('cc@example.com'); $mail->addBCC('bcc@example.com'); $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'; } 

Если вас интересует html-форматированный адрес электронной почты, обязательно передайте Content-type: text/html; в заголовке. Пример:

 // multiple recipients $to = 'aidan@example.com' . ', '; // note the comma $to .= 'wez@example.com'; // 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 <mary@example.com>, Kelly <kelly@example.com>' . "\r\n"; $headers .= 'From: Birthday Reminder <birthday@example.com>' . "\r\n"; $headers .= 'Cc: birthdayarchive@example.com' . "\r\n"; $headers .= 'Bcc: birthdaycheck@example.com' . "\r\n"; // Mail it mail($to, $subject, $message, $headers); 

Для получения дополнительной информации проверьте функцию php mail .

Также посмотрите на почтовый пакет PEAR Pear Mail Page

Он кажется немного более надежным, чем стандартная функция mail (), которая встроена (если стандартная функция не подходит).

Вот выдержка из этой страницы, показывающая, как она используется. Использование PEAR Mail send ()

 <?php include('Mail.php'); $recipients = 'joe@example.com'; $headers['From'] = 'richard@example.com'; $headers['To'] = 'joe@example.com'; $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); ?> в <?php include('Mail.php'); $recipients = 'joe@example.com'; $headers['From'] = 'richard@example.com'; $headers['To'] = 'joe@example.com'; $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); ?> 

Для большинства проектов я использую Swift-почтовую службу в эти дни. Это очень гибкий и элегантный объектно-ориентированный подход к отправке писем, созданных теми же людьми, которые предоставили нам популярную платформу Symfony и механизм шаблонов Twig .


Основное использование:

 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('jane.doe@gmail.com' => 'Jane Doe')) // The to address(es) ->setTo(array('frank.stevens@gmail.com' => '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); } 

Дополнительную информацию о том, как использовать Swift-почерк, см. В официальной документации .

это очень простой способ отправки текстового сообщения электронной почты с использованием функции почты.

 <?php $to = 'SomeOtherEmailAddress@Domain.com'; $subject = 'This is subject'; $message = 'This is body of email'; $from = "From: FirstName LastName <SomeEmailAddress@Domain.com>"; mail($to,$subject,$message,$from); 

Полный пример кода.

Попробуйте это раз ..

 <?php // Multiple recipients $to = 'johny@example.com, sally@example.com'; // 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 <mary@example.com>, Kelly <kelly@example.com>'; $headers[] = 'From: Birthday Reminder <birthday@example.com>'; $headers[] = 'Cc: birthdayarchive@example.com'; $headers[] = 'Bcc: birthdaycheck@example.com'; // Mail it mail($to, $subject, $message, implode("\r\n", $headers)); ?> 

Попробуй это:

 <?php $to = "somebody@example.com"; $subject = "My subject"; $txt = "Hello world!"; $headers = "From: webmaster@example.com" . "\r\n" . "CC: somebodyelse@example.com"; mail($to,$subject,$txt,$headers); ?> 

Вы можете использовать почтовый веб-сервис, такой как Postmark, Sendgrid и т. Д.

Sendgrid vs Postmark vs Amazon SES и другие поставщики услуг электронной почты / SMTP API?

Изменить. Я просто использую API Google Gmail . У меня возникли проблемы с отправкой напоминания по электронной почте моей организации работодателя из-за строгих фильтров. Но Gmail работает до тех пор, пока вы не спамете людей.

Отправил электронную почту с этим скриптом

 <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("Test@example.com",$subject,$message,"From: $from\n"); echo "Thank you for sending an email"; } } ?> 

Как только вы нажмете кнопку «Отправить электронную почту», электронное письмо будет отправлено на адрес Test@example.com