PHP is a scripting language widely used to develop web applications. It provides many functions for handling email sending. This article will introduce you to how to use the email sending function in PHP and provide specific code examples.
Before using PHP to send emails, you first need to ensure that your server has been configured to send emails. Generally speaking, you need an SMTP server to send emails. You can use the SMTP server provided by your email provider. For example, Gmail's SMTP server address is: smtp.gmail.com.
Next, you need a valid email account and password for verification. Make sure your account is not set to restrict sending emails.
Before you start sending an email, you need to set various information of the email, including recipients, subject, content, etc. The following is a simple sample code for setting email information:
$to = "recipient@example.com"; $subject = "这是邮件的主题"; $message = "这是邮件的内容"; $headers = "From: sender@example.com ";
After having the email information, we can use mail()## in PHP #Function to send email. The following is a complete sample code for sending an email:
$to = "recipient@example.com"; $subject = "这是邮件的主题"; $message = "这是邮件的内容"; $headers = "From: sender@example.com "; if (mail($to, $subject, $message, $headers)) { echo "邮件发送成功!"; } else { echo "邮件发送失败!"; }
mail() parameters to add attachments. The following is a sample code for sending emails containing attachments:
$to = "recipient@example.com"; $subject = "这是邮件的主题"; $message = "这是邮件的内容"; $headers = "From: sender@example.com "; $attachment = chunk_split(base64_encode(file_get_contents("path/to/file.pdf"))); $headers .= "MIME-Version: 1.0 "; $headers .= "Content-Type: multipart/mixed; boundary="boundary" "; $headers .= "--boundary "; $headers .= "Content-Type: application/pdf; name="file.pdf" "; $headers .= "Content-Transfer-Encoding: base64 "; $headers .= "Content-Disposition: attachment; filename="file.pdf" "; $headers .= $attachment . " "; if (mail($to, $subject, $message, $headers)) { echo "邮件发送成功!"; } else { echo "邮件发送失败!"; }
The above is the detailed content of PHP Mail Usage Guide: Simple and easy-to-understand tutorial for sending emails. For more information, please follow other related articles on the PHP Chinese website!