PHP 發送Email的幾種方法

轉載鏈接:http://blog.009it.com/php/75.html


在php中發送Email可以直接調用系統的mail()函數來完成,但是前提是你在php.ini文件中對mail都已經配置好了,以下為相關的配置信息:

[mail function]
; For Win32 only.
SMTP = localhost
smtp_port = 25; For Win32 only.
;sendmail_from = me@example.com; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
;sendmail_path =; Force the addition of the specified parameters to be passed as extra parameters
; to the sendmail binary. These parameters will always replace the value of
; the 5th parameter to mail(), even in safe mode.
;mail.force_extra_parameters =

Mail 配置選項

?

名稱 默認 描述 可更改

SMTP "localhost" Windows 專用:SMTP 服務器的 DNS 名稱或 IP 地址。 PHP_INI_ALL

smtp_port "25" Windows 專用:SMTP 段口號。自 PHP 4.3 起可用。 PHP_INI_ALL

sendmail_from NULL

Windows 專用:規定從 PHP 發送的郵件中使用的 "from"

?地址。

PHP_INI_ALL

sendmail_path NULL Unix 系統專用:規定sendmail 程序的路徑(通常 /usr/sbin/sendmail 或 /usr/lib/sendmail) PHP_INI_SYSTEM

?

上面寫的很清楚,要是windows的服務器,必須裝好開啟本地的smtp服務器,在linux和unix下,要用到sendmail,所以得配置好sendmail,根據自己的實際情況選擇適當的配置信息。

mail()函數如果郵件的投遞被成功地接收,則返回 true,否則返回 false,語法:

mail($to,$subject,$message,$headers,$parameters)

?

參數 描述

$to 必需。規定郵件的接收者。

$subject 必需。規定郵件的主題。該參數不能包含任何換行字符。

$message 必需。規定要發送的消息。

$headers 必需。規定額外的報頭,比如 From, Cc 以及 Bcc。

$parameters 必需。規定 sendmail 程序的額外參數。

?

簡單的發封郵件,代碼如下:

<?php$txt = "First line of text\nSecond line of text";// 如果一行大于 70 個字符,請使用 wordwrap()。
$txt = wordwrap($txt,70);// 發送郵件
mail("somebody@example.com","My subject",$txt);
?>

如果是一封帶HTML格式的Email則代碼如下:
<?php$to = "somebody@example.com, somebodyelse@example.com";
$subject = "HTML email";$message = "
<html>
<head>
<title>HTML email</title>
</head>
<body>
<p>This email contains HTML Tags!</p>
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
</tr>
</table>
</body>
</html>
";// 當發送 HTML 電子郵件時,請始終設置 content-type
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";// 更多報頭
$headers .= 'From: <webmaster@example.com>' . "\r\n";
$headers .= 'Cc: myboss@example.com' . "\r\n";mail($to,$subject,$message,$headers);
?>

函數很簡單,看似很好用,但是實際上局限性很明顯,必須是在本地的開啟smtp的情況下,而且經過測試成功率不是很高,所以程序中很少有人用到mail()函數來發郵件。

如果要擴展功能的話,還得重新構造,網上也有好多現成的類可以直接調用來實現,其實就是靠fsockopen來進行連接smtp,下面的代碼是個思路:

<?php
/**名稱:smtpsend . class . php功能:郵件發送類, 實現郵件發送功能, 可以發送html郵件;可驗證用戶是否具有發送權限;可實現從任意服務器郵箱發送郵件,并非局限于本機。 $smtpserver;SMTP服務器 $smtpserverport;SMTP服務器端口 $smtpuser;SMTP服務器的用戶帳號 $smtppass;SMTP服務器的用戶密碼 $fromMail;SMTP服務器的用戶郵箱 $toMail;發送給誰 $subject;郵件主題 $content;郵件內容 $mailtype;郵件格式(HTML / TXT), TXT為文本郵件 
*/class smtpclass {function smtp($relay_host = "", $smtp_port = 25, $auth = false, $user, $pass) {$this->debug = FALSE;$this->smtp_port = $smtp_port;$this->relay_host = $relay_host;$this->time_out = 60; //is used in fsockopen()$this->auth = $auth; //auth$this->user = $user;$this->pass = $pass;$this->host_name = "localhost"; //is used in HELO command$this->log_file = "";$this->sock = FALSE;}/* Main Function */function sendmail($to, $from, $subject = "", $body = "", $mailtype, $returnpath = "", $cc = "", $bcc = "", $additional_headers = "") {$mail_from = $this->get_address($this->strip_comment($from));$body = ereg_replace("(^|(\r\n))(\.)", "\1.\3", $body);$header = "";if (isset($returnpath) && $returnpath != "") {$header.= "Reply-To:" . $returnpath . "\r\n";}$header.= "MIME-Version:1.0\r\n";if ($mailtype == "HTML") {$header.= 'Content-Type:text/html; charset=gb2312' . "\r\n";}$header.= "To: " . $to . "\r\n";if ($cc != "") {$header.= "Cc: " . $cc . "\r\n";}$header.= "From: $from<" . $from . ">\r\n";$header.= "Subject: " . $subject . "\r\n";$header.= $additional_headers;$header.= "Date: " . date("r") . "\r\n";$header.= "X-Mailer:By Redhat (PHP/" . phpversion() . ")\r\n";list($msec, $sec) = explode(" ", microtime());$header.= "Message-ID: <" . date("YmdHis", $sec) . "." . ($msec * 1000000) . "." . $mail_from . ">\r\n";$TO = explode(",", $this->strip_comment($to));if ($cc != "") {$TO = array_merge($TO, explode(",", $this->strip_comment($cc)));}if ($bcc != "") {$TO = array_merge($TO, explode(",", $this->strip_comment($bcc)));}$sent = TRUE;foreach ($TO as $rcpt_to) {$rcpt_to = $this->get_address($rcpt_to);if (!$this->smtp_sockopen($rcpt_to)) {$this->log_write("Error: Cannot send email to " . $rcpt_to . "\n");$sent = FALSE;continue;}if ($this->smtp_send($this->host_name, $mail_from, $rcpt_to, $header, $body)) {$this->log_write("E-mail has been sent to <" . $rcpt_to . ">\n");} else {$this->log_write("Error: Cannot send email to <" . $rcpt_to . ">\n");$sent = FALSE;}fclose($this->sock);$this->log_write("Disconnected from remote host\n");}return $sent;}/* Private Functions */function smtp_send($helo, $from, $to, $header, $body = "") {if (!$this->smtp_putcmd("HELO", $helo)) {return $this->smtp_error("sending HELO command");}//authif ($this->auth) {if (!$this->smtp_putcmd("AUTH LOGIN", base64_encode($this->user))) {return $this->smtp_error("sending HELO command");}if (!$this->smtp_putcmd("", base64_encode($this->pass))) {return $this->smtp_error("sending HELO command");}}//if (!$this->smtp_putcmd("MAIL", "FROM:<" . $from . ">")) {return $this->smtp_error("sending MAIL FROM command");}if (!$this->smtp_putcmd("RCPT", "TO:<" . $to . ">")) {return $this->smtp_error("sending RCPT TO command");}if (!$this->smtp_putcmd("DATA")) {return $this->smtp_error("sending DATA command");}if (!$this->smtp_message($header, $body)) {return $this->smtp_error("sending message");}if (!$this->smtp_eom()) {return $this->smtp_error("sending <CR><LF>.<CR><LF> [EOM]");}if (!$this->smtp_putcmd("QUIT")) {return $this->smtp_error("sending QUIT command");}return TRUE;}function smtp_sockopen($address) {if ($this->relay_host == "") {return $this->smtp_sockopen_mx($address);} else {return $this->smtp_sockopen_relay();}}function smtp_sockopen_relay() {$this->log_write("Trying to " . $this->relay_host . ":" . $this->smtp_port . "\n");$this->sock = @fsockopen($this->relay_host, $this->smtp_port, $errno, $errstr, $this->time_out);if (!($this->sock && $this->smtp_ok())) {$this->log_write("Error: Cannot connenct to relay host " . $this->relay_host . "\n");$this->log_write("Error: " . $errstr . " (" . $errno . ")\n");return FALSE;}$this->log_write("Connected to relay host " . $this->relay_host . "\n");return TRUE;}function smtp_sockopen_mx($address) {$domain = ereg_replace("^.+@([^@]+)$", "\1", $address);if (!@getmxrr($domain, $MXHOSTS)) {$this->log_write("Error: Cannot resolve MX \"" . $domain . "\"\n");return FALSE;}foreach ($MXHOSTS as $host) {$this->log_write("Trying to " . $host . ":" . $this->smtp_port . "\n");$this->sock = @fsockopen($host, $this->smtp_port, $errno, $errstr, $this->time_out);if (!($this->sock && $this->smtp_ok())) {$this->log_write("Warning: Cannot connect to mx host " . $host . "\n");$this->log_write("Error: " . $errstr . " (" . $errno . ")\n");continue;}$this->log_write("Connected to mx host " . $host . "\n");return TRUE;}$this->log_write("Error: Cannot connect to any mx hosts (" . implode(", ", $MXHOSTS) . ")\n");return FALSE;}function smtp_message($header, $body) {fputs($this->sock, $header . "\r\n" . $body);$this->smtp_debug("> " . str_replace("\r\n", "\n" . "> ", $header . "\n> " . $body . "\n> "));return TRUE;}function smtp_eom() {fputs($this->sock, "\r\n.\r\n");$this->smtp_debug(". [EOM]\n");return $this->smtp_ok();}function smtp_ok() {$response = str_replace("\r\n", "", fgets($this->sock, 512));$this->smtp_debug($response . "\n");if (!ereg("^[23]", $response)) {fputs($this->sock, "QUIT\r\n");fgets($this->sock, 512);$this->log_write("Error: Remote host returned \"" . $response . "\"\n");return FALSE;}return TRUE;}function smtp_putcmd($cmd, $arg = "") {if ($arg != "") {if ($cmd == "") $cmd = $arg;else $cmd = $cmd . " " . $arg;}fputs($this->sock, $cmd . "\r\n");$this->smtp_debug("> " . $cmd . "\n");return $this->smtp_ok();}function smtp_error($string) {$this->log_write("Error: Error occurred while " . $string . ".\n");return FALSE;}function log_write($message) {$this->smtp_debug($message);if ($this->log_file == "") {return TRUE;}$message = date("M d H:i:s ") . get_current_user() . "[" . getmypid() . "]: " . $message;if (!@file_exists($this->log_file) || !($fp = @fopen($this->log_file, "a"))) {$this->smtp_debug("Warning: Cannot open log file \"" . $this->log_file . "\"\n");return FALSE;;}flock($fp, LOCK_EX);fputs($fp, $message);fclose($fp);return TRUE;}function strip_comment($address) {$comment = "\([^()]*\)";while (ereg($comment, $address)) {$address = ereg_replace($comment, "", $address);}return $address;}function get_address($address) {$address = ereg_replace("([ \t\r\n])+", "", $address);$address = ereg_replace("^.*<(.+)>.*$", "\1", $address);return $address;}function smtp_debug($message) {if ($this->debug) {echo $message;}}function senduserMail($smtpserver, $smtpserverport = 25, $smtpuser, $smtppass, $fromMail, $toMail, $subject, $content, $mailtype = 'HTML') {if ($fromMail == "") {die("發件人不能為空!");}if ($smtpuser == "") {die("用戶名不能為空!");}if ($smtppass == "") {die("用戶密碼不能為空!");}if ($subject == "") {die("標題不能為空!");}if ($toMail == "") {die("收件人不能為空!");}if ($content == "") {die("內容不能為空!");}$smtpserver = $smtpserver; //SMTP服務器$smtpserverport = $smtpserverport; //SMTP服務器端口$smtpuser = $smtpuser; //SMTP服務器的用戶帳號$smtppass = $smtppass; //SMTP服務器的用戶密碼$smtpusermail = $fromMail; //SMTP服務器的用戶郵箱$smtpemailto = $toMail; //發送給誰$mailsubject = $subject; //郵件主題$mailbody = $content; //郵件內容$mailtype = $mailtype; //郵件格式(HTML/TXT),TXT為文本郵件$this->smtp($smtpserver, $smtpserverport, true, $smtpuser, $smtppass); //這里面的一個true是表示使用身份驗證,否則不使用身份驗證.//$smtp->debug = TRUE;//是否顯示發送的調試信息$this->sendmail($smtpemailto, $smtpusermail, $mailsubject, $mailbody, $mailtype);}
}
//$smtp = new smtpclass();
//$smtp->senduserMail("mail.163.com",25,"用戶名","密碼","xxx@xxx.com.cn","xx@xx.com","測試","測試一下","TXT");?>

以上在網上看到的,其實具體的方法都是大同小異,用的很多的是一個開源的叫phpmailer,很方便的。用搜索引擎搜下然后下載就行。

這里貼出phpmailer的測試代碼:

<?php
require ("class.phpmailer.php");
require ("class.smtp.php");
//以下是實例:
$mail = new phpmailer(); //建立郵件發送類
$address = xxx@xxx . com;
$mail->IsSMTP(); // 使用SMTP方式發送
$mail->Host = "mail.xxx.com"; // 您的企業郵局域名
$mail->SMTPAuth = false; // 啟用SMTP驗證功能
$mail->Username = "xxx"; // 郵局用戶名(請填寫完整的email地址)
$mail->Password = "xxx"; // 郵局密碼
$mail->From = "xxxx@xxxx.cn"; //郵件發送者email地址
$mail->FromName = "您的名稱";
$mail->AddAddress("$address", ""); //收件人地址,可以替換成任何想要接收郵件的email信箱,格式是AddAddress("收件人email","收件人姓名")
//$mail->AddReplyTo("", "");
//$mail->AddAttachment("/var/tmp/file.tar.gz"); // 添加附件
//$mail->IsHTML(true); // set email format to HTML //是否使用HTML格式
$mail->Subject = "PHPMailer測試郵件"; //郵件標題
$mail->Body = "Hello,這是測試郵件"; //郵件內容
$mail->AltBody = "This is the body in plain text for non-HTML mail clients"; //附加信息,可以省略
if (!$mail->Send()) {echo "郵件發送失敗. <p>";echo "錯誤原因: " . $mail->ErrorInfo;exit;
}
echo "郵件發送成功";
?>

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/276516.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/276516.shtml
英文地址,請注明出處:http://en.pswp.cn/news/276516.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

學習 lodash 源碼整體架構,打造屬于自己的函數式編程類庫

前言這是 學習源碼整體架構系列第三篇。整體架構這詞語好像有點大&#xff0c;姑且就算是源碼整體結構吧&#xff0c;主要就是學習是代碼整體結構&#xff0c;不深究其他不是主線的具體函數的實現。文章學習的是打包整合后的代碼&#xff0c;不是實際倉庫中的拆分的代碼。上上篇…

python數據庫模糊查詢_Python操作mongodb數據庫進行模糊查詢操作示例

本文實例講述了Python操作mongodb數據庫進行模糊查詢操作。分享給大家供大家參考&#xff0c;具體如下&#xff1a;# -*- coding: utf-8 -*-import pymongoimport refrom pymongo import MongoClient#創建連接#10.20.66.106client MongoClient(10.20.4.79,27017)#client Mong…

推薦一個快速反射調用的類

使用傳統的.net反射機制&#xff0c;調用類的方法時&#xff0c;在調用頻率大的情況下&#xff0c;會感覺速度很慢。最近瀏覽盧彥的博客時&#xff0c;找到一個他改進后的反射調用類。試用以后感覺效率明顯提高&#xff0c;特推薦給大家。作者重新實現了&#xff0c;反射調用方…

CMake 構建項目Android NDK項目基礎知識

本篇文章將介紹如何使用 CMake 構建實現你的第一個 NDK 項目。 ##前言 你好&#xff01;歡迎來到我的的學習筆記分享系列&#xff0c;第一次給大家分享的是 Android NDK 開發的學習筆記&#xff0c;讓我們先開始了解 NDK 的構建方式吧&#xff01; NDK 構建方式有兩種&#xff…

linux installaccess Nessus-5.2.4

1、Download: http://www.tenable.com/products/nessus/select-your-operating-system 2、Current version&#xff1a;Nessus-5.2.4-debian6_i386.deb 3、Install&#xff1a;dpkg -i Nessus-5.2.4-debian6_i386.deb # dpkg -i Nessus-5.2.4-debian6_i386.deb Selecting p…

面試官問:JS的繼承

原文作者若川&#xff0c;掘金鏈接&#xff1a;https://juejin.im/post/5c433e216fb9a049c15f841b寫于2019年2月20日&#xff0c;現在發到公眾號聲明原創&#xff0c;之前被《前端大全》公眾號等轉載閱讀量超1w&#xff0c;知乎掘金等累計閱讀量超過1w。導讀&#xff1a;文章主…

qt 快速按行讀取文件_這是知識點之Linux下分割文件并保留文件頭

點擊上方"開發者的花花世界"&#xff0c;選擇"設為星標"技術干貨不定時送達&#xff01;這是一個知識點方便快捷的給結構化數據文件分割大小并保留文件的表頭&#xff0c;幾十個G的結構化文件不僅閱讀編輯麻煩&#xff0c;而且使用受限&#xff0c;因此高效…

mono 調用windows webService

1. 實現linux mono Develop中調用windows 中的webService l linux 與 windows 在一個局域網的網段中 l windows 的IIs中發布webService 2. windows 中的設置 l webService 的代碼 using System; using System.Collections.Generic; using System.Linq; using S…

Linux 內存機制

轉載鏈接&#xff1a;http://blog.csdn.net/tianlesoftware/article/details/5463790 一. 內存使用說明 Free 命令相對于top 提供了更簡潔的查看系統內存使用情況&#xff1a; [rootrac1 ~]# free total used free shared buffers cached Mem: …

network中的請求信息,headers中的每一項分別是什么意義?

這里是修真院前端小課堂&#xff0c;每篇分享文從 【背景介紹】【知識剖析】【常見問題】【解決方案】【編碼實戰】【擴展思考】【更多討論】【參考文獻】 八個方面深度解析前端知識/技能&#xff0c;本篇分享的是&#xff1a; 【network中的請求信息&#xff0c;headers中的每…

學習 sentry 源碼整體架構,打造屬于自己的前端異常監控SDK

前言這是學習源碼整體架構第四篇。整體架構這詞語好像有點大&#xff0c;姑且就算是源碼整體結構吧&#xff0c;主要就是學習是代碼整體結構&#xff0c;不深究其他不是主線的具體函數的實現。文章學習的是打包整合后的代碼&#xff0c;不是實際倉庫中的拆分的代碼。其余三篇分…

巴西龜吃什么

1、活蝦&#xff0c;哈哈&#xff0c;巴西龜最喜歡的食物&#xff0c;超市很多雞尾蝦買的&#xff0c;就那種&#xff0c;要活的&#xff0c;鍛煉它們的天性&#xff0c;一次一只可以吃一、兩天&#xff1b; 2、蚶子&#xff0c;貝殼類&#xff0c;活的&#xff0c;整個扔進去&…

綁定dictionary 給定關鍵字不再字典中_VBA代碼集錦-利用字典做兩列數據的對比并對齊...

源數據&#xff1a;代碼&#xff1a;Sub 對比()Dim arr, brr, crrDim i, j, n, lastrowA, lastrowB As Integer建立字典對象Set d CreateObject("scripting.dictionary")獲取數據區域最后一行的行數lastrowA Sheets("對比對齊兩列數據").Cells(Rows.Coun…

linux啟動時掛載rootfs的幾種方式 .

轉載鏈接&#xff1a;http://blog.csdn.net/zuokong/article/details/9022707 根文件系統&#xff08;在樣例錯誤消息中名為 rootfs&#xff09;是 Linux 的最基本的組件。根文件系統包含支持完整的 Linux 系統所需的所有內容。它包含所有應用程序、配置、設備、數據等 Linux 中…

PHP 手冊

by:Mehdi AchourFriedhelm BetzAntony DovgalNuno LopesHannes MagnussonGeorg RichterDamien SeguyJakub Vrana其他貢獻者2018-06-19Edited By: Peter Cowburn中文翻譯人員&#xff1a;肖盛文洪建家穆少磊宋琪黃嘯宇王遠之肖理達喬楚戴劼褚兆瑋周夢康袁玉強段小強© 1997-…

前端使用puppeteer 爬蟲生成《React.js 小書》PDF并合并

前端也可以爬蟲&#xff0c;寫于2018年08月29日&#xff0c;現在發布到微信公眾號申明原創。掘金若川 本文章鏈接&#xff1a;https://juejin.im/post/5b86732451882542af1c80821、 puppeteer 是什么&#xff1f;puppeteer: Google 官方出品的 headless Chrome node 庫puppetee…

蜘蛛與佛的故事

最近閉關,空面四壁,窗外層巒疊嶂,窗臺上只有一盆花每日陪著我&#xff0c;朋友們都說我要成佛了,想想也是&#xff01; 于是在閉關即將結束的時候找了一篇佛的故事送給自己&#xff0c;希望自己能夠頓悟一些"禪"機。 從前&#xff0c;有一座圓音寺&#xff0c;每天都…

信息安全管理與評估_計算機工程學院教師參加“信息安全管理與評估賽項”說明會...

看了就要關注我&#xff0c;喵嗚~2019年3月15日下午&#xff0c;2019年陜西省高等職業院校技能大賽“信息安全管理與評估賽項說明會”在咸陽職業技術學院舉行。出席本次會儀的有咸陽職業技術學院教務處長楊新宇、神州數碼范永強經理、神州數碼信息安全工程師高峰和各院校指導教…

haproxy概念和負載均衡

https://pan.baidu.com/s/1Sq2aJ35zrW2Xn7Th9j7oOA //軟件百度網盤連接 在80.100虛擬機上 systemctl stop firewalld //關閉防火墻 setenforce 0 //關閉監控 yum install lrz* -y //安裝上傳軟件 tar xf haproxy-1.5.15.tar.gz -C /opt/ //解壓壓縮包到/opt/ cd /op…

PHP用戶注冊郵箱驗證激活帳號

轉載鏈接&#xff1a;http://www.helloweba.com/view-blog-228.html 本文將結合實例&#xff0c;講解如何使用PHPMysql完成注冊帳號、發送激活郵件、驗證激活帳號、處理URL鏈接過期的功能。 業務流程 1、用戶提交注冊信息。 2、寫入數據庫&#xff0c;此時帳號狀態未激活。 …