symfonyemailpostmark

Sending email via postmark on symfony with different message streams


As my application has evolved, I've needed the proper way of sending an email to a bulk amount of users. Currently our transactional emails work well, and this is the structure for them.

.env file:

###> symfony/postmark-mailer ###
MAILER_DSN=postmark://token@default
###< symfony/postmark-mailer ###

Controller that sends email:

$email = (new Email())
    ->from('emailaddress', 'Sitename')
    ->to($email)
    ->priority(Email::PRIORITY_HIGH)
    ->subject('Subject line here')
    ->text("Your account's email has been changed to this one. If you didn't do this, contact us.");

//Send it.
$mailer->send($email);

This works, however when we want to send email in bulk (broadcasts) this doesn't work. We tried changing the header by doing this:

$email = (new TemplatedEmail())
    ->from(new Address('emailaddress', 'Sitename'))
    ->subject('Subject line')
    ->htmlTemplate('email/post.html.twig')
    ->context([
        'postTitle' => $post_title,
        'postContent' => $post_content_updated,
        'profilePicture' => $user->getProfilePicture(),
        'displayName' => $user->getDisplayName(),
    ]);

foreach($subscribers as $subscriber)
{
    $email->addBcc($subscriber->getEmail());
}

$email->getHeaders()
->addTextHeader('X-PM-Message-Stream', 'broadcast');

$mailer->send($email);

We get an error of: ErrorCode: '300', Message: 'Maximum of 50 recipients allowed per email message'.

I noticed that this error shows up in the default transactional stream instead of the broadcast. How do we make this work? I can't seem to find documentation pertaining to this.


Solution

  • Bulk emails don't use Bcc. You need to send separate email message for every email address. X-PM-Message-Stream is just header to say Postmark to use another stream (use another server and other tweaks). You can do it in your loop this way:

    foreach($subscribers as $subscriber) {
        $email = (new TemplatedEmail())
            ->from(new Address('emailaddress', 'Sitename'))
            ->to($subscriber->getEmail())
            ->subject('Subject line')
            ->htmlTemplate('email/post.html.twig')
            ->context([
                'postTitle' => $post_title,
                'postContent' => $post_content_updated,
                'profilePicture' => $user->getProfilePicture(),
                'displayName' => $user->getDisplayName(),
            ]);
    
        $email
            ->getHeaders()
            ->addTextHeader('X-PM-Message-Stream', 'broadcast');
    
        $mailer->send($email);
    }
    

    If you need to broadcast as fast as possible you should use API from Postmark. Then you can send 500 messages per one request to API. You can send 10 requests simultaneously so you will have speed about 5000 messages per time of processing one request (about 1 second I think)