forked from emaijala/MLInvoice
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmailer.php
More file actions
executable file
·331 lines (307 loc) · 10.1 KB
/
mailer.php
File metadata and controls
executable file
·331 lines (307 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
<?php
/**
* Email handler
*
* PHP version 5
*
* Copyright (C) Ere Maijala 2018.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category MLInvoice
* @package MLInvoice\Base
* @author Ere Maijala <ere@labs.fi>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link http://labs.fi/mlinvoice.eng.php
*/
require_once 'translator.php';
require_once 'settings.php';
/**
* Email handling
*
* @category MLInvoice
* @package MLInvoice\Base
* @author Ere Maijala <ere@labs.fi>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link http://labs.fi/mlinvoice.eng.php
*/
class Mailer
{
/**
* Any error that occurred while sending email
*
* @var string
*/
protected $error = '';
/**
* Return any error that occurred while sending email
*
* @return string
*/
public function getErrorMessage()
{
return $this->error;
}
/**
* Send email
*
* @param string $from "From" address
* @param array $to "To" addresses
* @param array $cc "CC" addresses
* @param array $bcc "BCC" addresses
* @param string $subject Subject
* @param string $body Message body
* @param string $attachments Attachments
*
* @return bool Success
*/
public function sendEmail($from, $to, $cc, $bcc, $subject, $body, $attachments)
{
mb_internal_encoding('UTF-8');
$message = new Swift_Message(
$subject,
$this->getFlowedBody($body),
'text/plain; format="flowed"'
);
$this->error = '';
try {
$message->setFrom($this->extractNameAndAddress($from));
} catch (Swift_RfcComplianceException $e) {
$this->error = Translator::translate(
'InvalidEmailAddress', ['%%email%%' => $from]
);
return false;
}
try {
$message->setTo($this->extractAddresses($to));
} catch (Swift_RfcComplianceException $e) {
$this->error = Translator::translate(
'InvalidEmailAddress', ['%%email%%' => $to]
);
return false;
}
try {
$message->setCc($this->extractAddresses($cc));
} catch (Swift_RfcComplianceException $e) {
$this->error = Translator::translate(
'InvalidEmailAddress', ['%%email%%' => $cc]
);
return false;
}
try {
$message->setBcc($this->extractAddresses($bcc));
} catch (Swift_RfcComplianceException $e) {
$this->error = Translator::translate(
'InvalidEmailAddress', ['%%email%%' => $bcc]
);
return false;
}
foreach ($attachments as $current) {
$attachment = new Swift_Attachment(
$current['data'], $current['filename'], $current['mimetype']
);
$message->attach($attachment);
}
$headers = $message->getHeaders();
$headers->addTextHeader('X-Mailer', 'MLInvoice');
$settings = isset($GLOBALS['mlinvoice_mail_settings'])
? $GLOBALS['mlinvoice_mail_settings'] : [];
if (!isset($settings['send_method']) || 'mail' === $settings['send_method']
) {
$result = $this->sendWithMail($message);
if (!$result) {
$this->error = Translator::translate('EmailFailed');
return false;
}
return true;
} elseif ('sendmail' === $settings['send_method']) {
$command = empty($settings['sendmail']['command'])
? '/usr/sbin/sendmail -bs'
: $settings['sendmail']['command'];
$transport = new Swift_SendmailTransport($command);
} elseif ('smtp' === $settings['send_method']) {
$smtp = empty($settings['smtp']) ? [] : $settings['smtp'];
$transport = new Swift_SmtpTransport(
$smtp['host'], $smtp['port'], $smtp['security']
);
if (!empty($smtp['username'])) {
$transport->setUsername($smtp['username']);
}
if (!empty($smtp['password'])) {
$transport->setPassword($smtp['password']);
}
if (!empty($smtp['stream_context_options'])) {
$transport->setStreamOptions($smtp['stream_context_options']);
}
}
$mailer = new Swift_Mailer($transport);
try {
$result = $mailer->send($message);
if (!$result) {
$this->error = Translator::translate('EmailFailed');
return false;
}
} catch (Exception $e) {
$this->error = Translator::translate('EmailFailed') . ': '
. $e->getMessage();
return false;
}
return true;
}
/**
* Send email using PHP's mail function
*
* Partially lifted from Swift 5.x MailTransport
*
* @param Swift_Message $message Message to send
*
* @return bool
*/
protected function sendWithMail(Swift_Message $message)
{
$toHeader = $message->getHeaders()->get('To');
$subjectHeader = $message->getHeaders()->get('Subject');
$to = $toHeader ? $toHeader->getFieldBody() : '';
$subject = $subjectHeader ? $subjectHeader->getFieldBody() : '';
// Remove headers that would otherwise be duplicated by the mail function
$message->getHeaders()->remove('To');
$message->getHeaders()->remove('Subject');
$messageStr = $message->toString();
// Separate headers from body
if (false !== $endHeaders = strpos($messageStr, "\r\n\r\n")) {
$headers = substr($messageStr, 0, $endHeaders) . "\r\n"; //Keep last EOL
$body = substr($messageStr, $endHeaders + 4);
} else {
$headers = $messageStr . "\r\n";
$body = '';
}
if ("\r\n" !== PHP_EOL) {
// Non-windows (not using SMTP)
$headers = str_replace("\r\n", PHP_EOL, $headers);
$subject = str_replace("\r\n", PHP_EOL, $subject);
$body = str_replace("\r\n", PHP_EOL, $body);
$to = str_replace("\r\n", PHP_EOL, $to);
} else {
// Windows, using SMTP
$headers = str_replace("\r\n.", "\r\n..", $headers);
$subject = str_replace("\r\n.", "\r\n..", $subject);
$body = str_replace("\r\n.", "\r\n..", $body);
$to = str_replace("\r\n.", "\r\n..", $to);
}
return mail($to, $subject, $body, $headers);
}
/**
* Convert a message body to the flowed format
*
* @param string $body Message body
*
* @return string
*/
protected function getFlowedBody($body)
{
$body = condUtf8Encode($body);
$lines = [];
foreach (explode(PHP_EOL, $body) as $paragraph) {
$line = '';
foreach (explode(' ', $paragraph) as $word) {
if (strlen($line) + strlen($word) > 66) {
$lines[] = "$line ";
$line = '';
}
if ($line) {
$line .= " $word";
} elseif ($word) {
$line = $word;
} else {
$line = ' ';
}
}
$line = rtrim($line);
$line = preg_replace('/\s+' . PHP_EOL . '$/', PHP_EOL, $line);
$lines[] = rtrim($line, ' ');
}
$result = '';
foreach ($lines as $line) {
$result .= chunk_split($line, 998, PHP_EOL);
}
return $result;
}
/**
* Extract an email address from a string that may also contain a name
*
* @param string $address Email address
*
* @return string
*/
protected function extractAddress($address)
{
if (preg_match('/<(.+)>/', $address, $matches)) {
return $matches[1];
}
return $address;
}
/**
* Extract name from an email address string
*
* @param string $address Email address
*
* @return string
*/
protected function extractName($address)
{
if (preg_match('/(.+)\s*<.+>/', $address, $matches)) {
return $matches[1];
}
return '';
}
/**
* Extract name and address from an email address string
*
* @param string $address Email address
*
* @return array
*/
protected function extractNameAndAddress($address)
{
$name = $this->extractName($address);
$address = $this->extractAddress($address);
return trim($name) === '' ? $address : [$address => $name];
}
/**
* Extract names and addresses from an array of email addresses
*
* @param array $addresses Email addresses
*
* @return array
*/
protected function extractAddresses($addresses)
{
$result = [];
if ($addresses) {
if (is_string($addresses)) {
$addresses = array_map('trim', str_getcsv($addresses));
}
foreach ($addresses as $idx => $address) {
$name = $this->extractName($address);
$addr = $this->extractAddress($address);
if (trim($name) !== '') {
$result[$addr] = $name;
} else {
$result[$idx] = $addr;
}
}
}
return $result;
}
}