Two ways to send PHP emails
Many programmers will encounter several problems when using PHP to send emails. If they encounter problems, they must have ideas to solve them. This article is an article compiled based on the idea of implementing email sending in PHP. , interested friends can refer to the different solutions given when encountering different problems.
1. Use PHP’s built-in mail() function
<?php $to = "test@163.com"; //收件人 $subject = "Test"; //主题 $message = "This is a test mail!"; //正文 mail($to,$subject,$message);
The result will be an error directly, as follows:
Warning: mail() [function.mail]: Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() inD:/www/Zend/email/email.php on line 10
Analysis reason: A local SMTP server is needed, and the code is changed:
<?php $to = "test@163.com";//收件人 $subject = "Test";//邮件主题 $message = "This is a test mail!";//邮件正文 ini_set('SMTP','smtp.163.com');//发件SMTP服务器 ini_set('smtp_port',25);//发件SMTP服务器端口 ini_set('sendmail_from',"admin@163.com");//发件人邮箱 mail($to,$subject,$message);
The result is still wrong:
Warning: mail() [function.mail]: SMTP server response: 553 authentication is required,smtp2,DNGowKD7v5BTDo9NnplVBA--.1171S2 1301220947 inD:/www/Zend/email/email.php on line 9
Analysis reason: Verification information is needed. How to write verification information? Where to configure it? After referring to some technical articles with these questions, I came to the conclusion that using the mail() function to send emails requires a mail server that can send letters without SMTP authentication. But today's SMTP mail servers basically require authentication, so if you want to use it to send emails, you can only set up a local SMTP server that does not require authentication. How to set up: Just use the IIS that comes with Windows, or download other SMTP server software from the Internet.
Conclusion: To use the mail() function to send emails, you must have an SMTP server that does not require authentication. In this case, the configuration work will be a little more, but it will be easier to use, just a few lines of code.
2. Use the mail class that encapsulates the SMTP protocol
This method is relatively common, especially for the majority of students who do not have a server and purchase a virtual host online, the first method is unrealistic. , so it’s better to use the SMTP protocol to send emails yourself.
But to complete this work, you need to have a certain understanding of the SMTP protocol. Students who like to do everything by themselves can write one by themselves. Students who like to use it as a tool can download it from the Internet. There are many .
However, I recommend using the Mail class in the PEAR extension. It has powerful functions: it can support emails in plain text and HTML formats; encoding can be set for each field, and correct configuration will not cause Chinese garbled characters; it can support attachments. etc.
You can use pear install Mail on the server The command is quick to install. Students who do not have sufficient server permissions can also directly download the PHP source code of the class and include it.
Note: Mail class depends on Net/SMTP.php and Mail/mime.php , to be downloaded together and included together when using.
Let me give an example of how to send emails in the Mail class. The methods of using other SMTP mail classes on the Internet are similar. You can refer to:
<?php // Pear Mail 扩展 require_once('Mail.php'); require_once('Mail/mime.php'); require_once('Net/SMTP.php'); $smtpinfo = array(); $smtpinfo["host"] = "smtp.163.com";//SMTP服务器 $smtpinfo["port"] = "25"; //SMTP服务器端口 $smtpinfo["username"] = "username@163.com"; //发件人邮箱 $smtpinfo["password"] = "password";//发件人邮箱密码 $smtpinfo["timeout"] = 10;//网络超时时间,秒 $smtpinfo["auth"] = true;//登录验证 //$smtpinfo["debug"] = true;//调试模式 // 收件人列表 $mailAddr = array('receiver@163.com'); // 发件人显示信息 $from = "Name <username@163.com>"; // 收件人显示信息 $to = implode(',',$mailAddr); // 邮件标题 $subject = "这是一封测试邮件"; // 邮件正文 $content = "<h3>随便写点什么</h3>"; // 邮件正文类型,格式和编码 $contentType = "text/html; charset=utf-8"; //换行符号 Linux: \n Windows: \r\n $crlf = "\n"; $mime = new Mail_mime($crlf); $mime->setHTMLBody($content); $param['text_charset'] = 'utf-8'; $param['html_charset'] = 'utf-8'; $param['head_charset'] = 'utf-8'; $body = $mime->get($param); $headers = array(); $headers["From"] = $from; $headers["To"] = $to; $headers["Subject"] = $subject; $headers["Content-Type"] = $contentType; $headers = $mime->headers($headers); $smtp =& Mail::factory("smtp", $smtpinfo); $mail = $smtp->send($mailAddr, $headers, $body); $smtp->disconnect(); if (PEAR::isError($mail)) { //发送失败 echo 'Email sending failed: ' . $mail->getMessage()."\n"; } else{ //发送成功 echo "success!\n"; }
If the SMTP classes found on the Internet are all It is highly encapsulated, so it is simpler to use than the above, but the usage methods are relatively similar.
Conclusion: There is no need to install any software to send emails in this way. You only need to include a PHP class and write a few more lines of configuration code. And there are many sample codes on the Internet. In many cases, you only need to copy them and modify a few parameters to use them, so it is very convenient and it is recommended to use this method.
No matter what kind of problem you encounter, there are thousands of methods. The most important thing is to have an idea to solve the problem. I hope this article can bring inspiration to everyone.
Related recommendations:
Powerful PHP email sending class
PHP simple email sending class
The above is the detailed content of Two ways to send PHP emails. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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

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

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,

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

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

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 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.
