PHP mail() Function
PHP mail() Function
PHP mail is the built in PHP function that is used to send emails from PHP scripts.
The mail function accepts the following parameters;
- Email address
- Subject
- Message
- CC or BC email addresses
Uses of Mail Function
- It’s a cost effective way of notifying users on important events.
- Let users contact you via email by providing a contact us form on the website that emails the provided content.
- Developers can use it to receive system errors by email
- You can use it to email your newsletter subscribers.
- You can use it to send password reset links to users who forget their passwords
- You can use it to email activation/confirmation links. This is useful when registering users and verifying their email addresses
PHP must be configured correctly in the php.ini file with the details of how your system sends email. Open php.ini file available in /etc/ directory and find the section headed [mail function].
Windows users should ensure that two directives are supplied. The first is called SMTP that defines your email server address. The second is called sendmail_from which defines your own email address.
<?php
// the message
$msg = "First line of text\nSecond line of text";
// use wordwrap() if lines are longer than 70 characters
$msg = wordwrap($msg,70);
// send email
mail("someone@example.com","My subject",$msg);
?>
Definition and Usage
The mail() function allows you to send emails directly from a script. its syntax is mail(to,subject,message,headers,parameters);
`Technical Details
Quantifiers define quantities:
`Return Value: | Returns the hash value of the address parameter, or FALSE on failure. Note: Keep in mind that even if the email was accepted for delivery, it does NOT mean the email is actually sent and received! |
PHP Changelog: | PHP 7.2: The headers parameter also accepts an array. PHP 5.4: Added header injection protection for the headers parameter. PHP 4.3.0: (Windows only) All custom headers (like From, Cc, Bcc and Date) are supported, and are not case-sensitive. PHP 4.2.3: The parameter parameter is disabled in safe mode PHP 4.0.5: The parameter parameter was added |
More Examples
Send an email with extra 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);
?<
Send an HTML email:
>?php
$to = "somebody@example.com, somebodyelse@example.com";
$subject = "HTML email";
$message = "
<html>
<head>
<title>HTML email</title>
</head>
<body>
<p>This email contains HTML Tags!>/p>
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
</tr>
</table>
</body>
</html>
";
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers
$headers .= 'From: ' . "\r\n";
$headers .= 'Cc: myboss@example.com' . "\r\n";
mail($to,$subject,$message,$headers);
?>
Sending HTML Formatted Emails
When you send a text message using PHP, all the content will be treated as simple text. We're going to improve that output, and make the email into a HTML-formatted email. To send an HTML email, the process will be the same. However, this time we need to provide additional headers as well as an HTML formatted message..
`
<?php
$to = 'maryjane@email.com';
$subject = 'Marriage Proposal';
$from = 'peterparker@email.com';
// 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";
// Create email headers
$headers .= 'From: '.$from."\r\n".
'Reply-To: '.$from."\r\n" .
'X-Mailer: PHP/' . phpversion();
// Compose a simple HTML email message
$message = '<html><body>';
$message .= '<h1 style="color:#f40;">Hi Jane!';
$message .= '<p style="color:#080;font-size:18px;">Will you marry me?';
$message .= '</body>>/html>';
// Sending email
if(mail($to, $subject, $message, $headers)){
echo 'Your mail has been sent successfully.';
} else{
echo 'Unable to send email. Please try again.';
}
?>
Sending attachments with email
To send an email with mixed content requires to set Content-type header to multipart/mixed. Then text and attachment sections can be specified within boundaries.
A boundary is started with two hyphens followed by a unique number which can not appear in the message part of the email. A PHP function md5() is used to create a 32 digit hexadecimal number to create unique number. A final boundary denoting the email's final section must also end with two hyphens.
`
<?php
// request variables // important
$from = $_REQUEST["from"];
$emaila = $_REQUEST["emaila"];
$filea = $_REQUEST["filea"];
if ($filea) {
function mail_attachment ($from , $to, $subject,
$message, $attachment){
$fileatt = $attachment; // Path to the file
$fileatt_type = "application/octet-stream"; // File Type
$start = strrpos($attachment, '/') == -1 ?
strrpos($attachment, '//') : strrpos($attachment, '/')+1;
$fileatt_name = substr($attachment, $start,
strlen($attachment)); // Filename that will be
used for the
file as the attachment
$email_from = $from; // Who the email is from
$subject = "New Attachment Message";
$email_subject = $subject; // The Subject of the email
$email_txt = $message; // Message that the email has in it
$email_to = $to; // Who the email is to
$headers = "From: ".$email_from;
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);
$msg_txt="\n\n You have recieved a new attachment
message from $from";
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type:
multipart/mixed;\n" . "
boundary=\"{$mime_boundary}\"";
$email_txt .= $msg_txt;
$email_message .= "This is a multi-part message in
MIME format.\n\n" .
"--{$mime_boundary}\n" . "Content-Type:text/html;
charset = \"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$email_txt . "\n\n";
$data = chunk_split(base64_encode($data));
$email_message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatt_type};\n" .
" name = \"{$fileatt_name}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename = \"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding:
base64\n\n" . $data . "\n\n" . "--{$mime_boundary}--\n";
$ok = mail($email_to, $email_subject,
$email_message, $headers);
if($ok) {
echo "File Sent Successfully.";
unlink($attachment); // delete a file after attachment sent.
}else {
die("Sorry but the email could not be sent.
Please go back and try again!");
}
}
move_uploaded_file($_FILES["filea"]["tmp_name"],
'temp/'.basename($_FILES['filea']['name']));
mail_attachment("$from", "youremailaddress@gmail.com",
"subject", "message", ("temp/".$_FILES
["filea"]["name"]));
}*/
?>
<html>
<head>
<script language = "javascript" type =
"text/javascript">
function CheckData45() {
with(document.filepost) {
if(filea.value ! = "") {
document.getElementById('one').innerText =
"Attaching File ... Please Wait";
}
}
}
</script>
</head>
<body>
<table width = "100%" height = "100%" border = "0"
cellpadding = "0" cellspacing = "0">
<tr>
<td align = "center">
<form name = "filepost" method = "post"
action = "file.php" enctype =
"multipart/form-data" id = "file">
<table width = "300" border = "0" cellspacing = "0"
cellpadding = "0">
<tr valign = "bottom">
<td height = "20">Your Name:</td>
</tr>
<tr>
<td>&input name = "from" type = "text"
id = "from" size = "30"></td>
</tr>
<tr valign = "bottom">
<td height = "20">
Your Email Address:</td>
</tr>
<tr>
<td class = "frmtxt2">
<input name = "emaila"
type = "text" id = "emaila" size =
"30"></td>
</tr>
<tr>
<td height = "20" valign =
"bottom">Attach File:</td>
</tr>
<tr valign = "bottom">
<td valign = "bottom"><input name = "filea"
type = "file" id = "filea" size = "16"></td>
</tr>
<tr>
<td height = "40" valign =
"middle"><input
name = "Reset2" type = "reset" id =
"Reset2" value = "Reset">
<input name = "Submit2" type = "submit"
value = "Submit" onClick = "return
CheckData45()"></td>
</tr>
</table>
</form>
<center>
<table width = "400">
<tr>
<td id = "one">
</td>
</tr>
</table>
</center>
</td>
</tr>
</table>
</body>
</html>