Jak wysłać e-mail za pomocą PHP?

Używam PHP na stronie internetowej i chcę dodać funkcjonalność wysyłania e-maili.

Mam zainstalowany WAMPSERVER.

Jak wysłać e-mail używając PHP?

Author: John Slegers, 2011-03-17

14 answers

Using PHP ' S mail() funkcja jest możliwa. Pamiętaj funkcja mail nie będzie działać na lokalnym serwerze.

<?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);
?> 

Odniesienie:

 460
Author: Muthu Kumaran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-04-11 20:47:39

Możesz również użyć klasy PHPMailer w https://github.com/PHPMailer/PHPMailer .

Pozwala na korzystanie z funkcji mail lub korzystanie z serwera smtp w sposób przejrzysty. Obsługuje również wiadomości e-mail i załączniki w formacie HTML, dzięki czemu nie musisz pisać własnej implementacji.

Klasa jest stabilna i jest używana przez wiele innych projektów, takich jak Drupal, SugarCRM, Yii i Joomla!

Oto przykład z powyższej strony:

<?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';
}
 126
Author: norteo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-23 13:35:50

Jeśli jesteś zainteresowany HTML sformatowany e-mail, upewnij się, aby przekazać Content-type: text/html; w nagłówku. Przykład:

// 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);

Aby uzyskać więcej szczegółów, sprawdź PHP mail function.

 44
Author: Sumoanand,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-20 01:22:08

Zajrzyj także do Pear mail package Pear Mail Page

Wydaje się być nieco bardziej wytrzymała niż wbudowana standardowa funkcja mail () (jeśli standardowa funkcja nie jest odpowiednia).

Oto fragment tej strony pokazujący, jak jest on używany. użycie Pear Mail send ()

<?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);
?> 
 14
Author: Kevin S,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-03-17 05:48:04

W większości projektów używam Swift mailer ostatnio. To bardzo elastyczne i eleganckie podejście obiektowe do wysyłania maili, stworzone przez te same osoby, które dały nam popularne Symfony framework oraz Twig template engine.


Użycie podstawowe:

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);
}

Zobacz oficjalna dokumentacja aby uzyskać więcej informacji na temat korzystania z programu Swift mailer.

 12
Author: John Slegers,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-20 09:12:55

Spróbuj tego:

<?php
$to = "[email protected]";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: [email protected]" . "\r\n" .
"CC: [email protected]";

mail($to,$subject,$txt,$headers);
?>
 8
Author: lyndact,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-22 04:26:21

Dla przyszłych czytelników: spróbuj, jeśli inne odpowiedzi nie zadziałają (jak to było u mnie):

1.) Pobierz PHPMailer , otwórz plik zip i rozpakuj folder do katalogu projektu.

3.) Zmień nazwę wyodrębnionego katalogu na PHPMailer i wpisz poniższy kod wewnątrz skryptu php (skrypt musi znajdować się poza folderem PHPMailer)

<?php
// PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer; 
use PHPMailer\PHPMailer\Exception;
// Base files 
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
// create object of PHPMailer class with boolean parameter which sets/unsets exception.
$mail = new PHPMailer(true);                              
try {
    $mail->isSMTP(); // using SMTP protocol                                     
    $mail->Host = 'smtp.gmail.com'; // SMTP host as gmail 
    $mail->SMTPAuth = true;  // enable smtp authentication                             
    $mail->Username = '[email protected]';  // sender gmail host              
    $mail->Password = 'password'; // sender gmail host password                          
    $mail->SMTPSecure = 'tls';  // for encrypted connection                           
    $mail->Port = 587;   // port for SMTP     

    $mail->setFrom('[email protected]', "Sender"); // sender's email and name
    $mail->addAddress('[email protected]', "Receiver");  // receiver's email and name

    $mail->Subject = 'Test subject';
    $mail->Body    = 'Test body';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) { // handle error.
    echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
?>
 8
Author: Ahtisham,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-01-20 13:17:38

Jest to bardzo podstawowa metoda wysyłania wiadomości e-mail za pomocą funkcji mail.

<?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);
 7
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-17 07:32:52

Podstawowym sposobem wysyłania wiadomości e-mail z PHP jest użycie wbudowanej funkcji mail(), ale istnieje kilka gotowych do użycia zestawów SDK, które mogą ułatwić integrację:

  1. Swiftmailer
  2. PHPMailer
  3. [13]} Pepipost (działa przez HTTP, stąd można uniknąć problemu z blokowaniem portów SMTP)
  4. Sendmail
P. S. jestem zatrudniony w Pepipost.
 7
Author: Dibya Sahoo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-04-11 20:49:38

Natywna funkcja PHP mail() nie działa dla mnie. Wydaje wiadomość:

503 ten serwer pocztowy wymaga uwierzytelnienia podczas próby wysłania na nielokalny adres e-mail

Więc zazwyczaj używam PHPMailer pakietu

Ściągnąłem wersję 5.2.23 z: GitHub.

Właśnie wybrałem 2 pliki i umieściłem je w moim źródłowym korzeniu PHP

Klasa.phpmailer.php
klasy.smtp.php

W PHP plik musi do dodania

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

Po tym, to tylko kod:

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();
}

To działa jak urok

 6
Author: Paulo Buchsbaum,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-04-11 20:34:17

Przykład pełnego kodu..

Spróbuj raz..
<?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));
?>
 5
Author: Mr. HK,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-21 03:40:50

Możesz użyć usługi poczty internetowej, takiej jak Postmark, Sendgrid itp.

Sendgrid vs Postmark vs Amazon SES i inni dostawcy e-mail / SMTP API?

Edit: właśnie używam Google Gmail API teraz. Miałem problemy z wysłaniem e-maila z przypomnieniem do organizacji mojego pracodawcy ze względu na ścisłe filtry. Ale Gmail działa tak długo, jak nie spamujesz ludzi.

 3
Author: emolaus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:02:45

Wysłano e-mail z tym skryptem

<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";
    }
  }
?>

Po naciśnięciu przycisku Wyślij e-mail, wiadomość zostanie wysłana na [email protected]

 1
Author: Hiren Parghi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-04 13:48:36
<?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);
}


?>

Powyższy kod działa dla mnie.

 1
Author: Pooja Khatri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-14 08:51:50