1. PHP Mailer Contact Form (PHPMailer)
PHP Mailer Script Explanation
-
PHPMailer Setup: You're using PHPMailer to send an email via SMTP (Gmail in this case).
-
Input Processing: The form values are collected
$_POST
and passed to PHPMailer for sending. -
Success/Error Handling: The email sending result is displayed via the
$result
or$error
message.
HTML Contact Form
-
Form Fields: Users enter their name, email, subject, and message.
-
Result/Error Message: The result of the form submission (success or error) is displayed at the top of the form.
2. Using PHP mail()
Function (Alternative to PHPMailer)
The mail()
function in PHP is another way to send emails. Below is a simple example of how you can send an email using mail()
.
Basic mail()
Syntax:
This basic script will send a plain text email. You can also add more headers, like CC, BCC, and MIME types for HTML emails.
Example with CC, BCC:
3. Sanitizing User Inputs
It's essential to sanitize user inputs to prevent email injection attacks. Here’s an example of sanitizing and validating email input:
4. Using Secure Mail with PHPMailer
For better security, especially for sending sensitive information, PHPMailer can be used with encryption (SSL/TLS) to securely send emails. This approach prevents the email contents from being intercepted during transmission.
Conclusion
-
PHP
mail()
Function: It is Simple to use for sending emails but lacks advanced features like HTML support, SMTP, and error handling. -
PHPMailer: A more robust solution for sending emails, especially with features like SMTP, HTML emails, and error handling.
-
Sanitizing Inputs: Always sanitize user inputs (especially email) to prevent security issues.