PHP: Send Email Examples

August 20, 2017

Basic example:


$to = 'test@example.com';
$subject = 'Test Subject';
$message = 'Test Message';
$headers = "From: test@example.net\r\nReply-To: text@example.net";
mail($to, $subject, $message, $headers);

Basic example: (alternative)


mail('test@example.com', 'Test Subject', 'Test Message', 
    "From: test@example.net\r\nReply-To: text@example.net");

Email with HTML and Plain Text contents:


$to = 'test@example.com';
$subject = 'Test Subject';
$message = 'Test Message';
$headers = "From: test@example.net\r\nReply-To: text@example.net\r\n";
$headers.= "Content-Type: multipart/alternative; boundary=\"1234567890\"";

$message = <<<EOT
--1234567890 
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

This is the text version of the message. 

--1234567890 
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

<p>This is the html version of the message.</p>

--1234567890--
EOT;

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

Email with attachment:


$to = 'test@example.com';
$subject = 'Test Subject';
$message = 'Test Message';
$headers = "From: test@example.net\r\nReply-To: text@example.net";
$headers.= "Content-Type: multipart/mixed; boundary=\"1111111111\"";

$attachment = chunk_split(base64_encode(file_get_contents('attachment.zip')));

$message = <<<EOT
--1111111111 
Content-Type: multipart/alternative; boundary="2222222222"

--2222222222
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

This is the text version of the message. 

--2222222222
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

<p>This is the html version of the message.</p>

--2222222222--

--1111111111
Content-Type: application/zip; name="attachment.zip" 
Content-Transfer-Encoding: base64 
Content-Disposition: attachment 

$attachment
--1111111111--
EOT;

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

Email with Cc and Bcc:


$to = 'test@example.com';
$subject = 'Test Subject';
$message = 'Test Message';
$headers = "From: test@example.net\r\nReply-To: text@example.net\r\n";

$headers.= "Cc: email@example.com\r\n";
$headers.= "Bcc: email@example.com\r\n";

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

Email with HTML contents:


$to = 'test@example.com';
$subject = 'Test Subject';
$message = '<p>Test Message</p>';
$headers = "From: test@example.net\r\nReply-To: text@example.net\r\n";

$headers.= "MIME-Version: 1.0\r\n";
$headers.= "Content-type: text/html; charset=iso-8859-1\r\n";

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