Home >Backend Development >PHP Tutorial >Detailed explanation of how to send PHP emails

Detailed explanation of how to send PHP emails

php中世界最好的语言
php中世界最好的语言Original
2018-05-16 11:07:032332browse

This time I will bring you PHPEmail sendingdetailed explanation of usage, what are the notes for PHP email sending, the following is a practical case, let’s take a look.

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:

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

Register an account and obtain appid and appkey;

Apply 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. VariousProgramming languagesThere are many class libraries for sending emails. 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, view the mail sending queue. postqueue -p can replace the mailq command in sendmail, and postqueue -f refreshes the queue (forces an attempt to send mail in the queue).

postcat, view 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, and postcat -b -q xxxxx can only view the body of the email.

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

The above introduction is basically sufficient 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 port 25 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 impossible to send emails with 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. The mail 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.

Simply put, to make PHP's built-in mail function work properly, you need to do the following:

Apply for a domain name, set MX records in DNS resolution, and point to the local machine (non-legal host) (Emails sent by FQDN, Fully Qualified Domain Name) will be discarded directly as spam);

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

Configure firewalls, security groups, and release ports .

Low sending efficiency, non-object-oriented calling method, troublesome configuration and blockade by cloud server manufacturers are the biggest obstacles to using the mail function. So since I started working in PHP, I have never used the mail function directly.

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);

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

PHP+MySQL实现消息队列步骤详解

ES6使用技巧总结

The above is the detailed content of Detailed explanation of how to send PHP 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