Home Backend Development PHP Tutorial php socket uses smtp to send emails with attachments

php socket uses smtp to send emails with attachments

Jul 25, 2016 am 08:54 AM

  1. /**

  2. * php socket smtp send email
  3. * edit: bbs.it-home.org
  4. */

  5. //define("SOL", "n");

  6. define(" EOL", "rn");
  7. define("SMTP_HOST", "smtp.163.com");//SMTP server
  8. define("SMTP_PORT", "25");//SMTP server port
  9. define("SMTP_USER ", "");//The user account of the SMTP server
  10. define("SMTP_PASS", "");//The user password of the SMTP server

  11. $from = "";//SMTP User email address of the server

  12. $to = "";//Who you want to send to can separate multiple emails with commas
  13. $cc = "";
  14. $bcc = "";

  15. $subject= "This is an email with attachments sent by PHP";//Many clients will have garbled email subject, so convert it

  16. $body = "This is an email sending program with attachments
    Do you see it? , the HTM tag is displayed here;Please click the link ".date('Y-m-d H:i:s');//Email content
  17. $smtp = new smtp(SMTP_HOST,SMTP_PORT,SMTP_USER,SMTP_PASS, true);//One of these true means authentication is used, otherwise authentication is not used.
  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. /*Contractor */

  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("/(^|(rn))(\.)/", "", $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<" . $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: <" . date("YmdHis", $sec) . "." . ($msec * 1000000) . "." . $from . ">" . 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 <" . $rcpt_to . ">");
  104. } else {
  105. $this->log_write("Error: Cannot send email to <" . $rcpt_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:<" . $from . ">")) {
  148. //$this->log_write("Error: Error occurred while sending MAIL FROM command.");
  149. return FALSE;
  150. }
  151. if (!$this->smtp_putcmd("RCPT", "TO:<" . $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 . "rn" . $body);
  211. return TRUE;
  212. }
  213. private function smtp_eom() {
  214. fputs($this->sock, "rn.rn");
  215. return $this->smtp_ok();
  216. }
  217. private function smtp_ok() {
  218. $response = str_replace("rn", "", fgets($this->sock, 512));
  219. if (!preg_match("/^[23]/", $response)) {
  220. fputs($this->sock, "QUITrn");
  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 . "rn");
  230. return $this->smtp_ok();
  231. }
  232. private function strip_line_breaks($address) {
  233. $address = preg_replace("/([trn])+/", "", $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. }

复制代码


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

Video Face Swap

Video Face Swap

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

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)

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

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