简体   繁体   中英

How to send an email in multiple chunks?

I'm using the php mail function to send email and it's working fine.

The email body is dynamically generated and the problem is that the email recipient can only receive emails that are 160 characters or less. If the body of the email is longer than 160 characters, then I want to split the body into separate blocks, each less than 160 characters.

I'm using CRON Jobs and curl to automatically send the email.

How can I send each separate email to the same recipient when more than one body is generated? Below $bodyAll represents that there is only one email to be sent because the dynamically generated content fits within 160 characters. If the body content is more than 160, then $bodyAll would not be sent and $bodyFirstPart would be sent to the recipient, then $bodySecondPart , etc., until all the separate body texts are sent.

$body = $bodyAll;
$body = $bodyFirstPart;
$body = $bodySecondPart;
$body = $bodyThirdPart;
$mail->addAddress("recepient1@example.com");
$mail->Subject = "Subject Text";
$mail->Body = "<i>Mail body</i>";
if(!$mail->send())

you can use strlen to check the length inside a while loop trimming it down with substr , and send each chunk every loop iteration:

<?php

$bodyAll = "
  some really long text that exceeds the 160 character maximum for emails,
  I mean it really just tends to drag on forever and ever and ever and ever and
  ever and ever and ever and ever and ever and ever and ever......
";

$mail->addAddress("recepient1@example.com");
$mail->Subject = "Subject Text";

while( !empty($bodyAll) ){

  // check if body too long
  if (strlen($bodyAll) > 160){
    // get the first chunk of 160 chars
    $body = substr($bodyAll,0,160);
    // trim off those from the rest
    $bodyAll = substr($bodyAll,160);
  } else {
    // loop terminating condition
    $body = $bodyAll;
    $bodyAll = "";
  }

  // send each chunk
  $mail->Body = "$body";
  if(!$mail->send())
    // catch send error
}

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