Welcome 微信登录

首页 / 网页编程 / PHP / php如何发送带附件的邮件

php如何发送带附件的邮件2014-08-05 傲雪星枫 emailclass.php[php] view plaincopyprint?01.<? 02.class CMailFile { 03. 04. var $subject; 05. var $addr_to; 06. var $text_body; 07. var $text_encoded; 08. var $mime_headers; 09. var $mime_boundary = "--==================_846811060==_"; 10. var $smtp_headers; 11. 12. function CMailFile($subject,$to,$from,$msg,$filename,$downfilename,$mimetype = "application/octet-stream",$mime_filename = false) { 13. $this->subject = $subject; 14. $this->addr_to = $to; 15. $this->smtp_headers = $this->write_smtpheaders($from); 16. $this->text_body = $this->write_body($msg); 17. $this->text_encoded = $this->attach_file($filename,$downfilename,$mimetype,$mime_filename); 18. $this->mime_headers = $this->write_mimeheaders($filename, $mime_filename); 19. } 20. 21. function attach_file($filename,$downfilename,$mimetype,$mime_filename) { 22. $encoded = $this->encode_file($filename); 23. if ($mime_filename) $filename = $mime_filename; 24. $out = "--" . $this->mime_boundary . " "; 25. $out = $out . "Content-type: " . $mimetype . "; name="$filename"; "; 26. $out = $out . "Content-Transfer-Encoding: base64 "; 27. $out = $out . "Content-disposition: attachment; filename="$downfilename" "; 28. $out = $out . $encoded . " "; 29. $out = $out . "--" . $this->mime_boundary . "--" . " "; 30. return $out; 31. } 32. 33. function encode_file($sourcefile) { 34. if (is_readable($sourcefile)) { 35. $fd = fopen($sourcefile, "r"); 36. $contents = fread($fd, filesize($sourcefile)); 37. $encoded = chunk_split(base64_encode($contents)); 38. fclose($fd); 39. } 40. return $encoded; 41. } 42. 43. function sendfile() { 44. $headers = $this->smtp_headers . $this->mime_headers; 45. $message = $this->text_body . $this->text_encoded; 46. mail($this->addr_to,$this->subject,$message,$headers); 47. } 48. 49. function write_body($msgtext) { 50. $out = "--" . $this->mime_boundary . " "; 51. $out = $out . "Content-Type: text/plain; charset="us-ascii" "; 52. $out = $out . $msgtext . " "; 53. return $out; 54. } 55. 56. function write_mimeheaders($filename, $mime_filename) { 57. if ($mime_filename) $filename = $mime_filename; 58. $out = "MIME-version: 1.0 "; 59. $out = $out . "Content-type: multipart/mixed; "; 60. $out = $out . "boundary="$this->mime_boundary" "; 61. $out = $out . "Content-transfer-encoding: 7BIT "; 62. $out = $out . "X-attachments: $filename; "; 63. return $out; 64. } 65. 66. function write_smtpheaders($addr_from) { 67. $out = "From: $addr_from "; 68. $out = $out . "Reply-To: $addr_from "; 69. $out = $out . "X-Mailer: PHP3 "; 70. $out = $out . "X-Sender: $addr_from "; 71. return $out; 72. } 73.} 74. 75./*用法 - 例如:mimetype 为 "image/gif" 76. $mailfile = new CMailFile($subject,$sendto,$replyto,$message,$filename,$mimetype); 77. $mailfile->sendfile(); 78. 79. $subject -- 主题 80. $sendto -- 收信人地址 81. $replyto -- 回复地址 82. $message -- 信件内容 83. $filename -- 附件文件名 84. $downfilename -- 下載的文件名 85. $mimetype -- mime类型 86.*/ 87.?>