使用PHP通过SMTP发送邮件新手指南_PHP
SMTP
由于PHP没有提供现成的smtp函数,却提供了一个功能不甚灵活的mail()函数,这个函数需要服务器配置上的支持,并且不支持smtp验证,在很多场合无法正常的工作,因此不建议使用。本文的目的在于为新手指明方向,并没有涉及那些高级的内容,一来本身水平有限,二来也担心不能准确的讲述相关的概念,进而对各位造成误导,还请自行深入学习。“使用php发送mail”最近已经成为继“register_globals”以后本版第二个新手陷阱,今天特地写这篇文章为新手解惑,希望可以为迷茫的人指明方向。
让我们先从以下这个例子开始说起:
引用:
[root@server~/]# telnet localhost 25
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
220 server.domain.com.br ESMTP Postfix (2.1.0)
MAIL FROM: teste@dominio.com.br
250 Ok
RCPT TO: teste@dominio.com.br
250 Ok
DATA
354 End data with <CR><LF>.<CR><LF>
teste
.
250 Ok: queued as 7B41F4665A
QUIT
221 Bye
Connection closed by foreign host.
注:以上来自netkiller的postfix文档,偷懒,直接用现成的。
首先是使用telnet来连接本地的25端口,稍微熟悉点网络的人都知道smtp协议使用25端口,这也就是说,现在在连接本地的smtp服务器。
引用:
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
220 server.domain.com.br ESMTP Postfix (2.1.0)
这些东西是系统输出信息,说明已经连接上了,而且这个smtp服务器是postfix做的。
“MAIL FROM: teste@dominio.com.br”这个命令指明了发件地址是teste@dominio.com.br,“250 Ok”说明这条命令被服务器接受并正确执行,这类似http协议的200、404、500等状态代码。接下来的“RCPT TO: teste@dominio.com.br”指明了收件地址是teste@dominio.com.br。
引用:
DATA
354 End data with <CR><LF>.<CR><LF>
teste
.
这一段是输入邮件正文,输入“DATA”以后系统提示使用“<回车>.<回车>”来结束输入,正文内容是“teste”。
最后使用“QUIT”退出。
以上就是最简单的一次发送mail的过程,从这个例子我们可以看出,发送mail其实是很简单的事情,实质上也就是建立一个对smtp服务器的连接,然后发送一些简单的命令给它,一封内容简单的邮件就发送出去了,至于更加复杂内容的邮件或者操作,其实也就是在此基础上稍加扩展而已。
把这个过程用php来实现,其实就是利用php的Socket functions、Network Functions等等操作socket的函数来和smtp服务器建立一个连接,然后发送文本的命令给服务器,如果你亲自去看看那些写好的利用smtp协议发送邮件的类或者函数,相信可以印证我的说法。
由于已经存在很多现成的封装得很好的类或者函数替我们完成底层的socket级操作,我们只需要直接拿来用就好,而我也不会费时费神的在本文里去讨论底层的代码,有精神去研究的话,自己找代码来研究吧。现在继续跟我走,我们来点实际的代码来说明如何使用php发送邮件,采用的类是PEAR::Mail。
代码:
<?php
require_once 'Mail.php';
$conf['mail'] = array(
'host' => 'xx.xx.xx.xx', //smtp服务器地址,可以用ip地址或者域名
'auth' => true, //true表示smtp服务器需要验证,false代码不需要
'username' => 'tester', //用户名
'password' => 'retset' //密码
);
/***
* 使用$headers数组,可以定义邮件头的内容,比如使用$headers['Reply-To']可以定义回复地址
* 通过这种方式,可以很方便的定制待发送邮件的邮件头
***/
$headers['From'] = 'tester@domain.com'; //发信地址
$headers['To'] = 'tester@domain.com'; //收信地址
$headers['Subject'] = 'test mail send by php'; //邮件标题
$mail_object = &Mail::factory('smtp', $conf['mail']);
$body = <<< MSG //邮件正文
hello world!!!
MSG;
$mail_res = $mail_object->send($headers['To'], $headers, $body); //发送
if( Mail::isError($mail_res) ){ //检测错误
die($mail_res->getMessage());
}
?>
以上的代码非常的简单,配合注释应该不难看懂,关于PEAR和PEAR::Mail的更多信息,可以自己去翻阅PEAR Manual得到进一步的信息。
现在你依葫芦画瓢已经可以开始工作了,不过如果你还想做得更好、做得更多的话,我在这里提供一些更多的指南。
1、SMTP协议
熟悉并了解SMTP协议的内容,这样你可以进行更多的高级操作,甚至自己写一个满足自己特别需求的发邮件程序。以上的代码虽然简单,但是肯定还是有很多人不了解注释里提到的邮件头是什么东西,它到底对发出的邮件有什么样的影响。
比如“发送html邮件为什么对方看到的是乱码”等等问题都可能和邮件头相关,如果对smtp协议比较了解的话,可以很快的知道问题所在。
2、MIME规范
如果想要发送html邮件甚至多媒体邮件,一定是需要对MIME有一定了解的,有了这方面的知识你就可以发送内容更加精彩的邮件。
3、PEAR
PEAR并非唯一的发送邮件的工具,但是PEAR包含了Mail、Mail_Mime等等已经封装好了的类,可以让我们的开发事半功倍,并且除了Mail方面的东西以外,它还提供了很多其他方面的现成的工具,非常值得花时间学一学。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

On Douyin, users can not only share their life details and talents, but also interact with other users. In this process, sometimes we need to send files to other users, such as pictures, videos, etc. So, how to send files to others on Douyin? 1. How to send files to others on Douyin? 1. Open Douyin and enter the chat interface where you want to send files. 2. Click the "+" sign in the chat interface and select "File". 3. In the file options, you can choose to send pictures, videos, audio and other files. After selecting the file you want to send, click "Send". 4. Wait for the other party to accept your file. Once the other party accepts it, the file will be transferred successfully. 2. How to delete files sent to others on Douyin? 1. Open Douyin and enter the text you sent.

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

The role of a DHCP relay is to forward received DHCP packets to another DHCP server on the network, even if the two servers are on different subnets. By using a DHCP relay, you can deploy a centralized DHCP server in the network center and use it to dynamically assign IP addresses to all network subnets/VLANs. Dnsmasq is a commonly used DNS and DHCP protocol server that can be configured as a DHCP relay server to help manage dynamic host configurations in the network. In this article, we will show you how to configure dnsmasq as a DHCP relay server. Content Topics: Network Topology Configuring Static IP Addresses on a DHCP Relay D on a Centralized DHCP Server

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

In network data transmission, IP proxy servers play an important role, helping users hide their real IP addresses, protect privacy, and improve access speeds. In this article, we will introduce the best practice guide on how to build an IP proxy server with PHP and provide specific code examples. What is an IP proxy server? An IP proxy server is an intermediate server located between the user and the target server. It acts as a transfer station between the user and the target server, forwarding the user's requests and responses. By using an IP proxy server
