天天看點

PHP發送郵件函數sendmail()

不需要郵件伺服器,不使用mail内置函數,一個類就搞定,利用phpmailer類我寫了一個自定義函數 sendmail() ,very實用!

以前也在幾個php論壇上發表過這個發郵件的函數,今天再發,因為today要附上使用例子,如果你還不會用,那就要補補php基礎課了。

1.下載下傳相關檔案sendmail.rar,包含 index.php檔案、phpmailer類庫檔案夾  下載下傳 

2.然後解壓 sendmail.rar 到伺服器的任何目錄下

3.打開 index.php ,如下(修改淺黃色标記部分,表單部分随便。)

<?php

include_once "phpmailer/class.phpmailer.php"; 

function sendmail($to,$subject,$content) {

 $mail = new phpmailer();

 // 以下設定 - 不要更改!

 $mail->issmtp();

 $mail->smtpauth = true;

 $mail->ishtml(true);

 $mail->charset ="gb2312";  

 $mail->encoding = "base64";

 // 以下設定 - 不要更改!    

 $mail->addaddress($to, ""); 

 $mail->subject = $subject;  

 $mail->body    = $content;    

 // 以下 5 個變量值必須據實修改

 $host    = '61.183.41.172';

 $username = '[email protected]';

 $password = '******';        

 $from    = '[email protected]';  

 $fromname = '天馬部落格';  

 //$mail->addreplyto("", "");      

 //$mail->addattachment("ok.jpg"); //附件 

 // 以下設定 - 不要更改!  

 $mail->host    = $host;                              

 $mail->username = $username;    

 $mail->password = $password;                

 $mail->from    = $from;          

 $mail->fromname = $fromname;                  

 // 發送并傳回相應資訊

 if(!$mail->send()){ return 0; exit(); }

 return 1;

}

?>

<form action="" method="post" name="f_sendmail" id="f_sendmail">

<input name="t_from" type="text" disabled="disabled" id="t_from" value="[email protected]" />

發件人

<p>

  <input name="t_to" type="text" id="t_to" />

收件人<p><input name="b_sendmail" type="submit" id="b_sendmail" value=" 發 送 " />

</form>

/**先設定 $to $subject $content 這三個變量的值

  再調用 sendmail 函數來發送郵件

**/

if($_post[b_sendmail]){

 $to = htmlspecialchars(addslashes($_post[t_to]));

 $subject = '天馬部落格:一封測試郵件↖(^ω^)↗';

 $content = '恭喜你,你已看到了php發送郵件的效果。 -- <a href="http://www.php95.com" target="_blank">天馬部落格</a>';

 if(sendmail($to,$subject,$content)) {

  echo "發送到 $to 的郵件已成功!";

 }else{

  echo '發送失敗!';

 } 

4.最後一步,運作index.php

你的郵件是否發送成功?

天馬測試本代碼,is ok,見證:

PHP發送郵件函數sendmail()
PHP發送郵件函數sendmail()

http://www.examw.com/biancheng/php/140429/