1

On my site a type of user can add new clients and I wanted to automate the activation email, so that when a new user is added then the client will get the activation email. But I'm getting an error that the activation $link is missing any idea how to get that parameter? This is what I have so far.



Craft::$app->elements->on(Elements::EVENT_AFTER_SAVE_ELEMENT, function(ElementEvent $event) {

      if ($event->element instanceof \craft\elements\User) {
        
        $user = $event->element;
       

        if($event->isNew) {
          
          Craft::$app
          ->getMailer()
          ->composeFromKey('after_activate_user')
          ->setTo($user)
          ->send();
        }
      }
    });

Digging through some code I saw that you can pass a link parameter like this:

 ->composeFromKey('after_activate_user', ['link' => Template::raw($link)])

But not sure where I can retrieve this $link

Any help is appreciated.

Thanks!

2

Rather than assembling the email yourself, you can just call the sendActivationEmail method in Craft:

if ($event->isNew) {
    Craft::$app->getUsers()->sendActivationEmail($user);
}

That will automatically generate the activation link for you.

1

If you want full control on the activation email site/language/template you just can't rely on sendActivationEmail(). You can do this instead:

use craft\mail\Message;

// get activation link
$verifyUrl = Craft::$app->users->getEmailVerifyUrl($user);

// create email
$msg = new Message();
$msg->setTo($user->email);
$msg->setSubject('Activate your account');

// compose the HTML body where you will output verifyUrl link
$template = Craft::$app->getView()->renderTemplate('path/to/template', [
   'user' => $user,
   'verifyUrl' => $verifyUrl
]); 
$msg->setHtmlBody($template);

// finally send the email
$msg->send();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.