How to add substitution tags to the subject of the email in SendGrid using the xsmtp-api with the php library

谁说我不能喝 提交于 2020-01-14 10:52:32

问题


I am trying to set up the name of my client in the subject of the email. This is very crucial for my application, and from what I've read in the SendGrid API docs it is quite possible!.

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

The problem is that I dob't seem to manage to accomplish this. At first I though that perhaps it's because I am already using the %name% sub within the body of the email, so I've created a new substitution parameter name %nameSubject%, and yet, it won't work.

I use the following code, and the rest of the parameters within the email are workigng just fine:

    /**
    @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);

}

Any help is much appriciated!.


回答1:


The substitution tags should be set individually for the subject or body. Try something like this:

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

You can replace the example array I used with your own array values. We also have some PHP code examples showing substitution tags in our docs as well. (http://sendgrid.com/docs/Code_Examples/php.html#-Using-Substitutions)



来源:https://stackoverflow.com/questions/16132427/how-to-add-substitution-tags-to-the-subject-of-the-email-in-sendgrid-using-the-x

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!