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(

    $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->setSubject("Contact Message from {$data["Name"]}"); 
    $messageBody = " 
        <p><strong>Name:</strong> {$data['Name']}</p> 
        <p><strong>Message:</strong> {$data['Message']}</p> 
    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
  - '#emailconfig'
    class: Swift_SmtpTransport
      Port: 587
      Encryption: tls
      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]"

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 and turn on 'Less secure apps access'.

Post your comment


No one has commented on this page yet.

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