laravel-mailjet icon indicating copy to clipboard operation
laravel-mailjet copied to clipboard

Using the Subject Line from a Template

Open temp1029 opened this issue 4 years ago • 1 comments

I am trying to use the subject line from my template in an email. The problem is, if you don't provide a subject line to a Laravel Mailable, the following code creates a subject line based on the classname.

$message->subject(Str::title(Str::snake(class_basename($this), ' ')));

In addition, setting the subject line to a "truthy" value, results in it overriding the subject line on the template. I haven't been able to find a way around this, but if one exists I'd appreciate some advice.

temp1029 avatar Jul 29 '21 19:07 temp1029

So I think I figured out a way to make this work, but the caveat is you can't specify any subject line when using a template. This is fine for my use-case but other's mileage might vary. Allowing this might need a config setting or an extra header to be set. Ideally Laravel would allow for empty subject lines, but that's unlikely.

Since this package is specific to Laravel I figured some special code to handle a Laravel oddity was OK.

In summary we just need to override the 'send' and 'bulkSend' functions in the laravel-mailjet transport file. This just looks for the 'X-MJ-TemplateID' header and removes the subject line if it is found. After removing the subject line it allows processing to proceed as normal.

The entire file should look like this:

<?php

namespace Mailjet\LaravelMailjet\Transport;

use Mailjet\MailjetSwiftMailer\SwiftMailer\MailjetTransport as BaseTransport;

use \Swift_Mime_SimpleMessage;

class MailjetTransport extends BaseTransport
{
    public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null)
    {
        if($message->getHeaders()->has('X-MJ-TemplateID'))
        {
            $message->setSubject(null);
        }

        return parent::send($message, $failedRecipients);
    }

    public function bulkSend(array $messages, &$failedRecipients = null)
    {
        foreach($messages as $message)
        {
            if($message->getHeaders()->has('X-MJ-TemplateID'))
            {
                $message->setSubject(null);
            }
        }

        return parent::bulkSend($messages, $failedRecipients);
    }
}

temp1029 avatar Sep 27 '21 17:09 temp1029

Hello, we analyzed your solution. For now, it's too specific and we can't implement it as default, for all. But in the future, we will make an improvement to this area. Thank you

oleksandr-mykhailenko avatar Nov 05 '23 16:11 oleksandr-mykhailenko