Home  >  Article  >  Backend Development  >  PHP review: sending emails

PHP review: sending emails

不言
不言Original
2018-04-16 14:42:511607browse

This article mainly introduces PHP review of sending emails. It has certain reference value. Now I share it with everyone. Friends in need can refer to it.

Please indicate the source of the article when reprinting: https:// tlanyan.me/php-review...

PHP review series directory

  • PHP basics

  • web request

  • cookie

  • web response

  • session

  • ## Database operations

  • Encryption and decryption

  • Composer

  • Create your own Composer package

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:

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

  2. Register an account and obtain appid and appkey;

  3. Application template;

  4. View the interface document and integrate it into the application;

  5. Call API to send text messages.

The process is simple and easy to understand, and it is also very convenient to access and use. You can basically connect and test it 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 they are basically limited to the concepts of email client, web page and provider. 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 that is often encountered in development. It mainly refers to a tool that understands people's intentions and requests resources from the resource side 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 to the local. 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 transfer mail to each other (default is plain text, and SSLTLS 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 used to send emails under Linux is mainly sendmail and postfix, which play the role of MTA/MDA (Mail Delivery Agent, Mail Delivery Agent) in the system as mentioned above. 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 fully commented and the options are basically self-explanatory. The most important configurations are: myhostname, myorigin, inet_interfaces, inet_protocols, and mydestination (if you If you plan to receive letters from external networks). It should be noted that when inet_interfaces is configured as localhost, the value of inet_protocols should be ipv4, otherwise something like postfix: fatal: parameter inet_interfaces: no local may appear. interface found for ::1 error message.

Several common postfix commands related to mail are:

  1. mail or mailx, to send mail. tlanyanThe 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 the detailed information of the email.

  2. postquque, check the mail sending queue. postqueue -p can replace the mailq command in sendmail, postqueue -f refreshes the queue (forces an attempt to send mail in the queue).

  3. postcat, check the information of unsent emails. For example, postcat -q xxxx (xxxx is the unsent queue ID displayed by postqueue or mailq) can view the detailed information of the email, postcat -b -q xxxxx can only view the text of the email.

  4. postsuper, a mail management program that can only be used by super users. postsuper -d xxxx, delete the emails with queue ID xxxxx; postsuper -h xxxxx, pause the sending of emails with queue ID xxxx, etc.

The above introduction is basically enough for sending emails. Note that the mail sent by the mail command can be delivered only if postfix is running (ps aux | grep postfix | grep -v grep output is not empty).

With postfix, after configuration, you can send emails to the outside world and receive emails from the external network, but it is limited to command line operations. If you want to use clients such as foxmail to send and receive emails, you need to make the server support the POP3/IMAP protocol. The open source dovecot can achieve this function. Dovecot serves to receive emails rather than send them. Understanding it is of little help in development. If you want to build a complete email system (including web page support, spam filtering, virus detection, transmission encryption, etc.), it is recommended to refer to or use the domestic open source EwoMail.

How helpful is understanding postfix for sending emails during development? To be honest, little help. The reason is that in order to prevent the proliferation of spam, major cloud server manufacturers have blocked port 25 (Google Cloud has even blocked port 465). It is possible for Amazon Cloud to be released through application (but there are rate and daily quota limits), and other vendors will almost never let you use your own domain name to send emails directly from this machine. It is almost a standard practice in the industry to block port 25 and use a third-party email service.

Smart people may think that using encrypted port 465 (based on SMTPS, SMTP over SSL protocol) or port 587 (SMTP over STARTTLS protocol) to send emails can circumvent restrictions? Alibaba Cloud/Tencent Cloud and other manufacturers do not block port 465. You can use this port to send emails without applying. But note that ports 465 and 587 are the ports used for communication between the client and the mail server, and 25 port is used for communication between mail servers. You can connect to the Gmail mailbox through port 465 to send emails externally, but you cannot let postfix use port 465 to deliver emails to the hotmail mail server.

In summary, sendmail/postfix, as the mail server software before the proliferation of spam and fraudulent emails, has made a great contribution to the industry. With the popularity of cloud servers, it is almost unable to send out emails using domain names pointing to the local machine. Sendmail/postfix is ​​of little use except for sending reminder emails within the local machine. To send emails externally, you must either build your own computer room or use a third-party email system.

PHP’s mail function

As a PHP developer, it is still useful to understand sendmail/postfix.

mailThe function uses sendmail/postfix to send emails by default. If you understand the relevant configuration, you will know why it can work/why it cannot work.

PHP review: sending emails

Simply put, to make PHP’s own mail function work properly, you need to do the following:

  1. Apply for a domain name, set MX records in DNS resolution, and emails sent to this machine (non-legal hosts (FQDN, Fully Qualified Domain Name) will be directly discarded as spam);

  2. Install sendmail/postfix, configure the software and run it;

  3. Configure firewall, security group, and release ports.

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

PHP发送邮件

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

PHP发送邮件也可以很简单,推荐方式就是使用Swift MailerPHPMailer等类库。引入这些类库后,注册第三方邮箱(比如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函数原因,最后给出了使用第三方类库发送邮件的代码示例。

感谢阅读,欢迎评论指正!

参考

  1. http://cn.linux.vbird.org/lin...

  2. http://doc.ewomail.com/ewomai...

  3. http://php.net/manual/en/func...

  4. https://swiftmailer.symfony.com

相关推荐;

怎样选择适合自己php框架

php中传值与传引用的区别

The above is the detailed content of PHP review: sending emails. 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