php - 如何使用带有 php 库的 xsmtp-api 将替换标签添加到 SendGrid 中的电子邮件主题

标签 php sendgrid

我试图在电子邮件的主题中设置我客户的姓名。 这对我的申请非常重要,从我在 SendGrid API docs 中读到的内容来看 很有可能!

Info - Substitution tags will work in the Subject line as well as the body of the email.

问题是我似乎无法做到这一点。 起初我认为这可能是因为我已经在电子邮件正文中使用了 %name% sub,所以我创建了一个新的替换参数名称 %nameSubject%, 然而,它不会起作用。

我使用以下代码,电子邮件中的其余参数都可以正常工作:

    /**
    @description Wrapper method in order to handle possible exception due to programmer\ maintainer errors.
    A part of a small wrapper class that I have designed to allow 1-line comfortable use of the the SendGrid and transport classes.
   @returns int - 1, unless there is an internal error, or an exception thrown
    */
public function execute(){
    if(!class_exists('SendGrid') || !class_exists('SendGrid\Mail')){
        throw new exception('Dependency exception SendGrid or SendGrid\Mail are not included');
    }
    if(!isset($this->mailingList) && empty($this->mailingList) || sizeof($this->mailingList) == 0){
        throw new exception('Cannot send an email to an empty set of addresses');
    }
    if(!isset($this->subject, $this->body) || empty($this->subject) || empty($this->body)){
        throw new exception('Cannot send an email without both a subject and a body');
    }

    $sendgrid = new SendGrid(SENDGRID_USER, SENDGRID_PASSWORD);

    // $this->importMailList();
    foreach($this->mailingList as $key => $val) {   
        $this->mail->addTo($key, $val);
    }
    $this->mail->
    setFrom($this->fromMail)-> 
    setSubject($this->subject)->
    setText($this->text)->
    setHtml($this->body);
    if(preg_match('/%name%/', $this->body) && !array_filter($this->mailingList, 'is_int') ){
        $this->mail->addSubstitution("%name%", array_values($this->mailingList));
    }
    return $sendgrid->smtp->send($this->mail);

}

非常感谢任何帮助!

最佳答案

应该为主题或正文单独设置替换标签。尝试这样的事情:

$this->mail->
setFrom($this->fromMail)-> 
setSubject($this->subject)->addSubstitution("%name%", array("Harry", "Bob"))->
...

您可以用您自己的数组值替换我使用的示例数组。我们也有一些 PHP 代码示例在我们的文档中显示替换标签。 ( http://sendgrid.com/docs/Code_Examples/php.html#-Using-Substitutions )

关于php - 如何使用带有 php 库的 xsmtp-api 将替换标签添加到 SendGrid 中的电子邮件主题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16132427/

相关文章:

php - 使用 xpath 获取输入字段的值

go - SendGrid SMTP 电子邮件不会发送到 Go 中的抄送和密件抄送地址

php - 通过来自 MYSQL 表的回显正确格式化日期时间本地表单输入

php - Zend Framework MySQL query() 插入长文本的问题

php - 如何仅销毁一个 session 而其他 session 正常工作

php - 插入使用同一行(相同的主键)mysql php pdo

azure - 尝试在 azure 服务器上创建 sendgrid 帐户时出现问题

javascript - 将 ASP.NET SendGrid 调用转换为 JavaScript?

c# - 如何以正确的编码从 HttpRequest 表单数据中读取字符串

node.js - 如何迭代 SendGrid 模板中的对象数组?