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

[2025-06-14 05:26:42] manifestcache-log.WARNING: Failed to save values: fwrite(): write of 8192 bytes failed with errno=28 No space left on device {"keys":["__CACHE__"],"exception":"[object] (ErrorException(code: 0): fwrite(): write of 8192 bytes failed with errno=28 No space left on device at /srv/users/maenterawasi/apps/maenterawasi/vendor/symfony/cache/Traits/FilesystemCommonTrait.php:108)"} [] ERROR [Warning]: Unknown: write failed: No space left on device (28) IN GET /articles/how-to-send-emails-in-silverstripe-4-with-gmail-smtp Line 0 in Unknown Trace ===== SilverStripe\Dev\CliDebugView->renderTrace() DetailedErrorFormatter.php:119 SilverStripe\Logging\DetailedErrorFormatter->output(2, Unknown: write failed: No space left on device (28), Unknown, 0, ) DetailedErrorFormatter.php:54 SilverStripe\Logging\DetailedErrorFormatter->format(Array) AbstractProcessingHandler.php:37 Monolog\Handler\AbstractProcessingHandler->handle(Array) Logger.php:344 Monolog\Logger->addRecord(300, E_WARNING: Unknown: write failed: No space left on device (28), Array) Logger.php:614 Monolog\Logger->log(300, E_WARNING: Unknown: write failed: No space left on device (28), Array) ErrorHandler.php:160 Monolog\ErrorHandler->handleError(2, Unknown: write failed: No space left on device (28), Unknown, 0, ) ERROR [Warning]: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/srv/users/maenterawasi/tmp/maenterawasi) IN GET /articles/how-to-send-emails-in-silverstripe-4-with-gmail-smtp Line 0 in Unknown Trace ===== SilverStripe\Dev\CliDebugView->renderTrace() DetailedErrorFormatter.php:119 SilverStripe\Logging\DetailedErrorFormatter->output(2, Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/srv/users/maenterawasi/tmp/maenterawasi), Unknown, 0, ) DetailedErrorFormatter.php:54 SilverStripe\Logging\DetailedErrorFormatter->format(Array) AbstractProcessingHandler.php:37 Monolog\Handler\AbstractProcessingHandler->handle(Array) Logger.php:344 Monolog\Logger->addRecord(300, E_WARNING: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/srv/users/maenterawasi/tmp/maenterawasi), Array) Logger.php:614 Monolog\Logger->log(300, E_WARNING: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/srv/users/maenterawasi/tmp/maenterawasi), Array) ErrorHandler.php:160 Monolog\ErrorHandler->handleError(2, Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/srv/users/maenterawasi/tmp/maenterawasi), Unknown, 0, )