Home Backend Development PHP Tutorial SMTP email sending class written in PHP

SMTP email sending class written in PHP

Jul 25, 2016 am 08:54 AM

  1. $smtpserver = "*****";
  2. $smtpserverport = 25;
  3. $smtpuser = "******";
  4. $smtppass = "***** **";
  5. $smtp = new smtp($smtpserver, $smtpserverport, true, $smtpuser, $smtppass); //A true here means that authentication is used, otherwise authentication is not used.
  6. $smtp-> ;debug = false;
  7. //$emailtype = "HTML";
  8. for ($i=0; $i<5; $i++) {
  9. $smtp->sendmail("*****", "* *****", "Hello world!","This is only a test!");
  10. }
  11. echo "A total of $i emails were sent! ";
  12. ?>
Copy code

The following is the implementation of the specific class.

  1. class smtp {

  2. /* Public Variables */
  3. var $smtp_port;
  4. var $time_out;
  5. var $host_name;
  6. var $log_file;
  7. var $relay_host;
  8. var $debug;
  9. var $auth;
  10. var $user;
  11. var $pass;
  12. /* Private Variables */
  13. var $sock;
  14. /* Constractor */
  15. function smtp($relay_host = "", $smtp_port = 25, $auth = false, $user, $pass)
  16. {
  17. $this->debug = false;
  18. $this->smtp_port = $smtp_port;
  19. $this->relay_host = $relay_host;
  20. $this->time_out = 30; //is used in fsockopen()
  21. $this->auth = $auth; //auth
  22. $this->user = $user;
  23. $this->pass = $pass;
  24. $this->host_name = "localhost"; //is used in HELO command
  25. $this->log_file = "";
  26. $this->sock = false;
  27. }
  28. /* Main Function */
  29. function sendmail($to, $from, $subject = "", $body = "", $mailtype= "", $cc = "", $bcc = "", $additional_headers = "")
  30. {
  31. $mail_from = $this->get_address($this->strip_comment($from));
  32. $body = ereg_replace("(^|( ))(.)", "1.3", $body);
  33. $header .= "MIME-Version:1.0 ";
  34. if ($mailtype == "HTML") {
  35. $header .= "Content-Type:text/html ";
  36. }
  37. $header .= "To: " . $to . " ";
  38. if ($cc != "") {
  39. $header .= "Cc: " . $cc . " ";
  40. }
  41. $header .= "From: $from<" . $from . ">; ";
  42. $header .= "Subject: " . $subject . " ";
  43. $header .= $additional_headers;
  44. $header .= "Date: " . date("r") . " ";
  45. $header .= "X-Mailer:By Redhat (PHP/" . phpversion() . ") ";
  46. list($msec, $sec) = explode(" ", microtime());
  47. $header .= "Message-ID: <" . date("YmdHis", $sec) . "." . ($msec * 1000000) . "." . $mail_from . ">; ";
  48. $TO = explode(",", $this->strip_comment($to));
  49. if ($cc != "") {
  50. $TO = array_merge($TO, explode(",", $this->strip_comment($cc)));
  51. }
  52. if ($bcc != "") {
  53. $TO = array_merge($TO, explode(",", $this->strip_comment($bcc)));
  54. }
  55. $sent = true;
  56. foreach ($TO as $rcpt_to) {
  57. $rcpt_to = $this->get_address($rcpt_to);
  58. if (!$this->smtp_sockopen($rcpt_to)) {
  59. $this->log_write("Error: Cannot send email to " . $rcpt_to . " ");
  60. $sent = false;
  61. continue;
  62. }
  63. if ($this->smtp_send($this->host_name, $mail_from, $rcpt_to, $header, $body)) {
  64. $this->log_write("E-mail has been sent to <" . $rcpt_to . ">; ");
  65. } else {
  66. $this->log_write("Error: Cannot send email to <" . $rcpt_to . ">; ");
  67. $sent = false;
  68. }
  69. fclose($this->sock);
  70. $this->log_write("Disconnected from remote host ");
  71. }
  72. return $sent;
  73. }

  74. /* Private Functions */

  75. function smtp_send($helo, $from, $to, $header, $body = "")
  76. {
  77. if (!$this->smtp_putcmd("HELO", $helo)) {
  78. return $this->smtp_error("sending HELO command");
  79. }
  80. // auth
  81. if ($this->auth) {
  82. if (!$this->smtp_putcmd("AUTH LOGIN", base64_encode($this->user))) {
  83. return $this->smtp_error("sending HELO command");
  84. }
  85. if (!$this->smtp_putcmd("", base64_encode($this->pass))) {
  86. return $this->smtp_error("sending HELO command");
  87. }
  88. }
  89. if (!$this->smtp_putcmd("MAIL", "FROM:<" . $from . ">;")) {
  90. return $this->smtp_error("sending MAIL FROM command");
  91. }
  92. if (!$this->smtp_putcmd("RCPT", "TO:<" . $to . ">;")) {
  93. return $this->smtp_error("sending RCPT TO command");
  94. }
  95. if (!$this->smtp_putcmd("DATA")) {
  96. return $this->smtp_error("sending DATA command");
  97. }
  98. if (!$this->smtp_message($header, $body)) {
  99. return $this->smtp_error("sending message");
  100. }
  101. if (!$this->smtp_eom()) {
  102. return $this->smtp_error("sending ;;.;; [EOM]");
  103. }
  104. if (!$this->smtp_putcmd("QUIT")) {
  105. return $this->smtp_error("sending QUIT command");
  106. }
  107. return true;
  108. }
  109. function smtp_sockopen($address)
  110. {
  111. if ($this->relay_host == "") {
  112. return $this->smtp_sockopen_mx($address);
  113. } else {
  114. return $this->smtp_sockopen_relay();
  115. }
  116. }
  117. function smtp_sockopen_relay()
  118. {
  119. $this->log_write("Trying to " . $this->relay_host . ":" . $this->smtp_port . " ");
  120. $this->sock = @fsockopen($this->relay_host, $this->smtp_port, $errno, $errstr, $this->time_out);
  121. if (!($this->sock && $this->smtp_ok())) {
  122. $this->log_write("Error: Cannot connenct to relay host " . $this->relay_host . " ");
  123. $this->log_write("Error: " . $errstr . " (" . $errno . ") ");
  124. return false;
  125. }
  126. $this->log_write("Connected to relay host " . $this->relay_host . " ");
  127. return true;;
  128. }
  129. function smtp_sockopen_mx($address)
  130. {
  131. $domain = ereg_replace("^.+@([^@]+)$", "1", $address);
  132. if (!@getmxrr($domain, $MXHOSTS)) {
  133. $this->log_write("Error: Cannot resolve MX "" . $domain . "" ");
  134. return false;
  135. }
  136. foreach ($MXHOSTS as $host) {
  137. $this->log_write("Trying to " . $host . ":" . $this->smtp_port . " ");
  138. $this->sock = @fsockopen($host, $this->smtp_port, $errno, $errstr, $this->time_out);
  139. if (!($this->sock && $this->smtp_ok())) {
  140. $this->log_write("Warning: Cannot connect to mx host " . $host . " ");
  141. $this->log_write("Error: " . $errstr . " (" . $errno . ") ");
  142. continue;
  143. }
  144. $this->log_write("Connected to mx host " . $host . " ");
  145. return true;
  146. }
  147. $this->log_write("Error: Cannot connect to any mx hosts (" . implode(", ", $MXHOSTS) . ") ");
  148. return false;
  149. }
  150. function smtp_message($header, $body)
  151. {
  152. fputs($this->sock, $header . " " . $body);
  153. $this->smtp_debug(">; " . str_replace(" ", " " . ">; ", $header . " >; " . $body . " >; "));
  154. return true;
  155. }
  156. function smtp_eom()
  157. {
  158. fputs($this->sock, " . ");
  159. $this->smtp_debug(". [EOM] ");
  160. return $this->smtp_ok();
  161. }
  162. function smtp_ok()
  163. {
  164. $response = str_replace(" ", "", fgets($this->sock, 512));
  165. $this->smtp_debug($response . " ");
  166. if (!ereg("^[23]", $response)) {
  167. fputs($this->sock, "QUIT ");
  168. fgets($this->sock, 512);
  169. $this->log_write("Error: Remote host returned "" . $response . "" ");
  170. return false;
  171. }
  172. return true;
  173. }
  174. function smtp_putcmd($cmd, $arg = "")
  175. {
  176. if ($arg != "") {
  177. if ($cmd == "") $cmd = $arg;
  178. else $cmd = $cmd . " " . $arg;
  179. }
  180. fputs($this->sock, $cmd . " ");
  181. $this->smtp_debug(">; " . $cmd . " ");
  182. return $this->smtp_ok();
  183. }
  184. function smtp_error($string)
  185. {
  186. $this->log_write("Error: Error occurred while " . $string . ". ");
  187. return false;
  188. }
  189. function log_write($message)
  190. {
  191. $this->smtp_debug($message);
  192. if ($this->log_file == "") {
  193. return true;
  194. }
  195. $message = date("M d H:i:s ") . get_current_user() . "[" . getmypid() . "]: " . $message;
  196. if (!@file_exists($this->log_file) || !($fp = @fopen($this->log_file, "a"))) {
  197. $this->smtp_debug("Warning: Cannot open log file "" . $this->log_file . "" ");
  198. return false;;
  199. }
  200. flock($fp, LOCK_EX);
  201. fputs($fp, $message);
  202. fclose($fp);
  203. return true;
  204. }
  205. function strip_comment($address)
  206. {
  207. $comment = "([^()]*)";
  208. while (ereg($comment, $address)) {
  209. $address = ereg_replace($comment, "", $address);
  210. }
  211. return $address;
  212. }
  213. function get_address($address)
  214. {
  215. $address = ereg_replace("([ ])+", "", $address);
  216. $address = ereg_replace("^.*<(.+)>;.*$", "1", $address);
  217. return $address;
  218. }
  219. function smtp_debug($message)
  220. {
  221. if ($this->debug) {
  222. echo $message . ";";
  223. }
  224. }
  225. }
  226. ?>

复制代码


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

See all articles