search
HomeBackend DevelopmentPHP Tutorial如何使用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方面的东西以外,它还提供了很多其他方面的现成的工具,非常值得花时间学一学。

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
PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP: The Foundation of Many WebsitesPHP: The Foundation of Many WebsitesApr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

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

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.