search
HomeBackend DevelopmentPHP TutorialDetailed explanation of how to send PHP emails

Detailed explanation of how to send PHP emails

May 16, 2018 am 11:07 AM
phpuseDetailed explanation

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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

Video Face Swap

Video Face Swap

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

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.