Mailer.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. try{
  38. if($recipient) {
  39. $this->mail->AddAddress($recipient);
  40. }
  41. $this->mail->Subject = $subject;
  42. $this->mail->Body = $content;
  43. if($attachments){
  44. if(is_array($attachments)){
  45. foreach($attachments as $k=>$val){
  46. $this->mail->addAttachment($val);
  47. }
  48. }else{
  49. $this->mail->addAttachment($attachments);
  50. }
  51. }
  52. if($this->mail->Send()) {
  53. return true;
  54. }else{
  55. show_error($this->mail->ErrorInfo);
  56. return false;
  57. }
  58. } catch (phpmailerException $e) {
  59. show_error($e->errorMessage(),500); //Pretty error messages from PHPMailer
  60. } catch (Exception $e) {
  61. show_error($e->getMessage(),500); //Boring error messages from anything else!
  62. }
  63. }
  64. }