【问题标题】:PHP create MIME message for Gmail APIPHP 为 Gmail API 创建 MIME 消息
【发布时间】:2016-03-11 13:48:51
【问题描述】:

我正在尝试使用 PHP 通过 Gmail API 发送电子邮件。文档说我需要创建一个 MIME 消息,将整个内容编码为 base64url 字符串,然后将此字符串设置为 Google_Service_Gmail_Message 的“原始”属性。

在 PHP 中创建此 MIME 消息的最佳方式是什么?我也在使用 Laravel 5.1,以防有人知道使用 Laravel 的便捷方法。以下是我所指的 Gmail API 文档:

https://developers.google.com/gmail/api/guides/sending

【问题讨论】:

    标签: php gmail


    【解决方案1】:

    我想我是使用 Laravel 附带的底层 Swift Mailer 来完成这项工作的:

    $message = \Swift_Message::newInstance();
    $message->setTo(['test@example.com'=>'Test Name']);
    $message->setBody('Here is my body');
    $message->setSubject('Here is my subject');
    echo $message->toString();
    

    这个输出:

    Message-ID: 
    Date: Mon, 07 Dec 2015 02:38:30 +0000
    Subject: Here is my subject
    From: 
    To: Test Name 
    MIME-Version: 1.0
    Content-Type: text/plain; charset=utf-8
    Content-Transfer-Encoding: quoted-printable
    
    Here is my body
    

    【讨论】:

      【解决方案2】:

      我得到了它的工作..,使用 imap_mail_compose

       string imap_mail_compose ( array $envelope , array $body )
      

      example-1 @: http://php.net/manual/en/function.imap-mail-compose.php

       $envelope["from"]= "foo@gmail.com";
       $envelope["to"]  = "foo3@example.com";
       $envelope["cc"]  = "bar@example.com";
       $envelope["subject"]  = "Testing..";
      
       $part1["type"] = TYPETEXT;
       $part1["subtype"] = "plain";
       $part1["description"] = "description3";
       $part1["contents.data"] = "contents.data3\n\n\n\t";
      
       $body[1] = $part1;
      
       $mime = imap_mail_compose ($envelope , $body);
       $mime = rtrim(strtr(base64_encode($mime), '+/', '-_'), '=');
       $message = new Google_Service_Gmail_Message();
       $message->setRaw($mime);
       $service->users_messages->send($userId, $message);
      

      【讨论】:

      • 确保你的base64urlencode不仅仅是base64encode,否则你会遇到错误。
      【解决方案3】:

      我从字符串创建 mime 消息,如下所示。如果你愿意,可以制作你自己的函数。

      我用base64_encode 对主题和消息进行编码,并将=?utf-8?B? 放在起点,?= 放在每个结尾。

      $mimeMessage  = "MIME-Version: 1.0\r\n";
      $mimeMessage  = "From: Fullname <from@from.com>\r\n";
      $mimeMessage .= "To: Fullname <to@t.com>\r\n";
      $mimeMessage .= "Subject: =?utf-8?B?".base64_encode('Sample Subject Which Contains Non-Latin Characters')."?=\r\n";
      $mimeMessage .= "Date: ".date(DATE_RFC2822)."\r\n";
      $mimeMessage .= "Content-Type: multipart/alternative; boundary=test\r\n\r\n";
      $mimeMessage .= "--test\r\n";
      $mimeMessage .= "Content-Type: text/plain; charset=UTF-8\r\n";
      $mimeMessage .= "Content-Transfer-Encoding: base64\r\n\r\n";
      $mimeMessage .= base64_encode('Sample email message which contains non-latin chcracters')."\r\n";
      

      使用换行符时要小心。有些线路需要\r\n\r\n

      然后,按照 Gmail API 的要求对整个 $mimeMessage 进行编码:

      $mimeMessageEncoded = base64url_encode($mimeMessage);
      

      【讨论】:

        【解决方案4】:

        您可以尝试 PhpMimeClient 并创建带有附件和内联图像的 mime 消息: https://github.com/breakermind/PhpMimeParser/blob/master/PhpMimeClient_class.php

        简单示例:

        $m = new PhpMimeClient();
        
        // Add files inline
        $m->addFile('photo.jpg',"zenek123");
        
        // Add file
        $m->addFile('sun.png');
        
        // create mime
        $m->createMime("Witaj księżniczko Alabambo",'<h1>Witaj księżniczko Alabambo <img src="cid:zenek123"> </h1>',"Wesołych świąt życzę!","Heniek Wielki", "heik@dom-ain.com","ho@gomail.coc");
        
        // get mime
        // $m->getMime()
        
        // Show mime in browser
        echo nl2br(htmlentities($m->getMime()));
        

        【讨论】:

          【解决方案5】:

          我知道这是一篇相当老的帖子,但我在 Google 上找到了它,我刚刚在使用 Laravel 5.5 时遇到了同样的问题,我就是这样做的——以防万一它对任何人有帮助:)

          下面的函数将使用刀片模板返回一个 HTML 字符串,该模板允许您将其传递到 Google API。

          /**
           * Create a Message from an email formatted string.
           *
           * @return Google_Service_Gmail_Message Message containing email.
           */
          function createMessage()
          {
              $message = new \Google_Service_Gmail_Message();
          
              // Initialise the Swift Message instance.
              $swift = (new Swift_Message())
                  ->setSubject('Test Email')
                  ->setFrom(['example@example.com' => 'Joe Bloggs'])
                  ->setTo(['other@example.com' => 'An Other'])
                  ->setBody(view('mail.invoice'), 'text/html')
          
                  // Optionally add any attachments
                  ->attach(Swift_Attachment::fromPath('my-document.pdf'));
          
              $message->setRaw(strtr(base64_encode($swift->toString()), array('+' => '-', '/' => '_')));
          
              return $message;
          }
          

          如果您想了解有关使用 SwiftMailer 的更多信息,可以前往 Symfony 网站了解更多信息 - 这是我用于此目的的页面。 https://swiftmailer.symfony.com/docs/messages.html

          希望对你有帮助!

          【讨论】:

            【解决方案6】:

            Swiftmailer 可以为您完成所有繁重的工作,包括 Base64 解析。

            $service = new \Google_Service_Gmail($client);
            $mailer = $service->users_messages;
            
            $message = (new \Swift_Message('Here is my subject'))
                ->setFrom('myemailaddress@myserver.com')
                ->setTo(['receiver@someserver.com'=>'Test Name'])
                ->setContentType('text/html')
                ->setCharset('utf-8')
                ->setBody('<h4>Here is my body</h4>');
            
            $msg_base64 = (new \Swift_Mime_ContentEncoder_Base64ContentEncoder())
                ->encodeString($message->toString());
            
            $message = new \Google_Service_Gmail_Message();
            $message->setRaw($msg_base64);
            $message = $mailer->send('me', $message);
            print_r($message);
            

            【讨论】:

              猜你喜欢
              • 2015-07-27
              • 2014-09-03
              • 2015-12-23
              • 2011-03-17
              • 2013-06-07
              • 2020-12-31
              • 2016-06-26
              • 2017-03-03
              • 2023-03-22
              相关资源
              最近更新 更多