如何以多个块发送电子邮件?

时间:2016-04-21 17:15:44

标签: php curl cron phpmailer

我正在使用php邮件功能发送电子邮件,而且工作正常。

电子邮件正文是动态生成的,问题是电子邮件收件人只能接收160个字符或更少的电子邮件。如果电子邮件的正文超过160个字符,那么我想将正文拆分为单独的块,每个块少于160个字符。

我正在使用CRON Jobs和curl自动发送电子邮件。

如果生成多个正文时,如何将每封单独的电子邮件发送给同一收件人?低于$bodyAll表示只有一封电子邮件要发送,因为动态生成的内容适合160个字符。如果正文内容超过160,那么$bodyAll将不会被发送,$bodyFirstPart将被发送给收件人,然后$bodySecondPart等,直到所有单独的正文发送

$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())

1 个答案:

答案 0 :(得分:3)

您可以使用strlen检查while循环内部的长度,使用substr对其进行修剪,并在每次循环迭代时发送每个块:

<?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
}