Mailer.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. if (!defined('BASEPATH')) exit('No direct script access allowed');
  3. require_once "PHPMail/PHPMailerAutoload.php";
  4. class Mailer
  5. {
  6. var $mail;
  7. public function __construct()
  8. {
  9. $this->mail = new PHPMailer();
  10. }
  11. public function set_config($config){
  12. $this->mail->IsSMTP(); // telling the class to use SMTP
  13. $this->mail->CharSet = "utf-8"; // 一定要設定 CharSet 才能正确处理中文
  14. $this->mail->SMTPDebug = 0; // enables SMTP debug information
  15. $this->mail->SMTPAuth = true; // enable SMTP authentication
  16. $this->mail->SMTPSecure = $config['smtp_secure']; // sets the prefix to the servier
  17. $this->mail->Host = $config['server']; // sets GMAIL as the SMTP server
  18. $this->mail->Port = $config['port']; // set the SMTP port for the GMAIL server
  19. $this->mail->Username = $config['sender'];
  20. $this->mail->Password = $config['secret_key'];
  21. $this->mail->AddReplyTo($config['sender']);
  22. $this->mail->SetFrom($config['sender']);
  23. $this->mail->isHTML(true);
  24. }
  25. public function add_recipient($recipient){
  26. $this->mail->AddAddress($recipient);
  27. }
  28. /**
  29. * 发送邮件
  30. * @param $recipient
  31. * @param $subject
  32. * @param $content
  33. * @param null $attachments
  34. * @return bool
  35. */
  36. public function send_email($recipient,$subject,$content,$attachments=null){
  37. $resp = array();
  38. $resp['code'] = "FAILED";
  39. try{
  40. if($recipient) {
  41. $this->mail->AddAddress($recipient);
  42. }
  43. $this->mail->Subject = $subject;
  44. $this->mail->Body = $content;
  45. if($attachments){
  46. if(is_array($attachments)){
  47. foreach($attachments as $k=>$val){
  48. $this->mail->addAttachment($val);
  49. }
  50. }else{
  51. $this->mail->addAttachment($attachments);
  52. }
  53. }
  54. if($this->mail->Send()) {
  55. $resp['code'] = "OK";
  56. }else{
  57. $resp['msg'] = $this->mail->ErrorInfo;
  58. }
  59. } catch (phpmailerException $e) {
  60. $resp['msg']=$e->errorMessage(); //Pretty error messages from PHPMailer
  61. } catch (Exception $e) {
  62. $resp['msg']=$e->errorMessage(); //Boring error messages from anything else!
  63. }
  64. return $resp;
  65. }
  66. }