search
HomeBackend DevelopmentPHP TutorialSMTP email sending class written in PHP

  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 $smtp->sendmail("*****", "* *****", "Hello world!","This is only a test!");
  9. }
  10. echo "A total of $i emails were sent! ";
  11. ?>
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; ";
  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: ; ";
  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 ; ");
  65. } else {
  66. $this->log_write("Error: Cannot send email 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:;")) {
  90. return $this->smtp_error("sending MAIL FROM command");
  91. }
  92. if (!$this->smtp_putcmd("RCPT", "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
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
Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

Give an example of how to store a user's name in a PHP session.Give an example of how to store a user's name in a PHP session.Apr 26, 2025 am 12:03 AM

Tostoreauser'snameinaPHPsession,startthesessionwithsession_start(),thenassignthenameto$_SESSION['username'].1)Usesession_start()toinitializethesession.2)Assigntheuser'snameto$_SESSION['username'].Thisallowsyoutoaccessthenameacrossmultiplepages,enhanc

What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),