Home Backend Development PHP Tutorial Detailed explanation of usage examples of php mail() function to send emails

Detailed explanation of usage examples of php mail() function to send emails

Jun 27, 2017 am 10:24 AM
mail php e-mail

1. Introduction
Mail() function, you can use this function to send emails.
Requirements
In order to use the Mail function, PHP must have the ability to compile and send binary mail files in your system. If you use other mail programs, such as qmail or postfix, you must be confident that you can use them to send mail packages. PHP will first look for sendmail on your path, so the following paths: :/usr/bin :/usr/sbin :/usr/etc :/etc:/usr/ucblib :/usr/lib are recommended. Users who compile PHP must also have access to binary sendmail.
Installation
These functions are part of the PHP core and can be used without being installed.
Runtime Configuration
The behavior of these functions is affected by the global Configuration file php.ini.
Table 1. Mail basic configuration options:

Name Default value Changeable value

SMTP "localhost" PHP_INI_ALL

smtp_port "25" PHP_INI_ALL

sendmail_from NULL PHP_INI_ALL

sendmail_path DEFAULT_SENDMAIL_PATH PHP_INI_SYSTEM

For more configuration options about Mail, please see the ini_set() function. The following is a brief explanation of this configuration option.
SMTP string
Used in Windows only: DNS name or IP address of the SMTP server. PHP will use the SMTP server when sending emails using the mail() function.
smtp_portint
Used in Windows only: Set the port number to connect to the specified SMTP server when sending mail using the mail() function. Default: 25. Only available after PHP 4.3.0.
sendmail_from string
When PHP sends emails in Windows systems, it will use the "From:" email address.
sendmail_path string
Where to find the sending mail program. Usually in: /usr/sbin/sendmail or /usr/lib/. The configuration options here are set to a default value so that they work properly for you. But if it fails, you can set it here.
If your system cannot use sendmail, you should follow these instructions to set up a sendmail wrapper/replacement for the mail system they provide. For example, Qmail users can set it to a new path: /var/qmail/bin/sendmail or /var/qmail/bin/qmail-inject.
 qmail - handles mail correctly without any options.
Resource Type
This extension module does not define any resource type.
Predefined constants
This extension module does not define any constants

2. Usage method
Syntax:  

bool mail ( string to, string subject, string message [, string additional_headers [, string additional_parameters]])   
Copy after login

mail() The function can send the specified message (string message) to the specified email address (string to). Multiple email addresses must be separated by commas. You can use this function to send email attachments and special types.
The meaning of each parameter in the above syntax is:
string to——the email address of the recipient,
string subject——the subject of the email,
string message——the email Text,
string additional_headers - add additional email information to the head and tail of the letter.
If the email is successfully sent, the mail() function will return TRUE, otherwise it will return FALSE. Notice!

The execution method of the mail() function in Windows is different from UNIX systems in many ways.​
​ 1. It does not use local binary to form the message body; ​
​ 2. Headers elements like From:, Cc:, Bcc: and Date: are not interpreted by MTA at first, but can be interpreted by PHP. PHP < 4.3 only supports Cc: and is case-sensitive, PHP >= 4.3 supports all mentioned header elements and is not case-sensitive.
 2.1. Example 1. Send an email:

mail("joecool@example.com", "My Subject", "Line 1nLine 2nLine 3");
Copy after login

 2.2. If the fourth parameter is used, this parameter string will be inserted into the header and tail of the letter. This is typically inserted to illustrate additional header information. Multiple additional header information must be separated by carriage return r and line feed n characters.
 Example 2. Send an email with additional header information:

mail("nobody@example.com", "the subject", $message,"From: webmaster@{$_SERVER[’SERVER_NAME’]}rn"    
."Reply-T webmaster@{$_SERVER[’SERVER_NAME’]}rn"."X-Mailer: PHP/" .phpversion());
Copy after login

2.3. If the additional_parameters parameter is used, the program uses the sendmail_path configuration to set an additional parameter when sending the email. For example, this can be used to set the sender's address envelope when using the -f option before mailing. When you set up the sender envelope using this method, you may need to add the user that your web server runs as to your sendmail configuration to prevent a 'X-Warning' header from being added to the message when you set the envelope sender using this method.
Example 3. Sending an email with additional header information and appending a command parameter.

mail("nobody@example.com", "the subject", $message,"From: webmaster@{$_SERVER[’SERVER_NAME’]}",      
 "-fwebmaster@{$_SERVER[’SERVER_NAME’]}");
Copy after login

  注意:其中的第五个参数附加在PHP 4.0.5版本中。在PHP 4.2.3以后的版本中的安全模式中被禁止,如果用它的话将返回一个警告信息和返回FALSE值。   
  你同样能用简单的字符串构造技术建立一个复杂的邮件消息。
例子 4. 发送一个复杂邮件

/*收件人*/
$to = "Mary " . ", " ; //注意逗号
$to .= "Kelly ";
 /*主题*/
$subject = "Birthday Reminders for August";
/*正文*/
$message = ’         
Here are the birthdays upcoming in August!
’;
 /*你能设置头内容:Content-type来发送HTML格式邮件。*/
 $headers = "MIME-Version: 1.0rn";
$headers .= "Content-type: text/html; charset=iso-8859-1rn";
 /*附加头消息*/
$headers .= "From: Birthday Reminder rn";
$headers .= "Cc: birthdayarchive@example.comrn";
$headers .= "Bcc: birthdaycheck@example.comrn";
/*发送它*/
mail($to, $subject, $message, $headers);
@example.com>@example.com>@example.com>
Copy after login

注意:
  1、不要在收件人地址和主题中有换行符号,否则邮件可能不能被发送出去。
  2、收件人地址参数(string to)中不能存在以"Something "形式地址,否则当用MTA时mail命令可能不被正确的分析。
  3、PHP使用mail函数发送邮件标题乱码问题 PHP程序使用mail()函数发送邮件的时候,标题中文的话会出现乱码。
解决方法:
  先用函数base64_encode() — 使用 MIME base64 对数据进行编码 标题字符串前加编码类型例如: =?UTF-8?B? 标题字符串后加:?= 邮件header说明Content-type — 防止邮件正文也乱码
举例:

$to  = &#39;xinple@example.com&#39;;
$subject  = "=?UTF-8?B?".base64_encode(&#39;邮件标题&#39;)."?=";
$headers  = &#39;MIME-Version: 1.0&#39; . "rn";
$headers .= &#39;Content-type: text/html; charset=utf-8&#39; . "rn";
// Additional headers
$headers .= &#39;To: Xinple&#39; . "rn";
$headers .= &#39;From: Admin &#39; . "rn";
$headers .= &#39;Reply-To: Xinple&#39; . "rn";
mail($to, $subject, $message, $headers);@example>@example.com>@example.com
Copy after login

The above is the detailed content of Detailed explanation of usage examples of php mail() function to send emails. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles