Practical-10
Write a PHP program to send Mail from PHP Script.
Introduction
Sending mail from a PHP script is a useful way to inform users on a website about any notifications or other information. Through mail, it is possible to convey any type of information to the users in a very efficient and fast way. In this article, we will look at how to send mail from a PHP script. We will cover topics like setting up a mail server, using SMTP to send mail from a PHP script, how to attach files to a mail, and more.
Previous knowledge of HTML and PHP is recommended to understand this article. Additionally, while setting up and running a mail server is out of scope of this article, having some knowledge in that area can prove to be useful.
Code
<?php
$to = 'recipient@example.com';
$subject = 'Test Mail from PHP Script';
$body = 'This is a test mail sent from a PHP script';
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'From: Your Name <sender@example.com>' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// send the email
mail($to, $subject, $body, $headers);
?>
Output
None
The above code demonstrates the basic use of mail() function in PHP to send an email from a PHP script. The mail() function requires 4 parameters which are the recipient address, subject, body of the email and header of the email. Lastly, we send the mail with mail() function after setting the parameters.
Related Links
- PHP official documentation of
mail() - Preparing Your Server to Send Email
- How To Send Email From localhost in PHP
- Setting up a Mail Server with Postfix and Dovecot
- Sending HTML mail in PHP