วิธีการส่งอีเมลโดยใช้ฟังก์ชั่น PHP mail()

⚡ สรุปอย่างชาญฉลาด

PHP mail is the built-in function that sends email directly from a PHP script using the server’s SMTP settings. This walkthrough covers the mail() syntax and parameters, configuring SMTP in php.ini, sanitizing user input with filter_var, sending secure mail, and using PHPMailer for reliable delivery.

  • 📧 What mail() Does: The mail() function sends an email from a script, taking the recipient, subject, message, and optional headers.
  • 📨 SMTP Transport: PHP mail relies on SMTP, whose host, port, and authentication are set in the php.ini configuration file.
  • 📋 CC and BCC: Optional headers add carbon copy and blind carbon copy recipients, with BCC hidden from the other recipients.
  • 🛡️ Sanitize Input: filter_var with FILTER_SANITIZE_EMAIL and FILTER_VALIDATE_EMAIL blocks header injection from contact form input.
  • 🔒 ปลอดภัย Mail: Encrypting the connection with SSL or TLS protects message contents from being read in transit.
  • 🧰 Use PHPMailเอ้อ: PHPMailer adds SMTP authentication, attachments, and HTML email, making it more reliable than raw mail().
  • 🤖 AI ช่วยเหลือ: AI tools can configure PHPMailer with SMTP and suggest fixes that keep your emails out of the spam folder.

PHP Mail

PHP mail คืออะไร?

PHP mail is the built-in PHP function that is used to send emails from PHP scripts.

ฟังก์ชันการส่งเมล์ยอมรับพารามิเตอร์ต่อไปนี้:

  • อีเมล
  • หัวข้อ
  • ระบุความประสงค์หรือข้อมูลเพิ่มเติม
  • CC or BCC email addresses

Why and When to use PHP mail

The mail function is useful in many situations:

  • It is a cost effective way of notifying users of important events.
  • ให้ผู้ใช้ติดต่อคุณผ่านอีเมล์โดยมีแบบฟอร์มติดต่อเราบนเว็บไซต์ที่ส่งเนื้อหาที่ให้มาทางอีเมล
  • Developers can use it to receive system errors by email.
  • คุณสามารถใช้มันเพื่อส่งอีเมล์ถึงสมาชิกรับจดหมายข่าวของคุณได้
  • You can use it to send password reset links to users who forget their passwords.
  • You can use it to email activation and confirmation links. This is useful when registering users and verifying their email addresses.

การส่งเมล์โดยใช้ PHP

The PHP mail function has the following basic syntax.

<?php
mail($to_email_address,$subject,$message,[$headers],[$parameters]);
?>

ที่นี่

  • “$to_email_address” คือที่อยู่อีเมลของผู้รับอีเมล
  • “$subject” คือหัวเรื่องอีเมล
  • “$message” คือข้อความที่จะส่ง
  • “[$headers]” is optional; it can be used to include information such as CC and BCC.
    • CC is the acronym for carbon copy. It is used when you want to send a copy to an interested person, i.e. a complaint email sent to a company can also be sent as CC to the complaints board.
    • BCC is the acronym for blind carbon copy. It is similar to CC, but the email addresses included in the BCC section are not shown to the other recipients.

ง่าย Mail Transmission โปรโตคอล (SMTP)

PHP mail uses the Simple Mail Transmission โปรโตคอล (SMTP) ในการส่งอีเมล

On a hosted server, the SMTP settings would already have been set.

The SMTP mail settings can be configured from the “php.ini” file in the PHP installation folder.

To configure SMTP settings on your localhost, assuming you are using XAMPP on Windows, locate the “php.ini” file in the directory “C:\xampp\php”.

  • Open it using Notepad or any text editor. We will use Notepad in this example. Click on the Edit menu.

ง่าย Mail Transmission โปรโตคอล

  • Click on the Find… menu

ง่าย Mail Transmission โปรโตคอล

  • The Find dialog will appear

ง่าย Mail Transmission โปรโตคอล

  • Click on the Find Next button

ง่าย Mail Transmission โปรโตคอล

Locate the entries under [mail function]. The default lines usually look like this:

  • - SMTP = โลคัลโฮสต์
  • - smtp_พอร์ต = 25

Remove the semicolons before SMTP and smtp_port, and set SMTP to your เซิร์ฟเวอร์ and the port to your SMTP port. Your settings should look as follows:

  • SMTP = smtp.example.com
  • smtp_พอร์ต = 25

Note: the SMTP settings can be obtained from your web hosting provider. If the server requires authentication, then add the following lines:

  • auth_username = example_username@example.com
  • auth_password = example_password

Save the new changes and restart the อาปาเช่ เซิร์ฟเวอร์

PHP Mail ตัวอย่าง

Let us now look at an example that sends a simple mail.

<?php
$to_email = 'name@example.com';
$subject = 'Testing PHP Mail';
$message = 'This mail is sent using the PHP mail function';
$headers = 'From: noreply@example.com';
mail($to_email,$subject,$message,$headers);
?>

Output:

ง่าย Mail Transmission โปรโตคอล

Note: the above example only takes the 4 mandatory parameters. You should replace the above fictitious email address with a real email address.

การฆ่าเชื้อข้อมูลอินพุตของผู้ใช้อีเมล์

ตัวอย่างข้างต้นใช้ค่าที่เข้ารหัสแบบตายตัวในโค้ดต้นฉบับสำหรับที่อยู่อีเมลและรายละเอียดอื่น ๆ เพื่อความเรียบง่าย

Let us assume you have to create a contact us form where users fill in the details and then submit.

  • Users can accidentally or intentionally inject code in the headers, which can result in sending spam mail.
  • เพื่อปกป้องระบบของคุณจากการโจมตีดังกล่าว คุณสามารถสร้างฟังก์ชันแบบกำหนดเองที่ทำการทำความสะอาดและตรวจสอบค่าต่างๆ ก่อนที่จะส่งอีเมล

Let us create a custom function that validates and sanitizes the email address using the filter_var built-in function. The filter_var function is used to sanitize and validate user input data.

มีโครงสร้างพื้นฐานดังต่อไปนี้

<?php
filter_var($field, SANITIZATION_TYPE);
?>

ที่นี่

  • “filter_var(…)” คือฟังก์ชันการตรวจสอบและฆ่าเชื้อ
  • “$field” คือค่าของฟิลด์ที่จะกรอง
  • “SANITIZATION_TYPE” is the type of sanitization to be performed on the field, such as:
    • ตัวกรอง_ตรวจสอบอีเมล – returns true for valid email addresses and false for invalid email addresses.
    • อีเมลกรองสุขอนามัย – removes illegal characters from email addresses, so an address with stray characters is reduced to info@domain.com.
    • กรอง_ฆ่าเชื้อ_URL – removes illegal characters from URLs, leaving a clean address such as https://www.example.com.
    • FILTER_SANITIZE_STRING – removes tags from string values, so <b>am bold</b> becomes am bold. Note this filter is deprecated in PHP 8.1; use htmlspecialchars() instead.

The code below uses a custom function to send secure mail.

<?php
function sanitize_my_email($field) {
$field = filter_var($field, FILTER_SANITIZE_EMAIL);
if (filter_var($field, FILTER_VALIDATE_EMAIL)) {
return true;
} else {
return false;
}
}
$to_email = 'name@example.com';
$subject = 'Testing PHP Mail';
$message = 'This mail is sent using the PHP mail function';
$headers = 'From: noreply@example.com';
// check if the email address is invalid
$secure_check = sanitize_my_email($to_email);
if ($secure_check == false) {
echo "Invalid input";
} else { // send email
mail($to_email, $subject, $message, $headers);
echo "This email is sent using PHP Mail";
}
?>

Output:

การฆ่าเชื้อข้อมูลอินพุตของผู้ใช้อีเมล์

ปลอดภัย Mail

อีเมลอาจถูกดักจับระหว่างการส่งโดยผู้รับที่ไม่ได้ตั้งใจ

This can expose the contents of the email to unintended recipients.

อีเมลที่ปลอดภัยช่วยแก้ปัญหานี้ได้โดย transmitting emails over an encrypted connection using SSL or TLS, for example SMTP over SSL on port 465 or STARTTLS on port 587.

Encryption scrambles the message before sending it, so only the intended recipient’s mail server can read it.

PHPMailer: A Better Alternative to mail()

For real applications, most developers use the PHPMailer library instead of the raw mail() function. PHPMailer authenticates with an external SMTP server, which greatly improves deliverability, and it makes attachments and HTML email simple.

Install it with Composer, then send mail through an authenticated, encrypted SMTP connection as shown below.

<?php
use PHPMailer\PHPMailer\PHPMailer;
require 'vendor/autoload.php';

$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'user@example.com';
$mail->Password = 'secret';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

$mail->setFrom('noreply@example.com', 'My App');
$mail->addAddress('name@example.com');
$mail->Subject = 'Testing PHPMailer';
$mail->Body = 'This email is sent using PHPMailer over SMTP';
$mail->send();
?>

Compared with mail(), PHPMailer gives you SMTP authentication, built-in encryption, attachment support, and clearer error handling, which is why it is the recommended choice for production email.

คำถามที่พบบ่อย

The most common cause is no configured mail server on localhost. Set correct SMTP values in php.ini, or use PHPMailer with an authenticated SMTP account. Also check the server error log and your spam folder.

Add headers that set MIME-Version to 1.0 and Content-Type to text/html, then put HTML markup in the message body. PHPMailer handles this automatically when you set its isHTML(true) option.

FILTER_SANITIZE_STRING is deprecated since PHP 8.1. Use htmlspecialchars() to escape output for display, or a specific validator such as FILTER_VALIDATE_EMAIL, depending on whether you are cleaning or checking the value.

Yes. Give AI your SMTP host, port, and security type, and it can generate the full PHPMailer setup with authentication, a sender, recipients, and error handling. Store credentials in environment variables, not code.

Yes. AI can advise on SPF, DKIM, and DMARC records, using an authenticated SMTP sender, avoiding spam trigger words, and setting a valid From address, then help you test deliverability.

สรุปโพสต์นี้ด้วย: