Home > Backend Development > PHP Tutorial > Detailed explanation of knowledge points for sending emails with PHP

Detailed explanation of knowledge points for sending emails with PHP

不言
Release: 2023-03-25 12:56:02
Original
1822 people have browsed it

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)
Copy after login

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"
Copy after login

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

$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!');
Copy after login

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

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

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

$transport = (new Swift_SendmailTransport());
Copy after login

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

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

老板再也不用担心发送邮件收不到了,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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template