PHPMailer 封装,让发邮件更简单

2017-02-21 13:25:32 +08:00
 ioioioioioioi

mail 函数使用方法:

\mail::to('tom@example.com')
        ->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('tom@example.com')
        ->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 support@example.com
     * @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('support@example.com', '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;
        }
    }
}
3013 次点击
所在节点    PHP
6 条回复
param
2017-02-21 13:30:33 +08:00
被 java @
被 Python @
被 ruby @
今天终于被 php @了
Troevil
2017-02-21 13:33:31 +08:00
@param 贴这个代码还能 @到你?, 这算是 v 站的 bug 了吧
liuxu
2017-02-21 13:34:46 +08:00
@param 你的 id 我服
param
2017-02-21 13:35:14 +08:00
@Troevil 故意注册的用户名哈哈
ioioioioioioi
2017-02-21 13:37:41 +08:00
@liuxu 我纳闷他什么意思呢,原来这个样子。
Jakesoft
2017-02-23 12:24:15 +08:00
@param 喜闻乐见

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/342029

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX