简体   繁体   中英

Get email size in CakePHP

My application uses a corporate SMTP server with an email size limit of 20mb. I have emails failing with error " [SocketException] SMTP Error: 552 4.3.1 Message size exceeds fixed maximum message size " when the attachments total 14.92mb.

Currently my code loops through the attached files and tallies the file size using PHP filesize() and then compares it against the hard-coded limit of 20mb. It's supposed to run separate code to tell the user if the files are too big, however, in the above example it's still less than the limit and it's generating an ugly error instead.

Is there a way I can measure the total size of the email, attachments and all? The corporate messaging team is pushing back saying that the email must be over 20mb and I would like to properly test this.

I am using CakePHP 2.3's EmailComponent. Here is a simplified version of the code:

App::uses('CakeEmail', 'Network/Email');
$email = new CakeEmail('smtp');
...

$totalAttachmentsSize = 0;
$attachments = array();
//loop array with files to be attached
foreach ($files as $file) {
$totalAttachmentsSize += filesize($file['path']);
$attachments[$file['name']] = $file['path'];
}

//compare attachments size to constant defined in bootstrap.php
if ($totalAttachmentsSize < MAX_EMAIL_SIZE) {
    $email->send();
}
else {
    //handle
}

Attachments are being base64 encoded, which will require some more bytes, also joining them together requires a few bytes for additional headers and stuff.

To get the exact size, check the return value of CakeEmail::send() , it will contain the rendered headers and message body. Use the the DebugTransport if you don't want to actually send the mail.

$email->transport('Debug');
$contents = $email->send();

$data = $contents['headers'] . "\r\n\r\n"
      . $contents['message'] . "\r\n\r\n\r\n.";

debug(strlen($data));

This should give you the exact number of bytes of the mail as it's being sent by the SMTP transport.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM