PHP发信 发邮件 SendMail SMTPclass

PHP发信有很多种方式,可以使用

1、脚本自带的函数sendmail()

2、可以使用Linux的命令SendMail

3、自己实现socket与SMTP服务器使用命令通信发信

4、使用第三方现有PHP邮件类库

前两种都需要环境支持且需要已配置好邮件帐户信息等等。

由于前两种移植性的关系,我们暂不考虑,本文我们采用网络上最简短的库,你可以任意修改它的PHP源代码。

类库文件:SMTPclass.php

<?php

class SMTPClient

{

 

function SMTPClient ($SmtpServer, $SmtpPort, $SmtpUser, $SmtpPass, $from, $to, $subject, $body)

{

$this->SmtpServer = $SmtpServer;

$this->SmtpUser = base64_encode ($SmtpUser);

$this->SmtpPass = base64_encode ($SmtpPass);

$this->from = $from;

$this->to = $to;

$this->subject = $subject;

$this->body = $body;

 

if ($SmtpPort == "")

{

$this->PortSMTP = 25;

}

else

{

$this->PortSMTP = $SmtpPort;

}

}

function SendMail ()

{

if ($SMTPIN = fsockopen ($this->SmtpServer, $this->PortSMTP))

{

fputs ($SMTPIN, "EHLO ".$HTTP_HOST."\r\n");

$talk["hello"] = fgets ( $SMTPIN, 1024 );

fputs($SMTPIN, "auth login\r\n");

$talk["res"]=fgets($SMTPIN,1024);

fputs($SMTPIN, $this->SmtpUser."\r\n");

$talk["user"]=fgets($SMTPIN,1024);

fputs($SMTPIN, $this->SmtpPass."\r\n");

$talk["pass"]=fgets($SMTPIN,256);

fputs ($SMTPIN, "MAIL FROM: <".$this->from.">\r\n");

$talk["From"] = fgets ( $SMTPIN, 1024 );

fputs ($SMTPIN, "RCPT TO: <".$this->to.">\r\n");

$talk["To"] = fgets ($SMTPIN, 1024);

fputs($SMTPIN, "DATA\r\n");

$talk["data"]=fgets( $SMTPIN,1024 );

fputs($SMTPIN, "Content-Type: text/html; charset=\"UTF-8\";\r\n");

$talk["data"]=fgets( $SMTPIN,1024 );

fputs($SMTPIN, "To: <".$this->to.">\r\nFrom: <".$this->from.">\r\nSubject:".$this->subject."\r\n\r\n\r\n".$this->body."\r\n.\r\n");

$talk["send"]=fgets($SMTPIN,256);

//CLOSE CONNECTION AND EXIT ...

fputs ($SMTPIN, "QUIT\r\n");

fclose($SMTPIN);

}

return $talk;

}

}

?>

类库文件配置文文件2 :SMTPconfig.php

<?php

//Server Address

$SmtpServer="smtp.garmin.com";

$SmtpPort="25"; //default

$SmtpUser="username";

$SmtpPass="password";

?>

然后可以就可以写一个PHP简单页面让其调用访问了这些类即可(下代码):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></head><body>

<form method="post" action="">

To:<input type="text" name="to" value="abc@garmin.com" />

From :<input type='text' name="from" value="bbc@garmin.com"/><br />

Subject :<input type='text' name="sub" value="this is a test mail"/><br />

Message :<textarea name="message" style="width: 237px; height: 176px;">php test mail</textarea>

<input type="submit" value=" Send " />

</form>

<?php

include('SMTPconfig.php');

include('SMTPClass.php');

if($_SERVER["REQUEST_METHOD"] == "POST")

{

$to = $_POST['to'];

$from = $_POST['from'];

$subject = $_POST['sub'];

$body = $_POST['message'];

$SMTPMail = new SMTPClient ($SmtpServer, $SmtpPort, $SmtpUser, $SmtpPass, $from, $to, $subject, $body);

$SMTPChat = $SMTPMail->SendMail();

 

echo "<font color=red size='+3'>邮件已经成功发送</font>";

}

?>

</body></html>

posted @ 2013-04-25 11:29  重庆Debug  阅读(366)  评论(0编辑  收藏  举报