Image by Muhammad Ribkhan from Pixabay
Articles » How to send emails in Silverstripe 4 with Gmail SMTP

How to send emails in Silverstripe 4 with Gmail SMTP

12 April, 2020

Let's assume you have a basic contact form like the one below in your page controller.

public function ContactForm() {
    $fields = new FieldList(
        TextField::create('Name'),
        EmailField::create('Email'),
        TextareaField::create('Message')
    );

    $actions = new FieldList(
        new FormAction('submit', 'Submit')
    );

    $validator = new RequiredFields('Name', 'Email', 'Message');
    $form = new Form($this, 'ContactForm', $fields, $actions, $validator);

    return $form;
}

 

With a controller action of 'submit' to handle submissions like below.

public function submit($data, $form) { 
    $email = new Email(); 
         
    $email->setTo('[email protected]'); 
    $email->setFrom($data['Email']); 
    $email->setSubject("Contact Message from {$data["Name"]}"); 
       
    $messageBody = " 
        <p><strong>Name:</strong> {$data['Name']}</p> 
        <p><strong>Message:</strong> {$data['Message']}</p> 
    ";
 
    $email->setBody($messageBody); 
    $email->send();
        
    return [
        'Content' => '<p>Thank you for your feedback.</p>',
        'ContactForm' => ''
    ];
}

 

Now create an 'email.yml' config file under the 'app/_config' directory similar to the following.

---
Name: myemailconfig
After:
  - '#emailconfig'
---
SilverStripe\Core\Injector\Injector:
  Swift_Transport:
    class: Swift_SmtpTransport
    properties:
      Host: smtp.gmail.com
      Port: 587
      Encryption: tls
    calls:
      Username: [ setUsername, ['`APP_SMTP_USERNAME`'] ]
      Password: [ setPassword, ['`APP_SMTP_PASSWORD`'] ]
      AuthMode: [ setAuthMode, ['login'] ]

Notice the `APP_SMTP_USERNAME` and `APP_SMTP_PASSWORD` will refer to our Gmail credentials, we'll store these in our '.env' file shown below.

APP_SMTP_USERNAME="[email protected]"
APP_SMTP_PASSWORD="crocodile123"

Make sure to replace '[email protected]' and 'crocodile123' with your actual Gmail credentials.

Once you've done all the above, flush the cache by adding '?flush=all' to the end of your site URL. Now give your form a quick test to see if emails are being sent from the configured Gmail account.

Allow less secure apps in Gmail account

If the form still isn't sending emails through your configured Gmail account, go to https://myaccount.google.com/security and turn on 'Less secure apps access'.

Post your comment

Comments

No one has commented on this page yet.

RSS feed for comments on this page | RSS feed for all comments