发送电子邮件使用带有gmail php api的所有样式的Html内容

时间:2017-11-22 09:17:27

标签: php gmail-api

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

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

我希望获得电子邮件中的所有样式。 我也尝试过charset 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);

2 个答案:

答案 0 :(得分:4)

正如OP通过将Content-Transfer-Encoding: quoted-printable更改为Content-Transfer-Encoding: base64所指出的那样解决了问题。

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

答案 1 :(得分:0)

解决方案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;
    }
}