Home Backend Development PHP Tutorial PHP supports sending classes for sending HTML format emails

PHP supports sending classes for sending HTML format emails

Jul 25, 2016 am 08:43 AM

  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) < 6){
  139. $this->_errorMessage = "parameters are required";
  140. return false;
  141. }
  142. $this->_from = $config['from'];
  143. $this->_to = $config['to'];
  144. $this->_subject = $config['subject'];
  145. $this->_body = $config['body'];
  146. $this->_userName = $config['username'];
  147. $this->_password = $config['password'];
  148. if(isset($config['isHTML'])){
  149. $this->_isHTML = $config['isHTML'];
  150. }
  151. return true;
  152. }
  153. /**
  154. * Send email
  155. * @access public
  156. * @return boolean
  157. */
  158. public function sendMail() {
  159. $command = $this->getCommand();
  160. $this->socket();
  161. foreach ($command as $value) {
  162. if($this->sendCommand($value[0], $value[1])) {
  163. continue;
  164. }
  165. else{
  166. return false;
  167. }
  168. }
  169. $this->close(); //其实这里也没必要关闭,smtp命令:QUIT发出之后,服务器就关闭了连接,本地的socket资源会自动释放
  170. echo 'Mail OK!';
  171. return true;
  172. }
  173. /**
  174. * Return error message
  175. * @return string
  176. */
  177. public function error(){
  178. if(!isset($this->_errorMessage)) {
  179. $this->_errorMessage = "";
  180. }
  181. return $this->_errorMessage;
  182. }
  183. /**
  184. * Return mail command
  185. * @access protected
  186. * @return array
  187. */
  188. protected function getCommand() {
  189. if($this->_isHTML) {
  190. $mail = "MIME-Version:1.0rn";
  191. $mail .= "Content-type:text/html;charset=utf-8rn";
  192. $mail .= "FROM:test<" . $this->_from . ">rn";
  193. $mail .= "TO:<" . $this->_to . ">rn";
  194. $mail .= "Subject:" . $this->_subject ."rnrn";
  195. $mail .= $this->_body . "rn.rn";
  196. }
  197. else{
  198. $mail = "FROM:test<" . $this->_from . ">rn";
  199. $mail .= "TO:<" . $this->_to . ">rn";
  200. $mail .= "Subject:" . $this->_subject ."rnrn";
  201. $mail .= $this->_body . "rn.rn";
  202. }
  203. $command = array(
  204. array("HELO sendmailrn", 250),
  205. array("AUTH LOGINrn", 334),
  206. array(base64_encode($this->_userName) . "rn", 334),
  207. array(base64_encode($this->_password) . "rn", 235),
  208. array("MAIL FROM:<" . $this->_from . ">rn", 250),
  209. array("RCPT TO:<" . $this->_to . ">rn", 250),
  210. array("DATArn", 354),
  211. array($mail, 250),
  212. array("QUITrn", 221)
  213. );
  214. return $command;
  215. }
  216. /**
  217. * @access protected
  218. * @param string $command SMTP command sent to the server
  219. * @param int $code Do you expect the response returned by the server?
  220. * @param boolean
  221. */
  222. protected function sendCommand($command, $code) {
  223. echo 'Send command:' . $command . ',expected code:' . $code . '
    ';
  224. //发送命令给服务器
  225. try{
  226. if(socket_write($this->_socket, $command, strlen($command))){
  227. //读取服务器返回
  228. $data = trim(socket_read($this->_socket, 1024));
  229. echo 'response:' . $data . '

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

PHP, HTML


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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles