search
HomeBackend DevelopmentPHP TutorialDetailed explanation of knowledge points for sending emails with PHP

Detailed explanation of knowledge points for sending emails with PHP

May 07, 2018 am 09:49 AM
phpExampleKnowledge points

This article summarizes the relevant knowledge points and detailed usage codes for sending emails in PHP. Friends in need can learn from it.

Sending emails is a common function of websites. Scenarios such as user activation and password retrieval often require sending emails to user mailboxes. This article first reviews the related concepts of sending emails, and then gives sample code for sending emails using PHP.

Send SMS

Functionally, SMS is similar to email, and is often used for notifications and security verification. Sending text messages (basically) requires paying the provider, so SMS providers have an incentive to provide clear documentation and easy-to-use interfaces for users to access. Generally speaking, those who send text messages are:

Look for suppliers, such as Alibaba Big Fish, aggregated data, etc.;

Register an account and obtain appid and appkey;

Apply for template;

View the interface document and integrate it into the application;

Call the API to send text messages.

The process is simple and easy to understand, and it is also very convenient to access and use. Basically, it can be connected and tested within an hour or two. Users do not need to consider details such as encoding and addressing of messages during the communication process. The disadvantage is that they have to pay.

E-mail is generally a free service, but related support is not that in place, which should also be understood. There are many class libraries for sending emails in various programming languages. From the perspective of the source, they can be basically divided into two categories: sending from the local machine and sending from a third-party email service provider. In order to understand the process of sending emails, let’s first introduce some related concepts.

Related concepts

Most people who are exposed to the Internet have experience in using email, but it is basically limited to email clients, web pages and providers. concept. As a developer, understanding the following concepts in this section will better help you master the details of email communication.

MUA: Mail User Agent, mail user agent. User agent is a word often encountered in development. It mainly refers to a tool that understands human intentions and requests resources from the user on behalf of the user. For example, the browser is the most commonly used user agent. It sends a request to the web server in the HTTP/HTTPS protocol format, parses the response, renders it and presents it to the user. Email user agents are commonly tools such as Foxmail and Outlook. After people write emails, they encapsulate the email content according to the format and communicate with the mail server.

MTA: Mail Transfer Agent, a program that helps users send and receive mail. The often mentioned mail server refers to the MTA. Open source programs include sendmail, postfix, QMail, etc.

MRA: Mail Retrieval Agent, the mail collection agent, retrieves the user's mail from the mail server locally. Mail clients are common MRAs.

SMTP: Simple Mail Transfer Protocol, Simple Mail Transfer Protocol. Users, mail servers, and mail servers all use this protocol to transmit mail to each other (default is plain text, and SSL\TLS encryption can be used).

POP3/IMAP: Post Office Protocol version 3/Internet Message Access Protocol, Post Office Protocol version 3 or Network Information Acquisition Protocol, the protocol used by the client to obtain mail from the server.

User A (163 mailbox) sends a letter to user B (Gmail mailbox). The process of user B getting the letter involves the above concepts. The process and conceptual relationship can be represented by the following simplified diagram:

用户A --发送邮件--> 用户B
 M|S         M|I
 U|M         R|M
 A|T         A|A
 |P         |P
 v          v
MTA(163)--转发(SMTP)->MTA(gmail)

Note: The above figure shows the general process of sending emails. Other MSA, MDA, ESMTP, SMTPS, etc. may appear in the entire process, but they are not Affects understanding of sending and receiving emails. The abbreviations and concepts mentioned below will be noted. For others, please check by yourself.

postfix

The software for sending emails under Linux is mainly sendmail and postfix. They act as the MTA/MDA (Mail Delivery Agent, Mail Delivery Agent) in the above concept in the system. Delivery Agent) role. It helps users send outbound emails and receive emails delivered to the user's mailbox (default location /var/spool/mail/username).

sendmail is a long-established email software with a very high reputation. But Wietse (Wietse Zweitze Venema) was not happy with it, so he came up with postfix. The postfix command is (almost) compatible with sendmail, but more efficient and secure (the origin of the suffix fix). It is currently the default email sending and receiving software for most Linux distributions. It is recommended to use postfix instead of sendmail (there was an article on this blog many years ago about how Configuring sendmail, I was young and ignorant at that time, so I planned to take the time to revise that article).

The main configuration file of postfix is ​​/etc/postfix/main.cf. The configuration file is very well commented and the options are basically self-explanatory. The most important configurations are: myhostname, myorigin, inet_interfaces, inet_protocols and mydestination (if you plan to receive letters from the external network). It should be noted that when inet_interfaces is configured as localhost, the value of inet_protocols should be ipv4, otherwise an error message similar to postfix: fatal: parameter inet_interfaces: no local interface found for ::1 may appear.

Several common postfix commands related to mail are:

mail or mailx, to send mail. The tlanyan user sends an email to root: mail -s "Greetings" root@localhost -r tlanyan@localhost, then enter A nice day! in the terminal, then press Enter, press ctrl D to end text editing, and the email has been sent. Log in to the root account and you will be prompted that there are new emails in /var/spool/mail/root. Use tail or other commands to view detailed information of the email.

postquque,查看邮件发送队列。postqueue -p可取代sendmail中的mailq命令,postqueue -f刷新队列(强制尝试发送队列中的邮件)。

postcat,查看未发送邮件的信息。例如postcat -q xxxx(xxxx是postqueue或者mailq显示的未发送队列ID)可查看邮件的详细信息,postcat -b -q xxxxx只查看邮件正文。

postsuper,超级用户才可使用的邮件管理程序。postsuper -d xxxx,删除队列ID为xxxxx的邮件;postsuper -h xxxxx,暂停队列ID为xxxx的邮件发送,等。

以上介绍对于发送邮件基本已足够。注意,mail命令发送的邮件能投递的前提是postfix正在运行(ps aux | grep postfix | grep -v grep输出不为空)。

有了postfix,配置好后可以对外发送邮件,也能收取外网发送过来的邮件,但限于命令行操作。想用foxmail等客户端收发邮件,需要让服务器支持POP3/IMAP协议。开源的dovecot可以实现这个功能。dovecot服务于收邮件而非发送,了解其对开发中的帮助不大。如果想搭建一套完整的邮件系统(包括网页端支持、垃圾邮件过滤、病毒查杀、传输加密等),建议参考或使用国产开源的 EwoMail。

了解postfix对开发中发送邮件帮助有多大?说实话,几乎没有帮助。原因是为了防止垃圾邮件泛滥,各大云服务器厂商屏蔽了25端口(Google Cloud连465都干掉了)。亚马逊云通过申请还有放行的可能(但有速率和每日额度限制),其他厂商几乎不会让你使用自己的域名从本机直接发送邮件。封禁25端口,必须使用第三方的邮件服务,几乎是业界的标准做法。

聪明的人可能想到,使用465加密端口(基于SMTPS,SMTP over SSL协议)或587端口(SMTP over STARTTLS协议)发送邮件,是不是就能绕开限制了?阿里云/腾讯云等厂商并不封禁465端口,发送邮件可以使用该端口而无需申请。但注意465和587端口是客户端和邮件服务器通讯使用的端口,邮件服务器之间通讯使用25端口。你可以通过465端口连接到Gmail邮箱对外发送邮件,但无法让postfix使用465端口投递邮件到hotmail邮件服务器。

总结来说,sendmail/postfix作为垃圾和欺诈邮件泛滥前的邮件服务器软件,对业界贡献很大。随着云服务器的盛行,几乎无法以指向本机的域名向外发送邮件,sendmail/postfix除了在本机内发送提醒邮件,用处已然不大。要对外发送邮件,要么自建机房,要么使用第三方邮件系统。

PHP的mail函数

作为PHP开发中,了解sendmail/postfix还是有点用处。mail函数默认使用sendmail/postfix发送邮件,了解相关配置,就能知道为啥能工作/为啥不能工作。

简单来说,要让PHP自带的mail函数正常工作,需要做以下事情:

申请域名,在DNS解析中设置MX记录,指向本机(非合法主机(FQDN, Fully Qualified Domain Name)发送的邮件都会被当做垃圾邮件直接丢弃);

安装sendmail/postfix,配置软件并运行;

配置防火墙、安全组,放行端口。

发送效率低、非面向对象的调用方式,配置麻烦以及云服务器厂商的封锁,是使用mail函数的最大阻碍。所以做PHP以来,本人并未直接用过mail函数。

PHP发送邮件

发个邮件要了解这么多,会让人觉得很心累。说好的PHP是最好的语言呢?

PHP发送邮件也可以很简单,推荐方式就是使用Swift Mailer或PHPMailer等类库。引入这些类库后,注册第三方邮箱(比如Gmail、QQ等),填好用户名密码,配置好STMP地址和端口,就能像发送短信一样轻松发送邮件。当然这些类库也支持使用sendmail/postfix发送邮件,但我想你不会再这样做了。

以Swift Mailer为例,直接上代码说明使用PHP发送邮件也是一个非常简单的事情!

首先,在项目中引入Swift Mailer:

composer require "swiftmailer/swiftmailer:^6.0"

然后准备好邮件内容(以文本文件为例,不带附件):

$message = (new Swift_Message('Test Message'))
  ->setFrom(['tlanyan@tlanyan.me' => 'tlanyan'])
  ->setTo(['tlanyan1@tlanyan.me'])
  ->setBody('Hello, this is a test mail from Swift Mailer!');

接着,设置好邮件传输方式(使用Gmail邮箱):

$transport = (new Swift_SmtpTransport('smtp.gmail.com', 465, 'ssl'))
  ->setUsername('username')
  ->setPassword('password');

或者使用sendmail/postfix的方式(不推荐):

$transport = (new Swift_SendmailTransport());

最后,使用transport构造mailer实例,发送邮件:

$mailer = new Swift_Mailer($transport);
$result = $mailer->send($message);

老板再也不用担心发送邮件收不到了,So easy!

总结

本文先回顾了发送邮件的相关概念,说明不推荐使用内置的mail函数原因,最后给出了使用第三方类库发送邮件的代码示例。

相关推荐:
几种PHP发送HTTP请求的方式分享

PHP Shares many practical PHP codes for sending text messages, emails, etc.



##

The above is the detailed content of Detailed explanation of knowledge points for sending emails with PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP: The Foundation of Many WebsitesPHP: The Foundation of Many WebsitesApr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

See all articles

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use