search
HomeBackend DevelopmentPHP TutorialPHP supports sending classes for sending HTML format emails

  1. /**
  2. * Email sending class
  3. * Supports sending plain text emails and HTML format emails
  4. * @example
  5. * $config = array(
  6. * "from" => "*****",
  7. * "to" = > "***",
  8. * "subject" => "test",
  9. * "body" => "test",
  10. * "username" => "* **",
  11. * "password" => "****",
  12. * "isHTML" => true
  13. * );
  14. *
  15. * $mail = new MySendMail();
  16. *
  17. * $mail ->setServer("smtp.126.com");
  18. *
  19. * $mail->setMailInfo($config);
  20. * if(!$mail->sendMail()) {
  21. * echo $mail- >error();
  22. * return 1;
  23. * }
  24. */
  25. class MySendMail{
  26. /**
  27. * @var Mail transfer agent username
  28. * @access private
  29. */
  30. private $_userName;
  31. /**
  32. * @var Mail transfer agent password
  33. * @access private
  34. */
  35. private $_password;
  36. /**
  37. * @var Mail transfer proxy server address
  38. * @access protected
  39. */
  40. protected $_sendServer;
  41. /**
  42. * @var Mail transfer proxy server port
  43. * @access protected
  44. */
  45. protected $_port=25;
  46. /**
  47. * @var sender
  48. * @access protected
  49. */
  50. protected $_from;
  51. /**
  52. * @var recipient
  53. * @access protected
  54. */
  55. protected $_to;
  56. /**
  57. * @var theme
  58. * @access protected
  59. */
  60. protected $_subject;
  61. /**
  62. * @var Email text
  63. * @access protected
  64. */
  65. protected $_body;
  66. /**
  67. * @var Whether it is an email in HTML format
  68. * @access protected
  69. */
  70. protected $_isHTML=true;
  71. /**
  72. * @var socket resource
  73. * @access protected
  74. */
  75. protected $_socket;
  76. /**
  77. * @var error message
  78. * @access protected
  79. */
  80. protected $_errorMessage;
  81. public function __construct($from="", $to="", $subject="", $body="", $server="", $username="", $password="",$isHTML="", $port="") {
  82. if(!empty($from)){
  83. $this->_from = $from;
  84. }
  85. if(!empty($to)){
  86. $this->_to = $to;
  87. }
  88. if(!empty($subject)){
  89. $this->_subject = $subject;
  90. }
  91. if(!empty($body)){
  92. $this->_body = $body;
  93. }
  94. if(!empty($isHTML)){
  95. $this->_isHTML = $isHTML;
  96. }
  97. if(!empty($server)){
  98. $this->_sendServer = $server;
  99. }
  100. if(!empty($port)){
  101. $this->_port = $port;
  102. }
  103. if(!empty($username)){
  104. $this->_userName = $username;
  105. }
  106. if(!empty($password)){
  107. $this->_password = $password;
  108. }
  109. }
  110. /**
  111. * Set up the mail transfer proxy
  112. * @param string $server The IP or domain name of the proxy server
  113. * @param int $port The port of the proxy server, SMTP default port 25
  114. * @param int $localPort The local port
  115. * @return boolean
  116. */
  117. public function setServer($server, $port=25) {
  118. if(!isset($server) || empty($server) || !is_string($server)) {
  119. $this->_errorMessage = "first one is an invalid parameter";
  120. return false;
  121. }
  122. if(!is_numeric($port)){
  123. $this->_errorMessage = "first two is an invalid parameter";
  124. return false;
  125. }
  126. $this->_sendServer = $server;
  127. $this->_port = $port;
  128. return true;
  129. }
  130. /**
  131. * Set up email
  132. * @access public
  133. * @param array $config Email configuration information
  134. * Contains email sender, recipient, subject, content, verification information of mail transfer agent
  135. * @return boolean
  136. */
  137. public function setMailInfo($config) {
  138. if(!is_array($config) || count($config) $this->_errorMessage = "parameters are required";
  139. return false;
  140. }
  141. $this->_from = $config['from'];
  142. $this->_to = $config['to'];
  143. $this->_subject = $config['subject'];
  144. $this->_body = $config['body'];
  145. $this->_userName = $config['username'];
  146. $this->_password = $config['password'];
  147. if(isset($config['isHTML'])){
  148. $this->_isHTML = $config['isHTML'];
  149. }
  150. return true;
  151. }
  152. /**
  153. * Send email
  154. * @access public
  155. * @return boolean
  156. */
  157. public function sendMail() {
  158. $command = $this->getCommand();
  159. $this->socket();
  160. foreach ($command as $value) {
  161. if($this->sendCommand($value[0], $value[1])) {
  162. continue;
  163. }
  164. else{
  165. return false;
  166. }
  167. }
  168. $this->close(); //其实这里也没必要关闭,smtp命令:QUIT发出之后,服务器就关闭了连接,本地的socket资源会自动释放
  169. echo 'Mail OK!';
  170. return true;
  171. }
  172. /**
  173. * Return error message
  174. * @return string
  175. */
  176. public function error(){
  177. if(!isset($this->_errorMessage)) {
  178. $this->_errorMessage = "";
  179. }
  180. return $this->_errorMessage;
  181. }
  182. /**
  183. * Return mail command
  184. * @access protected
  185. * @return array
  186. */
  187. protected function getCommand() {
  188. if($this->_isHTML) {
  189. $mail = "MIME-Version:1.0rn";
  190. $mail .= "Content-type:text/html;charset=utf-8rn";
  191. $mail .= "FROM:test_from . ">rn";
  192. $mail .= "TO:_to . ">rn";
  193. $mail .= "Subject:" . $this->_subject ."rnrn";
  194. $mail .= $this->_body . "rn.rn";
  195. }
  196. else{
  197. $mail = "FROM:test_from . ">rn";
  198. $mail .= "TO:_to . ">rn";
  199. $mail .= "Subject:" . $this->_subject ."rnrn";
  200. $mail .= $this->_body . "rn.rn";
  201. }
  202. $command = array(
  203. array("HELO sendmailrn", 250),
  204. array("AUTH LOGINrn", 334),
  205. array(base64_encode($this->_userName) . "rn", 334),
  206. array(base64_encode($this->_password) . "rn", 235),
  207. array("MAIL FROM:_from . ">rn", 250),
  208. array("RCPT TO:_to . ">rn", 250),
  209. array("DATArn", 354),
  210. array($mail, 250),
  211. array("QUITrn", 221)
  212. );
  213. return $command;
  214. }
  215. /**
  216. * @access protected
  217. * @param string $command SMTP command sent to the server
  218. * @param int $code Do you expect the response returned by the server?
  219. * @param boolean
  220. */
  221. protected function sendCommand($command, $code) {
  222. echo 'Send command:' . $command . ',expected code:' . $code . '
    ';
  223. //发送命令给服务器
  224. try{
  225. if(socket_write($this->_socket, $command, strlen($command))){
  226. //读取服务器返回
  227. $data = trim(socket_read($this->_socket, 1024));
  228. echo 'response:' . $data . '

    ';
  229. if($data) {
  230. $pattern = "/^".$code."/";
  231. if(preg_match($pattern, $data)) {
  232. return true;
  233. }
  234. else{
  235. $this->_errorMessage = "Error:" . $data . "|**| command:";
  236. return false;
  237. }
  238. }
  239. else{
  240. $this->_errorMessage = "Error:" . socket_strerror(socket_last_error());
  241. return false;
  242. }
  243. }
  244. else{
  245. $this->_errorMessage = "Error:" . socket_strerror(socket_last_error());
  246. return false;
  247. }
  248. }catch(Exception $e) {
  249. $this->_errorMessage = "Error:" . $e->getMessage();
  250. }
  251. }
  252. /**
  253. * Establish a network connection to the server
  254. * @access private
  255. * @return boolean
  256. */
  257. private function socket() {
  258. if(!function_exists("socket_create")) {
  259. $this->_errorMessage = "extension php-sockets must be enabled";
  260. return false;
  261. }
  262. //创建socket资源
  263. $this->_socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'));
  264. if(!$this->_socket) {
  265. $this->_errorMessage = socket_strerror(socket_last_error());
  266. return false;
  267. }
  268. //连接服务器
  269. if(!socket_connect($this->_socket, $this->_sendServer, $this->_port)) {
  270. $this->_errorMessage = socket_strerror(socket_last_error());
  271. return false;
  272. }
  273. socket_read($this->_socket, 1024);
  274. return true;
  275. }
  276. /**
  277. * 关闭socket
  278. * @access private
  279. * @return boolean
  280. */
  281. private function close() {
  282. if(isset($this->_socket) && is_object($this->_socket)) {
  283. $this->_socket->close();
  284. return true;
  285. }
  286. $this->_errorMessage = "no resource can to be close";
  287. return false;
  288. }
  289. }
  290. /**************************** Test ***********************************/
  291. $config = array(
  292. "from" => "********@163.com",
  293. "to" => "******@163.com",
  294. "subject" => "test",
  295. "body" => "test",
  296. "username" => "******",
  297. "password" => "password",
  298. );
  299. $mail = new MySendMail();
  300. $mail->setServer("smtp.163.com");
  301. $mail->setMailInfo($config);
  302. if(!$mail->sendMail()){
  303. echo $mail->error();
  304. return 1;
  305. }
复制代码

PHP, HTML


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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

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 Article

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor