【问题标题】:Send Email With Html content with all styling with gmail php api使用 gmail php api 发送带有所有样式的 Html 内容的电子邮件
【发布时间】:2018-05-05 23:04:38
【问题描述】:

我想使用 gmail api 发送带有所有 html 的电子邮件。 这是 html 的预览: https://docs.google.com/drawings/d/1J0nzeTol6VFr8sB1TlMDbTrSVanDncQ8FOelP_SvmY0/edit

但是当我将电子邮件发送到我的测试帐户然后我检查收件箱中的电子邮件时,电子邮件中的所有样式都丢失了。 这是邮件发送后的截图。 https://docs.google.com/drawings/d/1yfzmlqzMhJMWbJth-o6mfgSJcGAtUIKr41hpvzlFQGE/edit?usp=sharing

我想获得电子邮件中的所有样式。 我也尝试了字符集 iso-8859-1,但结果仍然相同。

这是我的 php 代码:

        $service = new Google_Service_Gmail($this->client);
        $user = 'me';
        $strSubject = $subject;
        $strRawMessage = "From: <".$from.">\r\n";
        $strRawMessage .= "To:  <".$to.">\r\n";
        $strRawMessage .= 'Subject: =?utf-8?B?' . base64_encode($strSubject) . "?=\r\n";
        $strRawMessage .= "MIME-Version: 1.0\r\n";
        $strRawMessage .= "Content-Type: text/html; charset=utf-8\r\n";
        $strRawMessage .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
        $strRawMessage .= $message."\r\n";
        // The message needs to be encoded in Base64URL
        $mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
        $msg = new Google_Service_Gmail_Message();
        $msg->setRaw($mime);
        //The special value **me** can be used to indicate the authenticated user.
        $service->users_messages->send("me", $msg);

【问题讨论】:

  • 通过将'Content-Transfer-Encoding: quoted-printable'更改为'Content-Transfer-Encoding: base64'修复
  • 所以,如果我没看错的话,您就是在以 Microsoft 的名义设计网络钓鱼电子邮件。不错。

标签: php gmail-api


【解决方案1】:

正如 OP 指出的那样,将 Content-Transfer-Encoding: quoted-printable 更改为 Content-Transfer-Encoding: base64 可以解决问题。

我几乎有同样的问题,并且能够以同样的方式解决它

【讨论】:

    【解决方案2】:

    解决方案Content-Transfer-Encoding: base64 没有帮助我。电子邮件几乎被延迟,甚至没有收入。在 70% 的情况下 - 电子邮件正文仍显示为 text/plain,而不是 text/html。

    <?php
    
    namespace App\Service;
    
    use App\Constant\Parameter;
    use App\Entity\Log;
    use Doctrine\ORM\EntityManagerInterface;
    use Exception;
    use Google_Client;
    use Google_Exception;
    use Google_Service_Gmail;
    use Google_Service_Gmail_Message;
    use Monolog\Logger;
    use SendGrid;
    use SendGrid\Mail\Mail;
    use SendGrid\Mail\TypeException;
    use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
    
    class MailingService
    {
        /**
         * @var ParameterBagInterface
         */
        private ParameterBagInterface $bag;
        /**
         * @var EntityManagerInterface
         */
        private EntityManagerInterface $manager;
    
        private Google_Client $client;
    
        private array $messages = [];
    
        public function __construct(EntityManagerInterface $manager, ParameterBagInterface $bag)
        {
            $this->bag = $bag;
            $this->manager = $manager;
        }
    
        /**
         * @param $to string recipient email address
         * @param $subject string email subject
         * @param $body string email text
         */
        public function addMessage(string $to, string $subject, string $body) {
            $message = new Google_Service_Gmail_Message();
            $sender = $this->bag->get('mailer.username');
            $rawMessageString = "From: <{$sender}>\r\n";
            $rawMessageString .= "To: <{$to}>\r\n";
            $rawMessageString .= 'Subject: =?utf-8?B?' . base64_encode($subject) . "?=\r\n";
            $rawMessageString .= "MIME-Version: 1.0\r\n";
            $rawMessageString .= "Content-Type: text/html; charset=utf-8\r\n";
            $rawMessageString .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
            $rawMessageString .= "{$body}\r\n";
    
            $rawMessage = base64_encode($rawMessageString);
            $message->setRaw($rawMessage);
            $this->messages[] = $message;
        }
    
        /**
         * @return bool|array
         */
        public function send()
        {
            $service = new Google_Service_Gmail($this->client);
            $user = $this->bag->get('mailer.username');
            try {
                foreach ($this->messages as $message) {
                    $service->users_messages->send($user, $message);
                }
                return true;
            } catch (Exception $e) {
                return [$e->getMessage()];
            }
        }
    
        /**
         * Returns an authorized API client.
         * @return void the authorized client object
         * @throws Google_Exception
         */
        public function initClient()
        {
            $client = new Google_Client();
            $client->setApplicationName('Gmail API PHP Quickstart');
            $client->setScopes([Google_Service_Gmail::GMAIL_SEND]);
            $client->setAuthConfig($this->bag->get('kernel.project_dir') . '/credentials.json');
            $client->setAccessType('offline');
            $client->setPrompt('select_account consent');
    
            $tokenPath = $this->bag->get('kernel.project_dir') . '/token.json';
            if (file_exists($tokenPath)) {
                $accessToken = json_decode(file_get_contents($tokenPath), true);
                $client->setAccessToken($accessToken);
            }
    
            // If there is no previous token or it's expired.
            if ($client->isAccessTokenExpired()) {
                // Refresh the token if possible, else fetch a new one.
                if ($client->getRefreshToken()) {
                    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
                } else {
                    // Request authorization from the user.
                    $authUrl = $client->createAuthUrl();
                    printf("Open the following link in your browser:\n%s\n", $authUrl);
                    print 'Enter verification code: ';
                    $authCode = trim(fgets(STDIN));
    
                    // Exchange authorization code for an access token.
                    $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
                    $client->setAccessToken($accessToken);
    
                    // Check to see if there was an error.
                    if (array_key_exists('error', $accessToken)) {
                        throw new Exception(join(', ', $accessToken));
                    }
                }
                // Save the token to a file.
                if (!file_exists(dirname($tokenPath))) {
                    mkdir(dirname($tokenPath), 0700, true);
                }
                file_put_contents($tokenPath, json_encode($client->getAccessToken()));
            }
            $this->client = $client;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-25
      • 2014-07-13
      • 2015-04-30
      • 2014-11-18
      • 2015-01-02
      • 2016-09-22
      • 2015-10-25
      • 2014-10-30
      • 2020-06-01
      相关资源
      最近更新 更多