V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
ioioioioioioi
V2EX  ›  PHP

PHPMailer 封装,让发邮件更简单

  •  1
     
  •   ioioioioioioi · 2017-02-21 13:25:32 +08:00 · 3029 次点击
    这是一个创建于 2861 天前的主题,其中的信息可能已经有所发展或是发生改变。

    mail 函数使用方法:

    \mail::to('[email protected]')
            ->subject('test subject')
            ->body('<p>hi world</p>')
            ->embed(['img/ban.png', 'img/about.png'])
            ->attach('img/test.pdf')
            ->send();
    
    

    如果没有 phpdotenv, 需要把相应的 env()改下。

    推荐封装一个 css_inline 函数。

    如果没有 Facade ,使用方法:

    
    $mailer = new \Classes\Mail;
    
    
    $mailer->to('[email protected]')
            ->subject('test subject')
            ->body('<p>hi world</p>')
            ->embed(['img/ban.png', 'img/about.png'])
            ->attach('img/test.pdf')
            ->send();
    
    

    源码

    <?php
    
    namespace Classes;
    
    class Mail
    {
        /**
         * Array to store email info
         * @var array
         */
        protected $info = [];
    
        /**
         * Initialize PHPMailer
         * Destory it after each email sent to avoid previous info left for next send
         * @return object PHPMailer
         */
        protected function mailer()
        {
            $mailer = new \PHPMailer;
    
            $mailer->isSMTP();                                      // Set mailer to use SMTP
            $mailer->Host     = env('mailer_host');                 // Specify main and backup SMTP servers
            $mailer->SMTPAuth = true;                               // Enable SMTP authentication
            $mailer->Username = env('mailer_user');                 // SMTP username
            $mailer->Password = env('mailer_password');             // SMTP password
            $mailer->Port     = env('mailer_port');
    
            $mailer->CharSet = 'UTF-8';
            $mailer->isHTML(true);
    
            return $mailer;
        }
    
        /**
         * Set email sender to $this->info['from']['email'] and $this->info['from']['name']
         * default is [email protected]
         * @param  string $email sender email
         * @param  string $name  sender name, optional
         * @return object        self object
         */
        public function from($email, $name = null)
        {
            $this->info['from']['email'] = $email;
            $this->info['from']['name'] = $name;
    
            return $this;
        }
    
        /**
         * Send email to addresses
         * @param  string|array $to send to email addresses
         * @return object     self object
         */
        public function to($to)
        {
            $this->info['to'] = $to;
    
            return $this;
        }
    
        /**
         * cc address. But actually sent separately, can be seen as set multiple to addresses
         * @param  string $cc email address
         * @return object     self object
         */
        public function cc($cc)
        {
            $this->info['cc'] = $cc;
    
            return $this;
        }
    
        /**
         * Set email reply to address
         * @param  string $email reply to email, stored as $this->info['replyTo']['email']
         * @param  string $name  reply to name, optional, $this->info['replyTo']['name']
         * @return object        self object
         */
        public function replyTo($email, $name = null)
        {
            $this->info['replyTo']['email'] = $email;
            $this->info['replyTo']['name'] = $name;
    
            return $this;
        }
    
        /**
         * Set email subject
         * @param  string $subject email subject, $this->info['subject']
         * @return object          self object
         */
        public function subject($subject)
        {
            $this->info['subject'] = $subject;
    
            return $this;
        }
    
        /**
         * Set email body
         * @param  string $body email body, $this->info['body']
         * @return object       self object
         */
        public function body($body)
        {
            $this->info['body'] = $body;
    
            return $this;
        }
    
        /**
         * Set email attachments
         * @param  string|array $file email attachments
         * @return object       self object
         */
        public function attach($file)
        {
            $this->info['attach'] = $file;
    
            return $this;
        }
    
        /**
         * Set embed images
         * embed 图片需要和 body 中的保持一致,会自动替换
         * @param  string|array $images images to embed
         * @return object         self object
         */
        public function embed($images)
        {
            $this->info['embed'] = $images;
    
            return $this;
        }
    
        /**
         * Send email
         * @return integer send email result, 1 for success
         */
        public function send()
        {
            // only send email when have to,subject and body
            if (@$this->info['to'] and @$this->info['subject'] and @$this->info['body']) {
    
                // get initialized mailer
                $mailer = $this->mailer();
    
                $this->localSend();
    
                if (@$this->info['from']['email']) { // use offered sender email&name
                    $mailer->setFrom($this->info['from']['email'], @$this->info['from']['name']);
                } else { // use default sender email and name
                    $mailer->setFrom('[email protected]', 'Send Name');
                }
    
                // set email to addresses
                $to = (array) $this->info['to'];
                foreach ($to as $one) {
                    $mailer->addAddress($one);
                }
    
                // set email cc address
                $mailer->addCC(@$this->info['cc']);
    
                if (@$this->info['replyTo']['email']) { // use offered reply to address&name
                    $mailer->addReplyTo(@$this->info['replyTo']['email'], @$this->info['replyTo']['name']);
                }
    
                // $body = css_inline($this->info['body']);
                $body = $this->info['body'];
     
                // set attachments
                if (@$this->info['attach']) {
                    $attach = (array) $this->info['attach'];
                    foreach ($attach as $oneAttach) {
                        $mailer->addAttachment($oneAttach);
                    }
                }
    
                // set embed images
                if (@$this->info['embed']) {
                    $embed = (array) $this->info['embed'];
                    foreach ($embed as $oneImage) {
                        $mailer->AddEmbeddedImage($oneImage, $oneImage);
    
                        $cid[] = 'cid:' . $oneImage;
                    }
    
                    $body = str_replace($embed, $cid, $body);
                }
    
                $mailer->Subject = $this->info['subject'];
                $mailer->Body    = $body;
    
                // flush used info, or next send email would be polluted
                $this->info = [];
    
                // send email and return success mark: 1 for success
                return $mailer->send();
            }
        }
    
        /**
         * if in dev mode, send all addresses to mailer_recipient
         */
        public function localSend()
        {
            if (dev()) { //使用你自己相应的判断环境的函数
                $email = env('mailer_recipient');
    
                $this->info['to'] = array_fill(0, count((array) $this->info['to']), $email);
    
                $this->info['cc'] = @$this->info['cc'] ? $email : null;
            }
        }
    }
    
    6 条回复    2017-02-23 12:24:15 +08:00
    param
        1
    param  
       2017-02-21 13:30:33 +08:00   ❤️ 1
    被 java @
    被 Python @
    被 ruby @
    今天终于被 php @了
    Troevil
        2
    Troevil  
       2017-02-21 13:33:31 +08:00
    @param 贴这个代码还能 @到你?, 这算是 v 站的 bug 了吧
    liuxu
        3
    liuxu  
       2017-02-21 13:34:46 +08:00
    @param 你的 id 我服
    param
        4
    param  
       2017-02-21 13:35:14 +08:00
    @Troevil 故意注册的用户名哈哈
    ioioioioioioi
        5
    ioioioioioioi  
    OP
       2017-02-21 13:37:41 +08:00
    @liuxu 我纳闷他什么意思呢,原来这个样子。
    Jakesoft
        6
    Jakesoft  
       2017-02-23 12:24:15 +08:00
    @param 喜闻乐见
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   945 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 22:51 · PVG 06:51 · LAX 14:51 · JFK 17:51
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.