Come inviare un'e-mail utilizzando PHP?


312

Sto usando PHP su un sito Web e voglio aggiungere funzionalità di e-mail.

Ho installato WAMPSERVER.

Come posso inviare un'e-mail tramite PHP?


19
Leggi il manuale
— Eco Eco

Risposte:


443

L'uso della mail()funzione di PHP è possibile. Ricorda che la funzione di posta non funzionerà su un server locale.

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

Riferimento:


6
cosa succede se devo inviare un'e-mail dal server locale. Voglio dire, c'è un modo per accedere al server di posta più vicino e farlo mandare posta per me. voglio dire che posso trovare l'indirizzo di un server di posta yahoo e quindi uso quel server per scopi di posta ... è possibile?
— user590849

19
Devi configurare SMTP sul tuo server locale. Dai un'occhiata a questo post simile, stackoverflow.com/questions/4652566/php-mail-setup-in-xampp
— Muthu Kumaran

Ciao @MuthuKumaran se questo va nello spam, c'è qualche buona soluzione per risolverlo, per favore rispondi.
— Muhammad Ashikuzzaman,

@MuhammadAshikuzzaman Non puoi risolvere il problema dello spam in PHP. Si prega di porre una nuova domanda sul sito StackExchange appropriato se questo è ancora rilevante.
— Uli Köhler,

Come assicurarsi o verificare se funziona sul mio server locale? Se non sono possibili metodi per farlo, suggerisci alcune alternative per favore. grazie.
— abhishah901,

121

Puoi anche usare la classe PHPMailer su https://github.com/PHPMailer/PHPMailer .

Ti permette di usare la funzione mail o usare un server smtp in modo trasparente. Gestisce anche e-mail e allegati basati su HTML in modo da non dover scrivere la propria implementazione.

La classe è stabile ed è utilizzata da molti altri progetti come Drupal, SugarCRM, Yii e Joomla!

Ecco un esempio dalla pagina sopra:

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

4
Se non si utilizza il compositore:use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; require_once('src/PHPMailer.php'); require_once('src/Exception.php');
— Wtower,

43

Se sei interessato a e-mail in formato HTML, assicurati di passare Content-type: text/html;l'intestazione. Esempio:

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

Per maggiori dettagli, controlla la funzione di posta php .


Ciao, ho stanco questo codice, ho aggiunto 3 destinatari, uno Hotmail, uno Gmail e uno il mio indirizzo e-mail del sito Web. Ho ricevuto tutto tranne su Hotmail. Hai idea del perché non funziona per Hotmail?
— antf,

Si prega di controllare la cartella spam in quel caso.
— Sumoan e

L'ho già fatto, non è nello spam, non sta raggiungendo affatto. Ho letto un po 'di più sull'argomento e sembra che Hotmail richieda un'intestazione speciale o non consente all'e-mail di passare i propri server ... Tuttavia non ho ancora trovato la soluzione.
— antf,

Ho risolto il mio problema utilizzando PHPMailer e inserendo i dati del mio account e-mail con SSL nell'oggetto e-mail di PHPMailer.
— antf,

Cosa succede se il messaggio ha contenuti HTML e php?

14

Guarda anche nel pacchetto di posta PEAR Pear Mail Page

Sembra essere un po 'più robusto della funzione standard mail () incorporata (se la funzione standard non è adeguata).

Ecco un estratto da questa pagina che mostra come viene utilizzato. Utilizzo dell'invio () di PEAR Mail

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

si prega di fornire un collegamento per il download del collegamento mail.php utilizzato e tutti gli altri file associati in una cartella. Grazie
— Muhammad Ashikuzzaman il

1
@Ashik Il Mail.phpfile indicato nel mio esempio fa parte del pacchetto Pear Mail. Se scarichi e installi il pacchetto Pear Mail, sarai in grado di includerlo Mail.php. Se fai clic sul link "Pear Mail Page" qui sopra, c'è un link per il download con le istruzioni.
— Kevin S,

12

Per la maggior parte dei progetti, utilizzo Swift mailer in questi giorni. È un approccio orientato agli oggetti molto flessibile ed elegante per l'invio di e-mail, creato dalle stesse persone che ci hanno fornito il popolare framework Symfony e il motore di template Twig .


Utilizzo di base:

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

Consulta la documentazione ufficiale per ulteriori informazioni su come utilizzare Swift mailer.


Ciao. Hai detto Swift_MailTransportquando dice il tuo link alla documentazione Swift_SendmailTransport. Vuol dire che ti riferivi alla versione precedente di Swift Mailer o è un refuso, o forse ho frainteso qualcosa? Devo installare la versione precedente di swift-mailer perché non ho php7 sul mio server. Quindi ho bisogno di sapere se la documentazione per la versione corrente andrebbe con la versione precedente del pacchetto. Grazie.
— Yevgeniy Afanasyev,

1
@YevgeniyAfanasyev: la mia risposta è stata il modo corretto di fare le cose 2 anni fa, ma Swift_MailTransport è stato deprecato da Swiftmailer v5.4.5 . Comunque, se non puoi usare PHP 7 per il tuo progetto, dovresti andare con Swiftmailer v5.4.9. Questa è l'ultima versione stabile che supporta ancora PHP 5. Per la documentazione della versione v5.4.9 o dettagli sulle differenze tra v5.4.9 e v6.0.2, potresti voler contattare Fabien Potencier o sollevare un problema su Github .
— John Slegers,

Grazie mille. Quindi non è disponibile alcuna documentazione per la versione precedente, quando sono disponibili i distributori. Buono a sapersi.
— Yevgeniy Afanasyev il

7

questo è un metodo molto semplice per inviare email in testo semplice usando la funzione mail.

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

7

Prova questo:

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

5

Esempio di codice completo ..

Provalo una volta ..

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

5

Per i lettori futuri: prova questo se le altre risposte non funzionano (come nel mio caso):

1.) Scarica PHPMailer , apri il file zip ed estrai la cartella nella directory del tuo progetto.

3.) Rinominare la directory estratta in PHPMailer e scrivere il codice seguente all'interno dello script php (lo script deve essere esterno alla cartella 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 = 'sender@gmail.com';  // sender gmail host              
    $mail->Password = 'password'; // sender gmail host password                          
    $mail->SMTPSecure = 'tls';  // for encrypted connection                           
    $mail->Port = 587;   // port for SMTP     

    $mail->setFrom('sender@gmail.com', "Sender"); // sender's email and name
    $mail->addAddress('receiver@gmail.com', "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;
}
?>

5

La funzione PHP nativa mail()non funziona per me. Emette il messaggio:

503 Questo server di posta richiede l'autenticazione quando si tenta di inviare a un indirizzo di posta elettronica non locale

Quindi, di solito uso il PHPMailerpacchetto

Ho scaricato la versione 5.2.23 da: GitHub .

Ho appena selezionato 2 file e li ho inseriti nella mia radice PHP di origine

class.phpmailer.php
class.smtp.php

In PHP, il file deve essere aggiunto

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

Dopo questo, è solo il codice:

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  = "yourcontact@yourdomain.com";
  $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();
}

Esso funziona magicamente


2
La ringrazio per la risposta. Hai lo stesso suggerimento di @norteo indicato nella sua risposta. Tieni presente che la versione 5.2 è obsoleta e non riceve aggiornamenti di sicurezza. Per la v6 puoi richiedere direttamente:use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; require_once('src/PHPMailer.php'); require_once('src/Exception.php');
— Wtower,

4

Il modo principale per inviare e-mail da PHP è utilizzare la sua mail()funzione integrata, ma ci sono un paio di SDK pronti all'uso che possono facilitare l'integrazione:

  1. Swiftmailer
  2. PHPMailer
  3. Pepipost (funziona su HTTP, quindi è possibile evitare il problema del blocco della porta SMTP)
  4. Inviare una mail

PS Sono impiegato con Pepipost.


3
Sei impiegato con Pepipost e metti Pepipost al n. 3. +1
— GeneCode

2
@GeneCode, Se qualcosa è meglio, allora lo è. Non importa se sei impiegato con loro o meno :) Swiftmailer e PHPMailer, sono sicuramente uno dei migliori strumenti open source per l'invio di e-mail (quindi li ho tenuti in 1 e 2). Allo stesso tempo, hanno alcune limitazioni e blocchi che abbiamo cercato di risolvere nel nostro SDK Pepipost.
— Dibya Sahoo,


1

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

Dopo aver premuto il pulsante Invia e-mail, l'e-mail verrà inviata a Test@esempio.com


1
<?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 = "demo@gmail.com";
    $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 = "demousername@example.com";
        $mail->Password = "demopassword";
        $mail->SetFrom("demousername@example.com", "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);
}


?>

Il codice sopra funziona per me.

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.