Search code examples
phpemail-attachmentsswiftmailermime-message

SwiftMailer RfcComplianceException Invalid ID given


I am working on a system that takes emails before they get sent out, finds all base64 encoded images within, and embeds them as inline attachments with content ids (cid).

Well SwiftMailer doesn't like the way I'm doing the Id's. I tried this:

$attachment = new \Swift_Attachment( $image['bytes'], $image['name'], $image['type'] );
$attachment->setDisposition('inline');
$attachment->setId($image['content_id']); // content id is dhGCSXS6bXRbBQIKl2xoXNh4

And it gave me this:

// Swift_RfcComplianceException: Invalid ID given <dhGCSXS6bXRbBQIKl2xoXNh4>

So apparently there's a format for content ids? I looked up RFC 2111 and couldn't really find anything spelling out a format. From looking around, I thought it was just whatever random unique string you can come up with. Or maybe it's just 4 o'clock and my brain has checked out.

Also, I can't just use the Swift generated cid because the cid has already been generated and used by another service earlier in the chain.

So is there a valid format for a cid?


Solution

  • I think there should be @ sign in the CID.

    To be more specific, CID should match as is in source:

    private function _assertValidId($id)
        {
            if (!preg_match(
                '/^'.$this->getGrammar()->getDefinition('id-left').'@'.
                $this->getGrammar()->getDefinition('id-right').'$/D',
                $id
                )) {
                throw new Swift_RfcComplianceException(
                    'Invalid ID given <'.$id.'>'
                    );
            }
        }
    

    And to be even more specific, CID should match below regex:

    /^(?:(?:[a-zA-Z0-9!#\$%&'\*\+\-\/=\?\^_`\{\}\|~]+(\.[a-zA-Z0-9!#\$%&'\*\+\-\/=\?\^_`\{\}\|~]+)*)|(?:"(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21\x23-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F]))*"))@(?:(?:[a-zA-Z0-9!#\$%&'\*\+\-\/=\?\^_`\{\}\|~]+(\.[a-zA-Z0-9!#\$%&'\*\+\-\/=\?\^_`\{\}\|~]+)*)|(?:\[(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x5A\x5E-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F]))*\]))$/D
    

    For more details examine: https://github.com/swiftmailer/swiftmailer/blob/de19df332219d73a2704525ba75aabd7dfaa303b/lib/classes/Swift/Mime/Grammar.php