Ricerca…


Parametri

Parametro Dettagli
string $to L'indirizzo email del destinatario
string $subject La riga dell'oggetto
string $message Il corpo dell'e-mail
string $additional_headers Opzionale: intestazioni da aggiungere all'email
string $additional_parameters Opzionale: argomenti da passare all'applicazione di invio posta configurata nella riga di comando

Osservazioni

L'e-mail che sto inviando tramite il mio script non arriva mai. Cosa dovrei fare?

  • Assicurati di avere segnalazioni di errori attivate per vedere eventuali errori.

  • Se hai accesso ai file di log degli errori di PHP, controlla quelli.

  • Il comando mail() configurato correttamente sul tuo server ? (Se si è in hosting condiviso, non è possibile modificare nulla qui.)

  • Se le e-mail stanno scomparendo, avvia un account di posta elettronica con un servizio di posta che ha una cartella di spam (o usa un account di posta che non prevede alcun filtro di spam). In questo modo, puoi vedere se l'e-mail non viene inviata, o forse inviata ma filtrata come spam.

  • Hai controllato l'indirizzo "da:" che hai utilizzato per i possibili messaggi "restituiti al mittente"? È anche possibile impostare un indirizzo di rimbalzo separato per i messaggi di errore.

L'e-mail che sto inviando viene filtrata come spam. Cosa dovrei fare?

  • L'indirizzo del mittente ("Da") appartiene a un dominio che viene eseguito sul server da cui si invia l'e-mail? Altrimenti, cambialo.

    Non utilizzare mai indirizzi mittente come [email protected] . Utilizza reply-to se hai bisogno di risposte per arrivare a un indirizzo diverso.

  • Il tuo server è su una lista nera? Questa è una possibilità quando sei in hosting condiviso quando i vicini si comportano male. La maggior parte dei provider di blacklist, come Spamhaus , ha strumenti che ti permettono di cercare l'IP del tuo server. Esistono anche strumenti di terze parti come MX Toolbox.

  • Alcune installazioni di PHP richiedono l'impostazione di un quinto parametro per mail () per aggiungere un indirizzo mittente. Guarda se questo potrebbe essere il tuo caso.

  • Se tutto il resto fallisce, prendi in considerazione l'uso di email come un servizio come Mailgun , SparkPost , Amazon SES , Mailjet , SendinBlue o SendGrid , solo per nominarne alcuni. Tutti hanno API che possono essere chiamate usando PHP.

Invio di e-mail - Informazioni di base, maggiori dettagli e un esempio completo

Una tipica email ha tre componenti principali:

  1. Un destinatario (rappresentato come un indirizzo email)
  2. Un soggetto
  3. Un corpo di messaggio

L'invio di posta in PHP può essere semplice come chiamare la funzione built-in mail() . mail() richiede fino a cinque parametri, ma i primi tre sono tutto ciò che è necessario per inviare un messaggio di posta elettronica (sebbene i quattro parametri siano comunemente usati come verrà dimostrato di seguito). I primi tre parametri sono:

  1. Indirizzo email del destinatario (stringa)
  2. L'oggetto dell'email (stringa)
  3. Il corpo dell'email (stringa) (ad esempio il contenuto dell'e-mail)

Un esempio minimo sarebbe simile al seguente codice:

mail('[email protected]', 'Email Subject', 'This is the email message body');

Il semplice esempio di cui sopra funziona bene in circostanze limitate come l'hardcoding di un avviso e-mail per un sistema interno. Tuttavia, è normale collocare i dati passati come parametri per mail() nelle variabili per rendere il codice più pulito e più facile da gestire (ad esempio, costruire dinamicamente una e-mail dall'invio di un modulo).

Inoltre, mail() accetta un quarto parametro che ti consente di avere intestazioni di posta aggiuntive inviate con la tua email. Queste intestazioni possono consentire di impostare:

  • il nome di From e l'indirizzo email che l'utente vedrà
  • l'indirizzo email Reply-To verrà inviata la risposta dell'utente
  • ulteriori intestazioni non standard come X-Mailer che possono dire al destinatario che questa email è stata inviata tramite PHP
$to      = '[email protected]';             // Could also be $to      = $_POST['recipient'];  
$subject = 'Email Subject';                     // Could also be $subject = $_POST['subject'];  
$message = 'This is the email message body';    // Could also be $message = $_POST['message'];  
$headers = implode("\r\n", [
    'From: John Conde <[email protected]>',
    'Reply-To: [email protected]',
    'X-Mailer: PHP/' . PHP_VERSION
]);

Il quinto parametro opzionale può essere utilizzato per passare altri flag come opzioni della riga di comando al programma configurato per essere utilizzato durante l'invio di posta, come definito dall'impostazione di configurazione sendmail_path . Ad esempio, questo può essere utilizzato per impostare l'indirizzo del mittente della busta quando si utilizza sendmail / postfix con l'opzione -f sendmail.

$fifth  = '[email protected]';

Anche se l'uso di mail() può essere abbastanza affidabile, non è assolutamente garantito che verrà inviata un'e- mail() quando viene chiamato mail() . Per vedere se c'è un potenziale errore durante l'invio della tua email, dovresti acquisire il valore di ritorno da mail() . TRUE sarà restituito se la posta è stata accettata con successo per la consegna. Altrimenti, riceverai FALSE .

$result = mail($to, $subject, $message, $headers, $fifth);

NOTA : Sebbene mail() possa restituire TRUE , ciò non significa che l'email è stata inviata o che l'email sarà ricevuta dal destinatario. Indica solo che la posta è stata consegnata con successo al sistema di posta del tuo sistema.

Se desideri inviare un'email HTML, non c'è molto più lavoro che devi fare. Devi:

  1. Aggiungi l'intestazione della MIME-Version
  2. Aggiungi l'intestazione Content-Type
  3. Assicurati che il tuo contenuto email sia HTML
$to      = '[email protected]';                            
$subject = 'Email Subject';                                     
$message = '<html><body>This is the email message body</body></html>';       
$headers = implode("\r\n", [
    'From: John Conde <[email protected]>',
    'Reply-To: [email protected]',
    'MIME-Version: 1.0',
    'Content-Type: text/html; charset=ISO-8859-1',
    'X-Mailer: PHP/' . PHP_VERSION
]);

Ecco un esempio completo di utilizzo della funzione mail() di PHP

<?php

// Debugging tools. Only turn these on in your development environment.

error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");

// Special mail settings that can make mail less likely to be considered spam
// and offers logging in case of technical difficulties.

ini_set("mail.log", "/tmp/mail.log");
ini_set("mail.add_x_header", TRUE);

// The components of our email

$to      = '[email protected]';
$subject = 'Email Subject';
$message = 'This is the email message body';
$headers = implode("\r\n", [
    'From: [email protected]',
    'Reply-To: [email protected]',
    'X-Mailer: PHP/' . PHP_VERSION
]);

// Send the email

$result = mail($to, $subject, $message, $headers);

// Check the results and react accordingly

if ($result) {
  
    // Success! Redirect to a thank you page. Use the
    // POST/REDIRECT/GET pattern to prevent form resubmissions
    // when a user refreshes the page.
  
    header('Location: http://example.com/path/to/thank-you.php', true, 303);
    exit;
  
}
else {
  
    // Your mail was not sent. Check your logs to see if
    // the reason was reported there for you.
  
}

Guarda anche

Documentazione ufficiale

Stack overflow domande correlate

Mailers alternativi

Email Server

Argomenti correlati

Invio di email HTML tramite posta ()

<?php
$to      = '[email protected]';
$subject = 'Sending an HTML email using mail() in PHP';
$message = '<html><body><p><b>This paragraph is bold.</b></p><p><i>This text is italic.</i></p></body></html>';

$headers = implode("\r\n", [
    "From: John Conde <[email protected]>",
    "Reply-To: [email protected]",
    "X-Mailer: PHP/" . PHP_VERSION,
    "MIME-Version: 1.0",
    "Content-Type: text/html; charset=UTF-8"
]);

mail($to, $subject, $message, $headers);

Questo non è molto diverso dall'invio di un messaggio di posta elettronica in chiaro . Le principali differenze chiave essendo il corpo del contenuto sono strutturate come un documento HTML e ci sono due intestazioni aggiuntive che devono essere incluse in modo che il client di posta elettronica sappia che il messaggio è indirizzato come HTML. Loro sono:

  • Versione MIME: 1.0
  • Content-Type: text / html; charset = UTF-8

Invio di e-mail di testo semplice tramite PHPMailer

Email di testo di base

<?php

$mail = new PHPMailer();

$mail->From     = "[email protected]";
$mail->FromName = "Full Name";
$mail->addReplyTo("[email protected]", "Reply Address");
$mail->Subject  = "Subject Text";
$mail->Body     = "This is a sample basic text email using PHPMailer.";

if($mail->send()) {
    // Success! Redirect to a thank you page. Use the
    // POST/REDIRECT/GET pattern to prevent form resubmissions
    // when a user refreshes the page.
  
    header('Location: http://example.com/path/to/thank-you.php', true, 303);
    exit;
} 
else {
    echo "Mailer Error: " . $mail->ErrorInfo;
}

Aggiunta di destinatari addizionali, destinatari CC, destinatari BCC

<?php

$mail = new PHPMailer();

$mail->From     = "[email protected]";
$mail->FromName = "Full Name";
$mail->addReplyTo("[email protected]", "Reply Address");
$mail->addAddress("[email protected]", "Recepient Name");
$mail->addAddress("[email protected]"); 
$mail->addCC("[email protected]");
$mail->addBCC("[email protected]");
$mail->Subject  = "Subject Text";
$mail->Body     = "This is a sample basic text email using PHPMailer.";

if($mail->send()) {
    // Success! Redirect to a thank you page. Use the
    // POST/REDIRECT/GET pattern to prevent form resubmissions
    // when a user refreshes the page.
  
    header('Location: http://example.com/path/to/thank-you.php', true, 303);
    exit;
} 
else {
    echo "Error: " . $mail->ErrorInfo;
}   

Invio di email con un allegato tramite mail ()

<?php

$to         = '[email protected]';
$subject    = 'Email Subject';
$message    = 'This is the email message body';

$attachment = '/path/to/your/file.pdf';
$content = file_get_contents($attachment);

/* Attachment content transferred in Base64 encoding
MUST be split into chunks 76 characters in length as
specified by RFC 2045 section 6.8. By default, the
function chunk_split() uses a chunk length of 76 with
a trailing CRLF (\r\n). The 76 character requirement
does not include the carriage return and line feed */
$content = chunk_split(base64_encode($content));

/* Boundaries delimit multipart entities. As stated
in RFC 2046 section 5.1, the boundary MUST NOT occur
in any encapsulated part. Therefore, it should be
unique. As stated in the following section 5.1.1, a
boundary is defined as a line consisting of two hyphens
("--"), a parameter value, optional linear whitespace,
and a terminating CRLF. */
$prefix     = "part_"; // This is an optional prefix
/* Generate a unique boundary parameter value with our
prefix using the uniqid() function. The second parameter
makes the parameter value more unique. */
$boundary   = uniqid($prefix, true);

// headers
$headers    = implode("\r\n", [
    'From: [email protected]',
    'Reply-To: [email protected]',
    'X-Mailer: PHP/' . PHP_VERSION,
    'MIME-Version: 1.0',
    // boundary parameter required, must be enclosed by quotes
    'Content-Type: multipart/mixed; boundary="' . $boundary . '"',
    "Content-Transfer-Encoding: 7bit",
    "This is a MIME encoded message." // message for restricted transports
]);

// message and attachment
$message    = implode("\r\n", [ 
    "--" . $boundary, // header boundary delimiter line
    'Content-Type: text/plain; charset="iso-8859-1"',
    "Content-Transfer-Encoding: 8bit",
    $message,
    "--" . $boundary, // content boundary delimiter line
    'Content-Type: application/octet-stream; name="RenamedFile.pdf"',
    "Content-Transfer-Encoding: base64",
    "Content-Disposition: attachment",
    $content,
    "--" . $boundary . "--" // closing boundary delimiter line
]);

$result = mail($to, $subject, $message, $headers); // send the email

if ($result) {
    // Success! Redirect to a thank you page. Use the
    // POST/REDIRECT/GET pattern to prevent form resubmissions
    // when a user refreshes the page.
  
    header('Location: http://example.com/path/to/thank-you.php', true, 303);
    exit;
}
else {
    // Your mail was not sent. Check your logs to see if
    // the reason was reported there for you.
}

Content-Transfer-codifiche

Le codifiche disponibili sono 7bit , 8bit , binary , quoted-stampabile , base64 , token ietf e x-token . Di queste codifiche, quando un'intestazione ha un Content-Type multiparte , la Content-Transfer-Encoding non deve avere alcun altro valore oltre a 7bit , 8bit o binary come indicato nella RFC 2045, sezione 6.4.

Il nostro esempio sceglie la codifica a 7 bit, che rappresenta i caratteri US-ASCII, per l'intestazione multipart perché, come notato nella sezione 6 dell'RFC 2045, alcuni protocolli supportano solo questa codifica. I dati entro i limiti possono quindi essere codificati su base part-by-part (RFC 2046, sezione 5.1). Questo esempio fa esattamente questo. La prima parte, che contiene il messaggio text / plain, è definita come 8bit poiché potrebbe essere necessario supportare caratteri aggiuntivi. In questo caso, viene utilizzato il set di caratteri Latin1 (iso-8859-1). La seconda parte è l'allegato e quindi è definita come un'applicazione codificata in base64 / octet-stream. Poiché base64 trasforma dati arbitrari nell'intervallo 7bit, può essere inviato su trasporti con restrizioni (RFC 2045, sezione 6.2).

Invio di email HTML tramite PHPMailer

<?php

$mail = new PHPMailer();

$mail->From     = "[email protected]";
$mail->FromName = "Full Name";
$mail->addReplyTo("[email protected]", "Reply Address");
$mail->addAddress("[email protected]", "Recepient Name");
$mail->addAddress("[email protected]"); 
$mail->addCC("[email protected]");
$mail->addBCC("[email protected]");
$mail->Subject  = "Subject Text";
$mail->isHTML(true);
$mail->Body     = "<html><body><p><b>This paragraph is bold.</b></p><p><i>This text is italic.</i></p></body></html>";
$mail->AltBody = "This paragraph is not bold.\n\nThis text is not italic.";

if($mail->send()) {
    // Success! Redirect to a thank you page. Use the
    // POST/REDIRECT/GET pattern to prevent form resubmissions
    // when a user refreshes the page.
  
    header('Location: http://example.com/path/to/thank-you.php', true, 303);
    exit;
} 
else {
    echo "Error: " . $mail->ErrorInfo;
}   

Invio di email con un allegato tramite PHPMailer

<?php

$mail = new PHPMailer();

$mail->From     = "[email protected]";
$mail->FromName = "Full Name";
$mail->addReplyTo("[email protected]", "Reply Address");
$mail->Subject  = "Subject Text";
$mail->Body     = "This is a sample basic text email with an attachment using PHPMailer.";

// Add Static Attachment
$attachment = '/path/to/your/file.pdf';
$mail->AddAttachment($attachment , 'RenamedFile.pdf');

// Add Second Attachment, run-time created. ie: CSV to be open with Excel
$csvHeader = "header1,header2,header3";
$csvData = "row1col1,row1col2,row1col3\nrow2col1,row2col2,row2col3";

$mail->AddStringAttachment($csvHeader ."\n" . $csvData, 'your-csv-file.csv', 'base64', 'application/vnd.ms-excel');

if($mail->send()) {
    // Success! Redirect to a thank you page. Use the
    // POST/REDIRECT/GET pattern to prevent form resubmissions
    // when a user refreshes the page.
  
    header('Location: http://example.com/path/to/thank-you.php', true, 303);
    exit;
} 
else {
    echo "Error: " . $mail->ErrorInfo;
}   

Invio di e-mail di testo semplice con Sendgrid

Email di testo di base

<?php

$sendgrid = new SendGrid("YOUR_SENDGRID_API_KEY");
$email    = new SendGrid\Email();

$email->addTo("[email protected]")
      ->setFrom("[email protected]")
      ->setSubject("Subject Text")
      ->setText("This is a sample basic text email using ");

$sendgrid->send($email);

Aggiunta di destinatari addizionali, destinatari CC, destinatari BCC

<?php

$sendgrid = new SendGrid("YOUR_SENDGRID_API_KEY");
$email    = new SendGrid\Email();

$email->addTo("[email protected]")
      ->setFrom("[email protected]")
      ->setSubject("Subject Text")
      ->setHtml("<html><body><p><b>This paragraph is bold.</b></p><p><i>This text is italic.</i></p></body></html>");
      
$personalization = new Personalization();
$email = new Email("Recepient Name", "[email protected]");
$personalization->addTo($email);
$email = new Email("RecepientCC Name", "[email protected]");
$personalization->addCc($email);
$email = new Email("RecepientBCC Name", "[email protected]");
$personalization->addBcc($email);
$email->addPersonalization($personalization);
    
$sendgrid->send($email);

Invio di e-mail con un allegato utilizzando Sendgrid

<?php

$sendgrid = new SendGrid("YOUR_SENDGRID_API_KEY");
$email    = new SendGrid\Email();

$email->addTo("[email protected]")
      ->setFrom("[email protected]")
      ->setSubject("Subject Text")
      ->setText("This is a sample basic text email using ");
      
$attachment = '/path/to/your/file.pdf';
$content    = file_get_contents($attachment);
$content    = chunk_split(base64_encode($content));

$attachment = new Attachment();
$attachment->setContent($content);
$attachment->setType("application/pdf");
$attachment->setFilename("RenamedFile.pdf");
$attachment->setDisposition("attachment");
$email->addAttachment($attachment);

$sendgrid->send($email);


Modified text is an extract of the original Stack Overflow Documentation
Autorizzato sotto CC BY-SA 3.0
Non affiliato con Stack Overflow