source: Common/Mail.php

Last change on this file was 15, checked in by chronos, 17 months ago
  • Modified: Updates and fixes.
File size: 8.2 KB
Line 
1<?php
2
3define('DISPOSITION_INLINE', 'inline');
4define('DISPOSITION_ATTACHMENT', 'attachment');
5
6define('CHARSET_ASCII', 'us-ascii');
7define('CHARSET_UTF8', 'utf-8');
8
9class Mail
10{
11 public string $Subject;
12 public string $From;
13 public array $Recipients;
14 public array $Bodies;
15 public array $Attachments;
16 public string $AgentIdent;
17 public string $Organization;
18 public string $ReplyTo;
19 public array $Headers;
20 private array $Priorities;
21 private string $Boundary;
22 public bool $TestMode;
23
24 function __construct()
25 {
26 $this->Priorities = array('1 (Highest)', '2 (High)', '3 (Normal)', '4 (Low)', '5 (Lowest)');
27 $this->Boundary = md5(date('r', time()));
28 $this->AgentIdent = 'PHP/Mail';
29 $this->TestMode = false;
30 $this->Clear();
31 }
32
33 function Clear(): void
34 {
35 $this->Bodies = array();
36 $this->Attachments = array();
37 $this->Recipients = array();
38 $this->SenderAddress = '';
39 $this->SenderName = '';
40 $this->Subject = '';
41 $this->Organization = '';
42 $this->ReplyTo = '';
43 $this->Headers = array();
44 }
45
46 function AddToCombined(string $Address): void
47 {
48 $this->Recipients[] = array('Address' => $Address, 'Type' => 'SendCombined');
49 }
50
51 function AddTo(string $Address, string $Name): void
52 {
53 $this->Recipients[] = array('Address' => $Address, 'Name' => $Name, 'Type' => 'Send');
54 }
55
56 function AddCc(string $Address, string $Name): void
57 {
58 $this->Recipients[] = array('Address' => $Address, 'Name' => $Name, 'Type' => 'Copy');
59 }
60
61 function AddBcc(string $Address, string $Name): void
62 {
63 $this->Recipients[] = array('Address' => $Address, 'Name' => $Name, 'Type' => 'HiddenCopy');
64 }
65
66 function AddBody(string $Content, string $MimeType = 'text/plain', string $Charset = 'utf-8'): void
67 {
68 $this->Bodies[] = array('Content' => $Content, 'Type' => strtolower($MimeType),
69 'Charset' => strtolower($Charset));
70 }
71
72 function Organization(string $org): void
73 {
74 if (trim($org != '')) $this->xheaders['Organization'] = $org;
75 }
76
77 function Priority(int $Priority): bool
78 {
79 if (!intval($Priority)) return false;
80
81 if (!isset($this->Priorities[$Priority - 1])) return false;
82
83 $this->xheaders['X-Priority'] = $this->Priorities[$Priority - 1];
84 return true;
85 }
86
87 function AttachFile($FileName, $FileType, $Disposition = DISPOSITION_ATTACHMENT): void
88 {
89 $this->Attachments[] = array('FileName' => $FileName, 'FileType' => $FileType,
90 'Disposition' => $Disposition, 'Type' => 'File');
91 }
92
93 function AttachData($FileName, $FileType, $Data, $Disposition = DISPOSITION_ATTACHMENT): void
94 {
95 $this->Attachments[] = array('FileName' => $FileName, 'FileType' => $FileType,
96 'Disposition' => $Disposition, 'Type' => 'Data', 'Data' => $Data);
97 }
98
99 function Send(): bool
100 {
101 if (count($this->Bodies) == 0) throw new Exception(T('Mail message need at least one text body'));
102
103 $Body = $this->BuildAttachment($this->BuildBody());
104
105 $To = '';
106 $this->Headers['CC'] = '';
107 $this->Headers['BCC'] = '';
108 foreach ($this->Recipients as $Index => $Recipient)
109 {
110 if ($Recipient['Type'] == 'SendCombined')
111 {
112 if ($Index > 0) $To .= ', ';
113 $To .= $Recipient['Address'];
114 } else
115 if ($Recipient['Type'] == 'Send')
116 {
117 if ($Index > 0) $To .= ', ';
118 $To .= $Recipient['Name'].' <'.$Recipient['Address'].'>';
119 } else
120 if ($Recipient['Type'] == 'Copy')
121 {
122 if ($Index > 0) $this->Headers['CC'] .= ', ';
123 $this->Headers['CC'] .= $Recipient['Name'].' <'.$To['Address'].'>';
124 } else
125 if ($Recipient['Type'] == 'HiddenCopy')
126 {
127 if ($Index > 0) $this->Headers['BCC'] .= ', ';
128 $this->Headers['BCC'] .= $Recipient['Name'].' <'.$To['Address'].'>';
129 }
130 }
131 if ($To == '') throw new Exception(T('Mail message need at least one recipient address'));
132
133 $this->Headers['Mime-Version'] = '1.0';
134
135 if ($this->AgentIdent != '') $this->Headers['X-Mailer'] = $this->AgentIdent;
136 if ($this->ReplyTo != '') $this->Headers['Reply-To'] = $this->ReplyTo;
137 if ($this->From != '')
138 {
139 $IndexStart = strpos($this->From, '<');
140 if ($IndexStart !== false)
141 {
142 $this->Headers['From'] = '=?utf-8?Q?'.quoted_printable_encode(trim(substr($this->From, 0, $IndexStart))).'?= '.substr($this->From, $IndexStart);
143 } else
144 {
145 $this->Headers['From'] = $this->From;
146 }
147 }
148
149 $Headers = '';
150 foreach ($this->Headers as $Header => $Value)
151 {
152 if (($Header != 'Subject') and ($Value != '')) $Headers .= $Header.': '.$Value."\n";
153 }
154
155 $this->Subject = strtr($this->Subject, "\r\n", ' ');
156
157 if ($this->Subject == '') throw new Exception(T('Mail message missing Subject'));
158
159 if ($this->TestMode)
160 {
161 echo('to: '.$To.', subject: '.$this->Subject.', body: '.$Body.', headers: '.$Headers);
162 $res = true;
163 } else
164 {
165 $res = mail($To, $this->Subject, $Body, $Headers);
166 }
167 return $res;
168 }
169
170 function ValidEmail(string $Address): bool
171 {
172 if (preg_match(".*<(.+)>", $Address, $regs)) $Address = $regs[1];
173 if (preg_match("^[^@ ]+@([a-zA-Z0-9\-]+\.)+([a-zA-Z0-9\-]{2}|net|com|gov|mil|org|edu|int)\$", $Address))
174 return true;
175 else return false;
176 }
177
178 function CheckAdresses(array $Addresses): void
179 {
180 foreach ($Addresses as $Address)
181 {
182 if (!$this->ValidEmail($Address))
183 {
184 throw new Exception(sprintf(T('Mail message invalid address %s'), $Address));
185 }
186 }
187 }
188
189 private function ContentEncoding($Charset): string
190 {
191 if ($Charset != CHARSET_ASCII) return '8bit';
192 else return '7bit';
193 }
194
195 private function BuildAttachment($Body): string
196 {
197 if (count($this->Attachments) > 0)
198 {
199 $this->Headers['Content-Type'] = "multipart/mixed;\n boundary=\"PHP-mixed-".$this->Boundary."\"";
200 $Result = "This is a multi-part message in MIME format.\n".
201 "--PHP-mixed-".$this->Boundary."\n";
202 $Result .= $Body;
203
204 foreach ($this->Attachments as $Attachment)
205 {
206 $FileName = $Attachment['FileName'];
207 $BaseName = basename($FileName);
208 $ContentType = $Attachment['FileType'];
209 $Disposition = $Attachment['Disposition'];
210 if ($Attachment['Type'] == 'File')
211 {
212 if (!file_exists($FileName))
213 throw new Exception(sprintf(T('Mail message attached file %s can\'t be found'), $FileName));
214 $Data = file_get_contents($FileName);
215 } else
216 if ($Attachment['Type'] == 'Data') $Data = $Attachment['Data'];
217 else $Data = '';
218
219 $Result .= "\n".'--PHP-mixed-'.$this->Boundary."\n".
220 "Content-Type: ".$ContentType."; name=\"".$BaseName."\"\n".
221 "Content-Transfer-Encoding: base64\n".
222 "Content-Disposition: ".$Disposition."\n\n";
223 $Result .= chunk_split(base64_encode($Data))."\r\n";
224 }
225 } else $Result = $Body;
226 return $Result;
227 }
228
229 private function BuildBody(): string
230 {
231 $Result = '';
232 if (count($this->Bodies) > 1)
233 {
234 $this->Headers['Content-Type'] = 'multipart/alternative; boundary="PHP-alt-'.$this->Boundary.'"';
235 $Result .= 'Content-Type: multipart/alternative; boundary="PHP-alt-'.$this->Boundary.'"'.
236 "\n\n";
237 } else
238 {
239 $this->Headers['Content-Type'] = $this->Bodies[0]['Type'].'; charset='.$this->Bodies[0]['Charset'];
240 $this->Headers['Content-Transfer-Encoding'] = $this->ContentEncoding($this->Bodies[0]['Charset']);
241 }
242
243 foreach ($this->Bodies as $Body)
244 {
245 if (count($this->Bodies) > 1) $Result .= "\n\n".'--PHP-alt-'.$this->Boundary."\n";
246 $Result .= 'Content-Type: '.$Body['Type'].'; charset='.$Body['Charset'].
247 "\nContent-Transfer-Encoding: ".$this->ContentEncoding($Body['Charset'])."\n\n".$Body['Content']."\n";
248 }
249 return $Result;
250 }
251}
252
253/*
254// Example
255$Mail = new Mail();
256$Mail->AddTo('nobody@nodomain', 'Recipient');
257$Mail->From = 'No reply <noreply@nodomain>';
258$Mail->Subject = 'Test message';
259$Mail->AddBody('This is sample message sent by PHP Mail class');
260$Mail->AddBody('This is sample <strong>HTML</strong> message sent by <i>PHP Mail class</i>', 'text/html');
261$Mail->AttachFile('mailtest.php', 'text/plain');
262$Mail->AttachData('DataFile.txt', 'text/plain', 'Sample text');
263$Mail->Send();
264*/
Note: See TracBrowser for help on using the repository browser.