Send Email With Html content with all styling with gmail php api

Viewed 2062

I want to send email with all html using the gmail api. This is the preview of the html : https://docs.google.com/drawings/d/1J0nzeTol6VFr8sB1TlMDbTrSVanDncQ8FOelP_SvmY0/edit

But when i send the email to my test account and then i check the email in inbox all the styling in email is lost. This is the screenshot of the email after sending. https://docs.google.com/drawings/d/1yfzmlqzMhJMWbJth-o6mfgSJcGAtUIKr41hpvzlFQGE/edit?usp=sharing

I want to get the all the styling in emails. I have also tried the charset iso-8859-1 but still the same result.

This is my php code :

        $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 Answers

Solution Content-Transfer-Encoding: base64 didn't helped me. Emails are delayed pretty much or even won't income. And in 70% cases - email body still appears as text/plain, instead 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;
    }
}
Related