Yii Framework Forum

SwiftMailer message-id


(Steve) #1

Is there a way to get the message-id for emails sent with SwiftMailer? SwiftMailer has getId(), but is this accessible somehow through Yii::$app->mailer? I can’t find any reference to it in the documentation.


(Henry Volkmer) #2

“Yii:$app” is a Service Locator (https://www.yiiframework.com/doc/guide/2.0/en/concept-service-locator) and the Key “mailer” contains a Swiftmailer Instance. Therefore, you can do this:

$mailer = Yii:$app->mailer;
#compose + send mail here
$id = $mailer->getId();

(Steve) #3

I’m getting

Calling unknown method: yii\swiftmailer\Mailer::getId()

Thanks for the link. I didn’t know about service locators.


(Henry Volkmer) #4

Try:
$id = Yii::$app->mailer->getSwiftMessage()->getId();


(Steve) #5

Calling unknown method: yii\swiftmailer\Mailer::getSwiftMessage()


(Steve) #6

I got it. I have to call:
Yii::$app->mailer->compose()->getSwiftMessage()->getId();

Thanks a lot for your help!


(Steve) #7

Running into another problem here. The message-id I get from Swfitmailer doesn’t match the message-id on the receiving end.

$mid = $message->compose()->getSwiftMessage()->getId(); var_dump($mid);
    // $mid = f902f65a871a2e4ada00f6f7865ab232@mydomain.com
$message->compose(
    // Compose and send
)->send();
$mid = $message->compose()->getSwiftMessage()->getId(); var_dump($mid); die;
    // $mid = eb11f9364e54601f18aff144d2f76948@mydomain.com

// message-id of received email: f1f5bb60bc2ffe6a7bcb2200fb03e993@mydomain.com

(Steve) #8

Dumb mistake on my part. The id’s are generated by compose().

 $message = Yii::$app->mailer->compose(
                            ['html' => 'notification-html'], 
                            ['title' => $title, 'message' => $msg]
                        );
$mid = $message->getSwiftMessage()->getId(); var_dump($mid);
     // $mid = 6fe84dde923f79673a1ae0f60868e218@mydomain.com
$message->setFrom() .... ->send();
$mid = $message->getSwiftMessage()->getId(); var_dump($mid); die;
    // $mid = ac4c38ba2652e0c03ae542529670c43d@mydomain.com

// message-id of received email:  6fe84dde923f79673a1ae0f60868e218@mydomain.com

Note for anyone else doing this. Grab the message-id before sending the email as it gets regenerated after send.