duanmei1694 2013-11-14 20:30
浏览 5

使用Swiftmailer,我可以替换或删除消息部分吗?

I'm using Swift Mailer to send mail to a fairly large list of email addresses. The message is customized slightly for each recipient. Some placeholders are replaced with unique text.

I assumed it would be more efficient (less garbage collection etc) to reuse one instance of Swift_Message multiple times. I just setTo(), setBody() and send again to the next address.

That works well with a single part body, usually just html. But ... when I want a second part, usually text, I can do addPart(), but next time around the loop, that will add another part, and then another part etc ... The problem doesn't happen with setBody because that overwrites the existing body.

Is there a way to overwrite or remove an existing part?

Thanks

  • 写回答

3条回答 默认 最新

  • dongweihuan8832 2014-02-08 11:48
    关注

    According to the Swift Mailer Docs, there is no such method as a getBody() really.

    I would suggest you to store the actual message template containing your placeholders in a variable and use setBody() on every iteration to replace the complete body of the message with the parsed template for the new recipient instead of trying to replace a tiny bit of it.

    I reckon your code could look something like this:

    $template = '<h1>Hello {{firstname}}</h1>, ...';
    $recipients = [
        ['firstname' => 'John', 'email' => 'john@example.com'],
        ...
    ];
    $message = Swift_Message::newInstance('Subject here');
    
    foreach ($recipients as $recipient) {
        $body = str_replace('{{firstname}}', $recipient['firstname'], $template);
        $message->setBody($body, 'text/html');
    
        // continue building the mail object and send it ...
    }
    

    This way you could indeed re-use the Swift_Message instance for every mail. Although it wouldn't make any difference to PHP if you re-use the instance or create a new one in every loop iteration.

    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号