Send Email Using PHP Script

In building a web application, sometimes we need a function to send email. For example, to verify the registration, send the latest product information to customers, send information lost passwords, or send articles for the readers. When we use PHP, we could use the function mail() to send email to the user.

Syntax :
mail ( string to, string subject, string message [, string additional_headers [, string additional_parameters]]);

Function mail() has three required parameters namely, destination email address, email subject and content of a message, and one optional parameter that email headers. Now we try to the simple script below:

<?
if(mail("admin@yourwebsite.com", "Try to send email", "This is email to test script, thanks for your response")){
  echo "Email Sent";
}
else{
  echo "Failed to send email";
}
?>
In the script above we try to send email with the subject "Try to send email", and the message "This is email to test script, thanks for your response". For email destination address "admin@yourwebsite.com", you can change the email address to test this script. In the script if the function mail () fails to send an email it will show the message "Failed to send email". Now we proceed to try to send an email with the header parameters, you can try the following script:
<?
if(mail("admin@yourwebsite.com", "Try to send email", "This is email to test script \nThanks for your response","From: Djambrong <test@djambrong.com>")){
  echo "Email Sent";
}
else{
  echo "Failed to send email";
}
?>
At the script above we are using \n in the content of message to change the line, we are also adding the header parameters "From: Djambrong <test@djambrong.com>" so the recipient know who are the sender of the email. Now we proceed to send emails in HTML format. You can try the following script:
<?
if(mail("admin@yourwebsite.com", "Try to send email Using HTML Format", "<html><body><p>This is an email to test script send email using HTML Format</p><p>Thanks for your response.</p></body></html>","From: Djambrong <test@djambrong.com>\nMIME-Version: 1.0\nContent-type: text/html; charset=iso-8859-1")){
  echo "Email Sent";
}
else{
  echo "Failed to send email";
}
?>
At the script above we are adding "MIME-Version: 1.0\nContent-type: text/html; charset=iso-8859-1" to the header so, we can insert the HTML code into the message, because at the receiver side, the message we send will be read in HTML format. Thus tutorial we share about "Send Email Using PHP Script", I'll see you in the next tutorial.