|
1 | 1 | # php-email
|
2 |
| -Provides an object-oriented way to send and queue emails |
| 2 | +Provides an object-oriented way to send and queue emails. |
| 3 | + |
| 4 | +There is a need to send e-mails in almost all projects, e.g. for user registration or |
| 5 | +password reset functions. Most e-mails sent are very easy. Sophisticated features |
| 6 | +like PGP encryption etc is not required. This library offers a way to create |
| 7 | +such e-mails without setting up the PHPMailer (the underlying library), to send |
| 8 | +multiple e-mails and even to defer sending e-mail sending by using a queue backed |
| 9 | +by a database - and all in an object-oriented way. |
| 10 | + |
| 11 | +Features are: |
| 12 | + |
| 13 | +* Encapsulating SMTP settings in an `EmailQueue` object. |
| 14 | +* Reuse a mailer object for multiple e-mails |
| 15 | +* Sending HTML and TEXT e-mails |
| 16 | +* Embedding pictures and attaching files |
| 17 | +* Enqueueing mails in a database backend |
| 18 | +* Prefixing subject lines automatically |
| 19 | +* Easily create compatible e-mail addresses including the address name |
| 20 | +* E-mail queue will try to send an e-mail multiple times before failing |
| 21 | +* Ability to set a "Mail Mode". Mail Modes can BCC, reroute or even block e-mails completely |
| 22 | + which can be useful in development or acceptance environments. |
| 23 | + |
| 24 | +# License |
| 25 | +This project is licensed under [GNU LGPL 3.0](LICENSE.md). |
| 26 | + |
| 27 | +# Installation |
| 28 | + |
| 29 | +## By Composer |
| 30 | + |
| 31 | +``` |
| 32 | +composer install technicalguru/email |
| 33 | +``` |
| 34 | + |
| 35 | +## By Package Download |
| 36 | +You can download the source code packages from [GitHub Release Page](https://github.com/technicalguru/php-email/releases) |
| 37 | + |
| 38 | +# How to use it |
| 39 | + |
| 40 | +## Create Main Configuration Object |
| 41 | + |
| 42 | +The central class for configuration is the `EmailConfig`. It holds all necessary information. |
| 43 | +Let's start with the basic skeleton: |
| 44 | + |
| 45 | +``` |
| 46 | +
|
| 47 | +use TgEmail\EmailConfig; |
| 48 | +
|
| 49 | +$config = new EmailConfig(); |
| 50 | +$config->setTimezone('Europe/Berlin'); |
| 51 | +$config->setDefaultSender('John Doe <john.doe@example.com>'); |
| 52 | +$config->setSubjectPrefix('[MyAppName] '); |
| 53 | +$config->setDebugAddress('admin@example.com'); |
| 54 | +``` |
| 55 | + |
| 56 | +The lines above create the configuration and tells it to use the timezone `Europe/Berlin` when it needs |
| 57 | +to create timestamps. This is required mainly when e-mails are queued and the timestamp needs to be |
| 58 | +recorded. This value is optional and defaults to `UTC`. |
| 59 | + |
| 60 | +Next, a default sender address is configured. The default sender will be used when a specific |
| 61 | +e-mail to be sent does not define a sender address. Creating e-mail addresses is explained further below. |
| 62 | + |
| 63 | +The subject prefix is used on every e-mail to be sent later. Subjects will be prefixed with this string. The |
| 64 | +default is `NULL` and will not modify the subject. |
| 65 | + |
| 66 | +A debug address is required only when you need to send a test mail. |
| 67 | + |
| 68 | +## Create SMTP Configuration |
| 69 | + |
| 70 | +We still need to tell where our SMTP server is located. So this is how you set these values: |
| 71 | + |
| 72 | +``` |
| 73 | +use TgEmail\Config\SmtpConfig; |
| 74 | +
|
| 75 | +$host = 'smtp.example.com; |
| 76 | +$port = 587; |
| 77 | +$auth = TRUE; |
| 78 | +$username = 'mySmtpUser'; |
| 79 | +$password = 'mySmtpPassword'; |
| 80 | +$secureOption = 'starttls'; |
| 81 | +
|
| 82 | +$smtpConfig = new SmtpConfig($host, $port, $auth, $username, $password, $secureOption); |
| 83 | +$config->setSmtpConfig($smtpConfig); |
| 84 | +``` |
| 85 | + |
| 86 | +Most options are self-explaining. `$auth` tells underlying PHPMailer whether to authenticate with given |
| 87 | +user credentials. `$secureOption` is defined by `PHPMailer` and shall have value `smtps` or `starttls`. |
| 88 | +See the PHPMailer documentation for further information. |
| 89 | + |
| 90 | +All properties can be set by using a setter: |
| 91 | + |
| 92 | +``` |
| 93 | +use TgEmail\Config\SmtpConfig; |
| 94 | +
|
| 95 | +$smtpConfig = new SmtpConfig(); |
| 96 | +$smtpConfig->setHost('smtp.example.com'); |
| 97 | +$smtpConfig->setPort(587); |
| 98 | +
|
| 99 | +// continue setup... |
| 100 | +``` |
| 101 | + |
| 102 | +Authentication credentials can also be set by using the `\TgUtils\Auth\CredentialsProvider` interface from |
| 103 | +`technicalguru/utils` package: |
| 104 | + |
| 105 | +``` |
| 106 | +// Define here your provider |
| 107 | +$provider = ...; |
| 108 | +
|
| 109 | +// Tell SMTP config |
| 110 | +$smtpConfig->setCredentialsProvider($provider); |
| 111 | +``` |
| 112 | + |
| 113 | +## Create the Main MailQueue object |
| 114 | + |
| 115 | +Now it's time to create our central `MailQueue` object: |
| 116 | + |
| 117 | +``` |
| 118 | +use TgEmail\EmailQueue; |
| 119 | +
|
| 120 | +$mailer = new EmailQueue($config); |
| 121 | +``` |
| 122 | + |
| 123 | +You are ready send your first e-mail. |
| 124 | + |
| 125 | +## Send a Test E-Mail |
| 126 | + |
| 127 | +There is a fast and easy way to check whether your setup works correctly: |
| 128 | + |
| 129 | +``` |
| 130 | +$email = $mailer->createTestMail(); |
| 131 | +$rc = $mailer->send($email); |
| 132 | +``` |
| 133 | + |
| 134 | +## Send an E-Mail |
| 135 | + |
| 136 | +We have setup the minimum requirements to send an e-mail: |
| 137 | + |
| 138 | +``` |
| 139 | +use TgEmail\Email; |
| 140 | +
|
| 141 | +$email = new Email(); |
| 142 | +$email |
| 143 | + ->setSubject('Hello World') |
| 144 | + ->addTo('john.doe@example.com', 'John Doe') |
| 145 | + ->addBcc('jane.doe@example.com') |
| 146 | + ->setReplyTo('my-support@example.com') |
| 147 | + ->setBody(Email::TEXT, 'The text e-mail body') |
| 148 | + ->setBody(Email::HTML, '<p>The HTML e-mail body</p>'); |
| 149 | + |
| 150 | +// Will return FALSE when sending fails |
| 151 | +$rc = $mailer->send($email); |
| 152 | +``` |
| 153 | + |
| 154 | +That's it. The code snippet above is all you would need in your application code in order to send e-mails. |
| 155 | +Configuration and setup shall be buried somewhere in your infrastructure setup. |
| 156 | + |
| 157 | +## Hot to add Attachments or embed Images |
| 158 | + |
| 159 | +Attaching files or embedding images is simple. You will need to have the file available and readable |
| 160 | +on the filesystem: |
| 161 | + |
| 162 | +``` |
| 163 | +use TgEmail\Attachment; |
| 164 | +
|
| 165 | +$myFile = new Attachment(Attachment::ATTACHED, 'file.pdf', NULL, '/local/path/to/file.pdf', 'application/pdf'); |
| 166 | +$myImage = new Attachment(Attachment::EMBEDDED, 'img.png', 'img1', '/local/path/to/img.png', 'image/png'); |
| 167 | +
|
| 168 | +$email |
| 169 | + ->addAttachment($myFile) |
| 170 | + ->addAttachment($myImage); |
| 171 | +``` |
| 172 | + |
| 173 | +Note the third parameter of embedded images. It defines a unique ID within your HTML email which you can reference by |
| 174 | + |
| 175 | +``` |
| 176 | +// Using the embedded image |
| 177 | +$myHTML = '<img src="cid:img1">'; |
| 178 | +``` |
| 179 | + |
| 180 | +The `MailQueue` will leave all your attachments untouched on your filesystem. However, sometimes you may wish to get rid |
| 181 | +of the file after you sent the e-mail. The constructor takes two additional arguments: |
| 182 | + |
| 183 | +``` |
| 184 | +$myFile = new Attachment(Attachment::ATTACHED, $filename, $cid, $path, $mimeType, TRUE, TRUE); |
| 185 | +``` |
| 186 | + |
| 187 | +The first boolean will trigger the file to be deleted after the e-mail was sent successfully. The second boolean tells |
| 188 | +whether the file can be deleted when sending failed. Using these parameters you don't need to take care |
| 189 | +about temporary files anymore. Especially when it comes to queueing and deferred sending. |
| 190 | + |
| 191 | +## Mail Modes |
| 192 | + |
| 193 | +`MailQueue` supports so-called Mail Modes. They tell the mailer object how to generally treat e-mails. This comes |
| 194 | +comfortable when you're either testing a setup, when you are in an environment that has real e-mail addresses (such as User Acceptance Test environments) or when actually sending out e-mails doesn't make much sense. |
| 195 | + |
| 196 | +These modes are available: |
| 197 | + |
| 198 | +* `EmailQueue::DEFAULT` - This is the normal operation. All e-mails are sent as defined. |
| 199 | +* `EmailQueue::BLOCK` - This will prevent any mail to be sent or queued. The return code is always TRUE. |
| 200 | +* `EmailQueue::REROUTE` - All e-mails will be sent to another address, usually an admin or developer address and the |
| 201 | + defined recipients of the e-mail are ignored. |
| 202 | +* `EmailQueue::BCC` - The e-mails will be sent to their intended recipients but additional addresses are set on BCC. |
| 203 | + |
| 204 | +### Blocking all E-Mails |
| 205 | + |
| 206 | +Blocking all e-mails to be sent or queued is quite easy: |
| 207 | + |
| 208 | +``` |
| 209 | +$mailer->setMailMode(EmailQueue::BLOCK); |
| 210 | +``` |
| 211 | + |
| 212 | +The same method can be used on the central `EmailConfig` object. |
| 213 | + |
| 214 | +### Rerouting all E-Mails |
| 215 | + |
| 216 | +You need a `RerouteConfig` configuration to be set in the main configuration. You can set this up-front when creating the |
| 217 | +config object, or alltogether when setting the mail mode: |
| 218 | + |
| 219 | +``` |
| 220 | +use TgEmail\Config\RerouteConfig; |
| 221 | +
|
| 222 | +// Create the config |
| 223 | +$subjectPrefix = '[Rerouted]'; |
| 224 | +$recipients = array('my-dev-account@example.com'); |
| 225 | +$rerouteConfig = new RerouteConfig($subjectPrefix, $recipients); |
| 226 | +
|
| 227 | +// And set the mail mode |
| 228 | +$mailer->setMailMode(EmailQueue::REROUTE, $rerouteConfig); |
| 229 | +``` |
| 230 | + |
| 231 | +### Set a Developer as BCC on all sent E-mails |
| 232 | + |
| 233 | +You need a `BccConfig` configuration to be set in the main configuration. You can set this up-front when creating the |
| 234 | +config object, or alltogether when setting the mail mode: |
| 235 | + |
| 236 | +``` |
| 237 | +use TgEmail\Config\BccConfig; |
| 238 | +
|
| 239 | +// Create the config |
| 240 | +$recipients = array('my-dev-account@example.com'); |
| 241 | +$bccConfig = new BccConfig($recipients); |
| 242 | +
|
| 243 | +// And set the mail mode |
| 244 | +$mailer->setMailMode(EmailQueue::BCC, $bccConfig); |
| 245 | +``` |
| 246 | + |
| 247 | +## Queue E-Mails to be sent later |
| 248 | + |
| 249 | +One drawback of sending out e-mails directly from application code is the that it is time-consuming. Your |
| 250 | +user needs to wait for the sending to complete before she/he can see any response from your application. |
| 251 | +Queueing e-mails is the solution as sending is deferred (preferrable to a cron job) and the user receives |
| 252 | +her/his application response fast. |
| 253 | + |
| 254 | +You will need a [`TgDatabase\Database`](https://github.com/technicalguru/php-database/blob/src/TgEmail/Database.php) |
| 255 | +object to queue e-mails. Otherwise, `EmailQueue` will throw exceptions when you try to queue e-mails. Please refer |
| 256 | +to the [`TgDatabase\Database`](https://github.com/technicalguru/php-database/) documentation about how to create |
| 257 | +the `Database` object. Setup the according `EmailsDAO` and `EmailQueue` as follows: |
| 258 | + |
| 259 | +``` |
| 260 | +use TgEmail\EmailsDAO; |
| 261 | +
|
| 262 | +$dao = new EmailsDAO($database); |
| 263 | +$mailer = new EmailQueue($config, $dao); |
| 264 | +``` |
| 265 | + |
| 266 | +The mailer will automatically create the queue table if it does not exist. |
| 267 | + |
| 268 | +Once, the `EmailsDAO` is available, you can easily queue e-mails: |
| 269 | + |
| 270 | +``` |
| 271 | +// Create your email object here |
| 272 | +$email = ... |
| 273 | +
|
| 274 | +// Queue it. Will return FALSE when sending fails |
| 275 | +$rc = $mailer->queue($email); |
| 276 | +``` |
| 277 | + |
| 278 | +## Processing the E-Mail Queue |
| 279 | + |
| 280 | +You can process the queue in another call or during a cronjob: |
| 281 | + |
| 282 | +``` |
| 283 | +$mailer->processQueue($maxSeconds); |
| 284 | +``` |
| 285 | + |
| 286 | +The argument `$maxSeconds` will ensure that the processing stops when the time limit has been reached. |
| 287 | +The argument is optional and defaults to 60 seconds. |
| 288 | + |
| 289 | +## How to Create an E-mail Address |
| 290 | + |
| 291 | +There are multiple ways to create e-mail addresses. All mailing components use an `EmailAddress` object. |
| 292 | +You can use this object as an argument whereever e-mail addresses are expected. Several ways exist |
| 293 | +to create such an object. |
| 294 | + |
| 295 | +``` |
| 296 | +// From a string |
| 297 | +$address = EmailAddress::from('john.doe@example.com'); |
| 298 | +$address = EmailAddress::from('<john.doe@example.com>'); |
| 299 | +$address = EmailAddress::from('John Doe <john.doe@example.com>'); |
| 300 | +
|
| 301 | +// From email string and name |
| 302 | +$address = EmailAddress::from('john.doe@example.com', 'John Doe'); |
| 303 | +
|
| 304 | +// From another object |
| 305 | +$obj = new \stdClass; |
| 306 | +$obj->name = 'John Doe'; |
| 307 | +$obj->email = 'john.doe@example.com'; |
| 308 | +$address = EmailAddress::from($obj); |
| 309 | +
|
| 310 | +// From another EmailAddress |
| 311 | +$address = EmailAddress::from($anotherEmailAddressObject); |
| 312 | +``` |
| 313 | + |
| 314 | +This means that you can use these flavours when creating e-mails: |
| 315 | + |
| 316 | +``` |
| 317 | +$email->addTo('John Doe <john.doe@example.com>'); |
| 318 | +$email->addTo('john.doe@example.com', 'John Doe'); |
| 319 | +$email->addTo(array('John Doe <john.doe@example.com>', $anotherEmailAddressObject, $obj); |
| 320 | +``` |
| 321 | + |
| 322 | +## Creating Configuration Objects from Objects, Arrays or JSON strings |
| 323 | + |
| 324 | +The configuration objects introduced above can also be created using JSON strings, objects or associative arrays. |
| 325 | +The following snippets describe the JSON objects in short notation. |
| 326 | + |
| 327 | +``` |
| 328 | +SmtpConfig: |
| 329 | +----------- |
| 330 | +{ |
| 331 | + "host": "www.example.com", |
| 332 | + "port": 587, |
| 333 | + "debugLevel": 0, |
| 334 | + "auth": true, |
| 335 | + "secureOption": "starttls", |
| 336 | + "charset": "utf8", |
| 337 | + "credentials": { |
| 338 | + "user": "username", |
| 339 | + "pass": "password" |
| 340 | + } |
| 341 | +}, |
| 342 | +
|
| 343 | +RerouteConfig: |
| 344 | +-------------- |
| 345 | +{ |
| 346 | + "recipients": "hans.mustermann@example.com", |
| 347 | + "subjectPrefix": "[Rerouted]" |
| 348 | +}, |
| 349 | +
|
| 350 | +BccConfig: |
| 351 | +---------- |
| 352 | +{ |
| 353 | + "recipients": "hans.mustermann@example.com" |
| 354 | +}, |
| 355 | +
|
| 356 | +EmailConfig: |
| 357 | +------------ |
| 358 | +{ |
| 359 | + "timezone": "Europe\/Berlin", |
| 360 | + "mailMode": "default", |
| 361 | + "smtpConfig": {... see above ...}, |
| 362 | + "rerouteConfig": {... see above ...}, |
| 363 | + "bccConfig": {... see above ...}, |
| 364 | + "debugAddress": "john.doe@example.com", |
| 365 | + "defaultSender": "jane.doe@example.com", |
| 366 | + "subjectPrefix": "[PHPUnitTest] " |
| 367 | +} |
| 368 | +``` |
| 369 | + |
| 370 | +Each of the configuration classes provide a static `from()` method that take these types as an argument and return the |
| 371 | +configuration object itself: |
| 372 | + |
| 373 | +``` |
| 374 | +$smtpConfig = SmtpConfig::from($jsonStringOrObjectOrAssocArray); |
| 375 | +$rerouteConfig = RerouteConfig::from($jsonStringOrObjectOrAssocArray); |
| 376 | +$bccConfig = BccConfig::from($jsonStringOrObjectOrAssocArray); |
| 377 | +$emailConfig = EmailConfig::from($jsonStringOrObjectOrAssocArray); |
| 378 | +``` |
| 379 | + |
| 380 | +# Development Notes |
| 381 | + |
| 382 | +Most PHPUnit tests will not be executed when there is no SMTP server or database available. The unit tests will check |
| 383 | +for environment variable `EMAIL_TEST_SMTP` and `EMAIL_DATABASE`. There is a bash script available, |
| 384 | +[`set-test-env.sh`](https://github.com/technicalguru/php-email/blob/set-test-env.sh) that creates those |
| 385 | +variables for you. Copy it to e.g. `set-local-test-env.sh` and follow instructions in the file. |
| 386 | + |
| 387 | +# Contribution |
| 388 | +Report a bug, request an enhancement or pull request at the [GitHub Issue Tracker](https://github.com/technicalguru/php-email/issues). |
0 commit comments