欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php socket使用smtp发送带附件的邮件

程序员文章站 2024-04-06 14:43:55
...
  1. /**

  2. * php socket smtp发送邮件
  3. * edit: bbs.it-home.org
  4. */
  5. //define("SOL", "\n");

  6. define("EOL", "\r\n");
  7. define("SMTP_HOST", "smtp.163.com");//SMTP服务器
  8. define("SMTP_PORT", "25");//SMTP服务器端口
  9. define("SMTP_USER", "");//SMTP服务器的用户帐号
  10. define("SMTP_PASS", "");//SMTP服务器的用户密码
  11. $from = "";//SMTP服务器的用户邮箱

  12. $to = "";//发送给谁 可用逗号隔开多个邮箱
  13. $cc = "";
  14. $bcc = "";
  15. $subject="这是一个由PHP发送的带附件的邮件";//邮件主题 很多客户端会有乱码,所以转一下码

  16. $body = "这个是一个带附件的邮件发送程序
    看到没,这里显示了HTM标签哦;请点开链接 ".date('Y-m-d H:i:s');//邮件内容
  17. $smtp = new smtp(SMTP_HOST,SMTP_PORT,SMTP_USER,SMTP_PASS, true);//这里面的一个true是表示使用身份验证,否则不使用身份验证.
  18. $smtp->addAttachment("mail.zip");
  19. $smtp->sendmail($to, $from, $subject, $body, $cc, $bcc);
  20. class smtp {

  21. /* Public Variables */

  22. public $attachments = array();
  23. /* Private Variables */
  24. private $smtp_host;
  25. private $smtp_port;
  26. private $time_out;
  27. private $host_name;
  28. private $auth;
  29. private $user;
  30. private $pass;
  31. private $sock;
  32. /* Constractor */

  33. public function smtp($smtp_host = null, $smtp_port = null, $user = null, $pass = null, $auth = true) {
  34. $this->smtp_host = (!empty($smtp_host)) ? $smtp_host : SMTP_HOST;
  35. $this->smtp_port = (!empty($smtp_port)) ? $smtp_port : SMTP_PORT;
  36. $this->user = (!empty($user)) ? $user : SMTP_PORT;
  37. $this->pass = (!empty($pass)) ? $pass : SMTP_PORT;
  38. $this->auth = $auth;
  39. $this->time_out = 15;
  40. #
  41. $this->host_name = "localhost";
  42. $this->sock = FALSE;
  43. }
  44. /* Main Function */

  45. public function sendmail($to, $from, $subject = "", $body = "", $cc = "", $bcc = "") {
  46. $bndp = md5(uniqid("")) . rand(1000, 9999);
  47. $bnd = md5(uniqid("")) . rand(1000, 9999);
  48. list ($msec, $sec) = explode(" ", microtime());
  49. $mail_from = $this->strip_line_breaks($from);

  50. $mail_to = explode(",", $to);
  51. $body = preg_replace("/(^|(\r\n))(\\.)/", "", $body);
  52. if ($cc != "") $mail_to = array_merge($mail_to, explode(",", $cc));
  53. if ($bcc != "") $mail_to = array_merge($mail_to, explode(",", $bcc));
  54. $headers = "MIME-Version:1.0" . EOL;

  55. $headers .= "To: " . $to . EOL;
  56. if ($cc != "") {
  57. $headers .= "Cc: " . $cc . EOL;
  58. }
  59. $headers .= "From: $from" . EOL;
  60. $headers .= "Subject: " . $subject . EOL;
  61. $headers .= "Date: " . date("r") . EOL;
  62. $headers .= "X-Mailer: Webmail ver 1.0 (PHP Version/" . phpversion() . ")" . EOL;
  63. $headers .= "Message-ID: " . EOL;
  64. if (count($this->attachments) > 0) {
  65. $headers .= "Content-Type: multipart/mixed;" . EOL . chr(9) . " boundary=\"" . $bndp . "\"" . EOL . EOL;
  66. $headers .= '--'.$bndp . EOL;
  67. $headers .= 'Content-Type : multipart/alternative; boundary="' . $bnd . '"' . EOL . EOL;
  68. $headers .= '--' . $bnd . EOL;
  69. $headers .= 'Content-Type: text/plain; charset=utf-8' . EOL;
  70. $headers .= "Content-Transfer-Encoding: 8bit" . EOL . EOL;
  71. $headers .= $body . EOL;
  72. $headers .= '--' . $bnd . EOL;
  73. $headers .= 'Content-type: text/html; charset=utf-8' . EOL;
  74. $headers .= "Content-Transfer-Encoding: 8bit" . EOL . EOL;
  75. $headers .= $body . EOL;
  76. $headers .= '--' . $bnd . '--' . EOL;
  77. foreach ($this->attachments as $att) {

  78. $headers .= "--" . $bndp . EOL . $att;
  79. }
  80. $headers .= '--' . $bndp . '--' . EOL;
  81. $this->clear_attachments();
  82. } else {
  83. $headers .= 'Content-Type : multipart/alternative;boundary="'.$bnd.'"' . EOL . EOL;
  84. $headers .= '--'.$bnd . EOL;
  85. $headers .= 'Content-Type: text/plain; charset=utf-8' . EOL;
  86. $headers .= "Content-Transfer-Encoding: 8bit" . EOL . EOL;
  87. $headers .= $body . EOL;
  88. $headers .= '--'.$bnd . EOL;
  89. $headers .= 'Content-type: text/html; charset=utf-8' . EOL;
  90. $headers .= "Content-Transfer-Encoding: 8bit" . EOL . EOL;
  91. $headers .= $body . EOL;
  92. $headers .= '--'.$bnd.'--' . EOL;
  93. }
  94. $sent = TRUE;

  95. foreach ($mail_to as $rcpt_to) {
  96. $rcpt_to = $this->strip_line_breaks($rcpt_to);
  97. if (!$this->smtp_sockopen($rcpt_to)) {
  98. $this->log_write("Error: Cannot send email to " . $rcpt_to);
  99. $sent = FALSE;
  100. continue;
  101. }
  102. if ($this->smtp_send($this->host_name, $mail_from, $rcpt_to, $headers, $body)) {
  103. $this->log_write("E-mail has been sent to ");
  104. } else {
  105. $this->log_write("Error: Cannot send email to ");
  106. $sent = FALSE;
  107. }
  108. fclose($this->sock);
  109. }
  110. $this->log_write("{$mail_to} send over;");
  111. return $sent;
  112. }
  113. public function addAttachment($file, $dispo = "attachment") {

  114. $file_data = (file_exists($file)) ? file_get_contents($file) : "";
  115. if ($file_data != "") {
  116. $filename = basename($file);
  117. $ext = pathinfo($filename, PATHINFO_EXTENSION);
  118. $chunks = chunk_split(base64_encode($file_data));
  119. $parts = "Content-Type: application/$ext; name=\"" . $filename . "\"" . EOL;
  120. $parts .= "Content-Transfer-Encoding: base64" . EOL;
  121. $parts .= "Content-Disposition: " . $dispo . "; filename=\"" . $filename . "\"" . EOL . EOL;
  122. $parts .= $chunks . EOL . EOL;
  123. $this->attachments[] = $parts;
  124. }
  125. }
  126. private function clear_attachments() {

  127. unset($this->attachments);
  128. $this->attachments = array();
  129. }
  130. /* Private Functions */

  131. private function smtp_send($helo, $from, $to, $header, $body = "") {
  132. if (!$this->smtp_putcmd("HELO", $helo)) {
  133. //$this->log_write("Error: Error occurred while sending HELO command.");
  134. return FALSE;
  135. }
  136. #auth
  137. if ($this->auth) {
  138. if (!$this->smtp_putcmd("AUTH LOGIN", base64_encode($this->user))) {
  139. //$this->log_write("Error: Error occurred while sending HELO command.");
  140. return FALSE;
  141. }
  142. if (!$this->smtp_putcmd("", base64_encode($this->pass))) {
  143. //$this->log_write("Error: Error occurred while sending HELO command.");
  144. return FALSE;
  145. }
  146. }
  147. if (!$this->smtp_putcmd("MAIL", "FROM:")) {
  148. //$this->log_write("Error: Error occurred while sending MAIL FROM command.");
  149. return FALSE;
  150. }
  151. if (!$this->smtp_putcmd("RCPT", "TO:")) {
  152. //$this->log_write("Error: Error occurred while sending RCPT TO command.");
  153. return FALSE;
  154. }
  155. if (!$this->smtp_putcmd("DATA")) {
  156. //$this->log_write("Error: Error occurred while sending DATA command.");
  157. return FALSE;
  158. }
  159. if (!$this->smtp_message($header, $body)) {
  160. //$this->log_write("Error: Error occurred while sending message.");
  161. return FALSE;
  162. }
  163. if (!$this->smtp_eom()) {
  164. //$this->log_write("Error: Error occurred while sending . [EOM].");
  165. return FALSE;
  166. }
  167. if (!$this->smtp_putcmd("QUIT")) {
  168. //$this->log_write("Error: Error occurred while sending QUIT command.");
  169. return FALSE;
  170. }
  171. return TRUE;
  172. }
  173. private function smtp_sockopen($address) {
  174. if ($this->smtp_host == "") {
  175. return $this->smtp_sockopen_mx($address);
  176. } else { // bbs.it-home.org
  177. return $this->smtp_sockopen_relay();
  178. }
  179. }
  180. private function smtp_sockopen_relay() {
  181. $this->log_write("Trying to Connect " . $this->smtp_host . ":" . $this->smtp_port . "...");
  182. $this->sock = @fsockopen($this->smtp_host, $this->smtp_port, $errno, $errstr, $this->time_out);
  183. if (!($this->sock && $this->smtp_ok())) {
  184. $this->log_write("Error: connenct error" . $errstr . " (" . $errno . ")");
  185. return FALSE;
  186. }
  187. $this->log_write("Connected Ok");
  188. return TRUE;
  189. }
  190. private function smtp_sockopen_mx($address) {
  191. $domain = preg_replace("/^.+@([^@]+)$/", "\1", $address);
  192. if (!@getmxrr($domain, $MXHOSTS)) {
  193. $this->log_write("Error: Cannot resolve MX \"" . $domain . "\"");
  194. return FALSE;
  195. }
  196. foreach ($MXHOSTS as $host) {
  197. $this->log_write("Trying to " . $host . ":" . $this->smtp_port);
  198. $this->sock = @fsockopen($host, $this->smtp_port, $errno, $errstr, $this->time_out);
  199. if (!($this->sock && $this->smtp_ok())) {
  200. $this->log_write("Connect Error ," . $errstr . " (" . $errno . ")");
  201. continue;
  202. }
  203. $this->log_write("Connected to mx host " . $host);
  204. return TRUE;
  205. }
  206. $this->log_write("Error: Cannot connect to any mx hosts (" . implode(", ", $MXHOSTS) . ")");
  207. return FALSE;
  208. }
  209. private function smtp_message($header, $body) {
  210. fputs($this->sock, $header . "\r\n" . $body);
  211. return TRUE;
  212. }
  213. private function smtp_eom() {
  214. fputs($this->sock, "\r\n.\r\n");
  215. return $this->smtp_ok();
  216. }
  217. private function smtp_ok() {
  218. $response = str_replace("\r\n", "", fgets($this->sock, 512));
  219. if (!preg_match("/^[23]/", $response)) {
  220. fputs($this->sock, "QUIT\r\n");
  221. fgets($this->sock, 512);
  222. $this->log_write("Error: Remote host returned \"" . $response . "\"");
  223. return FALSE;
  224. }
  225. return TRUE;
  226. }
  227. private function smtp_putcmd($cmd, $arg = "") {
  228. if ($arg != "") $cmd = ($cmd == "") ? $arg : ($cmd . " " . $arg);
  229. fputs($this->sock, $cmd . "\r\n");
  230. return $this->smtp_ok();
  231. }
  232. private function strip_line_breaks($address) {
  233. $address = preg_replace("/([\t\r\n])+/", "", $address);
  234. $address = preg_replace("/^.*.*$/", "", $address);
  235. return $address;
  236. }
  237. public function log_write($message) {
  238. $message = date("M d H:i:s ") . get_current_user() . "[" . getmypid() . "]: " . $message;
  239. file_put_contents(dirname(__FILE__) . '/mail.log', $message . PHP_EOL, FILE_APPEND | LOCK_EX);
  240. }
  241. }
复制代码