介绍
介绍
在现如今的互联网时代里电子邮件的使用率大幅度降低了,除了企业内部发通知之外就剩下网站平台发送激活邮件使用了。
但是无论如何发送邮件这个需求还是有的,而大多数发送邮件都是使用SMTP协议方式发送的,因为匿名邮件会被大多数客户端(如:Outlook、Foxmail、GMail等等)自动丢尽垃圾箱里面了。
今天福哥就要给我们的TFPHP框架增加一个发送电子邮件的工具对象TFMail,这个对象发送邮件遵循的是SMTP协议规范的,也就是说使用TFMail发送邮件需要使用一个SMTP账号才行。
TFMail
setSMTP
public function setSMTP(string $a,int $b,string $c,string $d,int $e=60):bool{
$this->a=fsockopen($a,$b,$f,$g,$e);
if($this->a){
$this->b=$a;
$this->c=$b;
$this->d=$c;
$this->e=$d;
return true;
}
return false;
}send
public function send(string $a,string $b,array $c):bool{
if($this->a==null){
return false;
}
$this->f=array();
$this->g=0;
$this->h="";
$d=$c['from'];
$e=$c['to'];
$f=$c['multipleTo'];
$g=$c['fromAlias'];
$h=$c['toAlias'];
$i=$c['multipleToAlias'];
$j=$c['charset'];
if($j==null){
$j=$this->j;
}
else{
$j=strtoupper($j);
}
if($d==null||$e==null){
return false;
}
if(!$this->f(220)){
return false;
}
$this->e("helo ".$this->b);
if(!$this->f(250)){
return false;
}
$this->e("auth login");
if(!$this->f(334)){
return false;
}
$this->e(base64_encode($this->d));
if(!$this->f(334)){
return false;
}
$this->e(base64_encode($this->e));
if(!$this->f(235)){
return false;
}
$k=$l=sprintf("<%s>",$d);
if($g!=null){
$k=sprintf("\"%s\"<%s>",$this->c($g,$j),$d);
}
$m=$n=array();
if($f!=null){
foreach($f as $o=>$e){
$m[$o]=$n[$o]=sprintf("<%s>",$f[$o]);
if($i[$o]!=null){
$m[$o]=sprintf("\"%s\"<%s>",$this->c($i[$o],$j),$f[$o]);
}
}
}
else{
$m[0]=$n[0]=sprintf("<%s>",$e);
if($h!=null){
$m[0]=sprintf("\"%s\"<%s>",$this->c($h,$j),$e);
}
}
$p=join(",\r\n\t",$m);
$this->e("mail from: ".$k);
if(!$this->f(250)){
if($k!=$l){
$this->e("mail from: ".$l);
if(!$this->f(250)){
return false;
}
}
else{
return false;
}
}
foreach($m as $o=>$q){
$this->e("rcpt to: ".$n[$o]);
if(!$this->f(250)){
return false;
}
}
$this->e("data");
if(!$this->f(354)){
return false;
}
$r=$this->a();
$s=$this->b();
$t=$this->d($b);
$a=$this->c($a,$j);
$u=base64_encode(md5(time()));
$v=base64_decode($this->i);
$w=sprintf($v,$k,$p,$a,$s,$r,$u,$r,$j,$t,$r,$j,$j,$b,$r);
$this->e($w);
$this->e("\r\n.\r\n",false);
if(!$this->f(250)){
return false;
}
return true;
}close
public function close():bool{
if($this->a!=null){
fclose($this->a);
return true;
}
return false;
}讲解
TFMail
TFMail对象存放在Socket/TFMail.inc.php里面。
setSMTP
在这个方法里面我们要求用户提供SMTP账号信息,包括SMTP服务器地址和端口、SMTP的用户名和密码等等。同时福哥在这个方法里面建立了SMTP服务器的连接。
send
这个方法是TFMail的主要逻辑,在这个方法里面福哥会依据SMTP协议规范和SMTP服务器对话,完成发送电子邮件的操作。
close
这个方法是要关闭SMTP服务器的连接,回收资源。
效果
这里是一个打印step信息的效果,可以看到TFMail和SMTP服务器的交互过程。

总结
今天福哥给TFPHP框架添加了邮件发送工具对象TFMail,有了这个TFMail之后,我们就可以在网站平台里面想用户发送电子邮件了。
这个功能会首先用到TFUMS的绑定邮件功能上,届时可以验证TFMail对象是否好用了。