1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
|
4
|
|
|
namespace Drakakisgeo\Mailtester; |
5
|
|
|
|
6
|
|
|
use RuntimeException; |
7
|
|
|
use Swift_Message; |
8
|
|
|
use Swift_Mailer; |
9
|
|
|
use Swift_Mime_MimePart; |
10
|
|
|
use Swift_SmtpTransport; |
11
|
|
|
|
12
|
|
|
trait InteractsWithSwiftEmailer |
13
|
|
|
{ |
14
|
|
|
private $emailMessage = null; |
15
|
|
|
|
16
|
|
|
public function sendMail() |
17
|
|
|
{ |
18
|
|
|
if (is_null($this->emailMessage)) { |
19
|
|
|
throw new RuntimeException('You need to create the message first and chain it.'); |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
$transport = Swift_SmtpTransport::newInstance(getenv('MAIL_HOST'), getenv('MAIL_PORT')); |
23
|
|
|
$mailer = Swift_Mailer::newInstance($transport); |
24
|
|
|
|
25
|
|
|
if (!$mailer->send($this->emailMessage)) { |
26
|
|
|
throw new RuntimeException('Can\'t send the Email message'); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
$this->emailMessage = null; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
public function buildMailMessage(array $options) |
33
|
|
|
{ |
34
|
|
|
$options = $this->setDefaults($options); |
35
|
|
|
|
36
|
|
|
// Make sure Body exists |
37
|
|
|
if (!array_key_exists('body', $options)) { |
38
|
|
|
throw new RuntimeException('You really need to set the body'); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
$this->emailMessage = Swift_Message::newInstance() |
42
|
|
|
->setSubject($options['subject']) |
43
|
|
|
->setFrom($options['from']) |
44
|
|
|
->setCc($options['cc']) |
45
|
|
|
->setBcc($options['bcc']) |
46
|
|
|
->setTo($options['to']) |
47
|
|
|
->setBody($options['body'], $options['contentType']); |
48
|
|
|
|
49
|
|
|
return $this; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
private function setDefaults($options) |
53
|
|
|
{ |
54
|
|
|
$defaults = [ |
55
|
|
|
'from' => ['[email protected]' => 'FromTester'], |
56
|
|
|
'to' => ['[email protected]' => 'ToTester'], |
57
|
|
|
'subject' => 'Testing Email', |
58
|
|
|
'contentType' => 'text/html', |
59
|
|
|
'cc' => [], |
60
|
|
|
'bcc' => [] |
61
|
|
|
]; |
62
|
|
|
|
63
|
|
|
foreach ($defaults as $key=>$value) { |
64
|
|
|
if (!array_key_exists($key, $options)) { |
65
|
|
|
$options[$key] = $value; |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
return $options; |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|