View source
<?php
namespace Drupal\sparkpost\Form;
use Drupal\Core\Config\ConfigManager;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Link;
use Drupal\Core\Mail\MailFormatHelper;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\sparkpost\ClientService;
class TestMailForm extends FormBase {
protected $sparkpostClient;
public function __construct(ClientService $sparkpost_client) {
$this->sparkpostClient = $sparkpost_client;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('sparkpost.client'));
}
public function getFormId() {
return 'test_mail_form';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form['recipient'] = [
'#type' => 'email',
'#title' => $this
->t('Recipient'),
'#required' => TRUE,
'#default_value' => $this
->configFactory()
->get('system.site')
->get('mail'),
];
$form['subject'] = [
'#type' => 'textfield',
'#title' => $this
->t('Subject'),
'#maxlength' => 255,
'#default_value' => $this
->t('Drupal Sparkpost test email'),
];
$form['body'] = [
'#type' => 'textarea',
'#title' => $this
->t('Body'),
'#default_value' => $this
->t('If you receive this message it means your site is capable of using Sparkpost to send email. This url is here to test click tracking: !link', [
'!link' => Link::fromTextAndUrl($this
->t('link'), Url::fromUri('http://www.drupal.org/project/sparkpost'))
->toString(),
]),
];
$form['submit'] = [
'#type' => 'submit',
'#value' => t('Send'),
];
return $form;
}
public function validateForm(array &$form, FormStateInterface $form_state) {
parent::validateForm($form, $form_state);
}
public function submitForm(array &$form, FormStateInterface $form_state) {
try {
$to = $form_state
->getValue('recipient');
$subject = $form_state
->getValue('subject');
$message = $form_state
->getValue('body');
$response = $this->sparkpostClient
->sendMessage([
'content' => [
'subject' => $subject,
'html' => $message,
'text' => MailFormatHelper::htmlToText($message),
],
'recipients' => [
[
'address' => [
'email' => $to,
],
],
],
]);
drupal_set_message($this
->t('Sparkpost test email sent from %to.', [
'%to' => $to,
]), 'status');
} catch (\Exception $e) {
drupal_set_message($this
->t('Message could not be sent: %message', [
'%message' => $e
->getMessage(),
]), 'error');
}
}
}