search
HomeBackend DevelopmentPHP Tutorial用Socket发送电子邮件--续篇smtp认证_PHP

SMTP

作者limodou 



  在前面我曾经写过一篇文章介绍了如何利用socket编程来发送邮件以解决web服务器不支

持mail
()函数的问题。经过我的测试也是可以使用的。但目前众多的免费邮件提供商从263开

163新浪网也快开始了均在smtp功能上增加了认证功能使得原邮件发送类无法使用。在

经过对相应smtp后续rfc的学习之后
经过了多次的试验我终于试验成功了。于是怀着急迫的心

情向大家介绍。
 



SMTP 认证功能介绍 

  此处不想向你详细介绍SMTP认证功能因为我也说不清楚详细的请参考[RFC 2554]规范。

SMTP的认证功能主要是增加了AUTH命令。AUTH命令有多种用法
而且有多种认证机制。AUTH支持

的认证机制主要有LOGIN
CRAM-MD5[注1]等。LOGIN应该是大多数免费邮件服务器都支持的263

与新浪都支持。而新浪还支持CRAM
-MD5机制。认证机制一般只在真正发送邮件之前进行而且只

需要执行一次。当认证成功后
即可按原来正常的处理发送邮件。原理是口令-应答(Challenge-

Response)即由服务器发送命令要求客户端回答客户端根据服务器发送信息进行回答如果应

答通过了
则认证成功即可继续处理。下面对这两种制作一个简单介绍。S:表示服务器返回

C:表示客户端发送。 





LOGIN 

它应该比较简单。口令-应答过程如下 



1 C: AUTH LOGIN 

2 S: 334 dXNlcm5hbWU6 

3 C: dXNlcm5hbWU6 

4 S: 334 cGFzc3dvcmQ6 

5 C: cGFzc3dvcmQ6 

6 S: 235 Authentication successful. 

1 为客户端向服务器发送认证指令。 

2 服务端返回base64编码串成功码为334。编码字符串解码后为“username:说明要求客户

端发送用户名。
 

3 客户端发送用base64编码的用户名此处为“username:”。 

4 服务端返回base64编码串成功码为334。编码字符串解码后为“password:说明要求客户

端发送用户口令。
 

5 客户端发送用base64编码的口令此处为“password:”。 

6 成功后服务端返回码为235表示认证成功可以发送邮件了。 



对于LOGIN方式认证其实就是将用户名与口令用base64进行编码根据服务器的要求分别发出

即可。
(就我看来由于base64是一种公共的编码标准也起不到太大的保护作用。) 

CRAM-MD5机制 

关于CRAM-MD5的机制可以参考[RFC 2195]规范这里不详细说明了。主要就是通过口令-回答机

由服务端发出一个信息串这个由随机数时间戳服务器地址构成并且用base64编码。

客户端收到后
发送一个由用户名加一个空格再加一个摘要构成的串并用base64编码。摘

要是通过MD5算法求出。这种机制要求服务端与客户端有相同的加密串。当客户端发送摘要后


务器对其合法性进行验证
成功后返回235。 

如何得知邮件服务器支持什么认证 

  在smtp的[RFC 821]在与邮件服务器连接成功后第一个命令一般是“HELO”。但是在支

持认证的邮件服务器中
第一个命令应改为“EHLO”[注2]。在命令成功后263的返回可能为 



EHLO hello 

250-smtp.263.net [注3] 

250-PIPELINING 

250-SIZE 10240000 

250-ETRN 

250-AUTH LOGIN 

250 8BITMIME 

  从而可以看到263支持LOGIN方式认证。当然如果你已经知道邮件服务器是什么方式也没

有必要自动进行判断
但是如果不知道就需要分析这个返回结果了。不过大部分的邮件服务器

都支持最简单的LOGIN方式。
 



  好了下面开始对以前所写的sendmail.class.php3进行修改。你没有不要紧本文在最后提

供了sendmail
.class.php3的打包文件可以下载。至于例子则自已根据本文进行编写。 



修改sendmail.class.php3 

  此处只说出修改的重点而不是全面的分析。 



  首先回顾一下sendmail.class.php3的思路让大家先心中有数。 



  sendmail.class.php3一共有四个函数分别为 



send_mail 类的构造函数用于信息的初始化 

send 邮件发送函数执行socket命令发送邮件 

do_command 命令执行函数执行一条smtp命令并将处理返回结果 

show_debug 显示调示信息函数 

  首先用户应先调用类的构造函数对必要的参数进行初始化。如smtp服务器地址($smtp)

迎信息
($welcome)及是否显示调示信息($debug)。同时还要初始化一些内部变量如最后执行

命令
($lastact)最后响应信息($lastmessage)及端口号($port=25) 



  然后用户生成邮件信息并调用send()函数发送邮件。在send()函数中根据smtp规范

一条命令接一条命令执行(详情参见前面的文章)。在执行命令时是通过调用do_command()来实

现的。如果do_command
()执行出错则程序立即返回否则继续向下执行。如果设置了显示调示

信息标志
则do_command()在命令发送和信息响应时会返回调示信息。 



  好了大家已经对它的运行有了一个了解下面就是如何修改了。 



  修改构造函数(send_mail) 

  由于以前的send_mail类不支持认证功能所以先要增加认证信息。增加了三个参数

$auth $authuser和$authpasswd。$auth是一个标志表示是否要使用认证功能。$authuser

和$authpasswd是smtp认证的用户名和口令
根据相应的邮件服务商的要求例如263是同pop3相

一致。大部分应该也是如此。这样
同时需要在类的内部变量表后面增加三个内部变量$auth

$user$passwd。 



  修改发送函数(send) 

  将发送命令HELO改为发送EHLO。同时要加入判断是否要进行认证处理 



//改为支持ESMTP EHLO命令 

if($this->auth) 

 

else 

$this->lastact="HELO "; 

  即如果需要认证处理则发送EHLO命令否则还发送HELO命令。 



  然后增加认证处理 



//2000.02.28 增加认证处理 

if($this->auth) 

 



//回传用户名用base64编码 

$this->lastact=base64_encode($this->user) . "

"
; 

if(!$this->do_command($this->lastact, "334")) 

 



//回传口令用base64编码 

$this->lastact=base64_encode($this->passwd) . "

"
; 

if(!$this->do_command($this->lastact, "235")) 

 

} 

  注意这里只实现了AUTH LOGIN机制CRAM-MD5没有实现。而且对服务器传回的信息没有判

默认为第一次要求用户名第二次要求口令。 



  修改命令执行函数(do_command) 

  原函数不能显示当响应串为多行的情况。修改为 



/* 2000.02.28 修改,将返回信息显示完全 
$this->lastmessage = fgets ( $this->fp, 512 ); 

$this->show_debug($this->lastmessage, "in"); 

*/
 

while(true) 

 

  这样类就改好了。 



测试send_mail类 

  下面是我编写的一个测试小程序用于发送一封信但是为了安全起见我将用户名及口令

没有用真实信息
如果大家想要测试请改成你自已的信息。程序如下(send.php) 



<? 

include("sendmail.class.php3"); 



$sendmail=new send_mail("smtp.263.net", true, "username", "password", "hello", 

true); 

$sendmail->send("toemail, "fromemail", "test", "This is a test!"); 

?> 

结论 

  对于263的测试很顺利也比较快。但是新浪网则不容易成功主要是超时而且发成功也收

不着
不知为何 



  注意由于发送smtp需要用户名及口令且大部分的smtp认证使用与pop3相同的用户名和口

令。所以如果大家使用这个方法
可能会把用户名和口令写入程序上传到服务器。但是这样做

是不安全的。加密也不一定好用
因为信息放在服务器上相应的解密信息也会放到服务器上。

我的建议是
再申请一个专门用来发信用的信箱这样别人知道了也不怕。 



  希望这个程序对你有用。sendmail.class.php3下载。 



相关的RFC 



RFC 1869 SMTP Service Extensions 

RFC 2195 IMAP/POP AUTHorize Extension(里面有关于CRAM-MD5的说明) 

RFC 2222 Simple Authentication and Security Layer 

RFC 2554 SMTP Service Extension for Authentication 



-------------------------------------------------------------------------------- 

[注1] 

CRAM=Challenge-Response Authentication Mechanism 口令-应答认证机制 

MD5是一种摘要算法主要用于RSAPGP中。 

[注2] 

关于EHLO的说明参见[RFC 1869] 

[注3] 

在邮件服务器应答串中如果应响码后面跟空格( )表示应答串只有一行如果为减号(-)

表示有多行且最后一行响应码后面为空格( ) 

本文所有权属于limodou。如要转载请保留此信息。 





注意sendmail.class.php3下载地址 

http://www.zphp.com/files/sendmail.cl
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
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!