Я использую общий хост и не смог выяснить, как использовать почтовые функции PEAR - все, что я прочитал, похоже, предполагает, что читатель уже знает, как включить PEAR с помощью include ('Mail.php' ) - но никто не говорит, как получить файл Mail.php. Urgh.
В любом случае, мои приложения отправляют электронные письма нечасто и только нескольким получателям за раз. Поэтому я чувствую, что с помощью почтовой утилиты php все в порядке.
Кроме того, иногда мои вложения генерируются динамически, поэтому я оставляю chunk_split вне метода, чтобы я мог легко прикрепить фактический файл или просто сгенерировать данные и прикрепить их в виде файла.
Вот простой класс электронной почты, который на самом деле был протестирован:
<?php
class MyMail {
private function getMimeType ($fileName) {
$mime_types = array("pdf"=>"application/pdf","zip"=>"application/zip","csv"=>"text/plain","doc"=>"application/msword"
,"docx"=>"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
,"xls"=>"application/vnd.ms-excel","xlsx"=>"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
,"ppt"=>"application/vnd.ms-powerpoint","pptx"=>"application/vnd.openxmlformats-officedocument.presentationml.presentation"
,"gif"=>"image/gif","png"=>"image/png","jpeg"=>"image/jpg","jpg"=>"image/jpg","mp3"=>"audio/mpeg","wav"=>"audio/x-wav"
,"mpeg"=>"video/mpeg","mpg"=>"video/mpeg","mpe"=>"video/mpeg","css"=>"text/css","js"=>"application/javascript"
,"php"=>"text/plain","htm"=>"text/html","html"=>"text/html","txt"=>"text/plain");
$extension = explode('.',$fileName);
$extension = end($extension);
$extension = strtolower($extension);
if(isset($mime_types[$extension]))
return $mime_types[$extension];
return "application/octet-stream";
}
private $to = '';
private $subject = '';
private $returnPath = '';
private $attachments = array();
private $recipients = array('from' => '', 'reply' => '');
private $message = '';
public function setTo($s) { // comma separated list
$this->to = $s;
}
public function setSubject($s) {
$this->subject = $s;
}
public function setFrom($s) { // one email address only!
$this->recipients['from'] = "From: $s";
}
public function setReturnPath($s) { // one email address only!
$this->returnPath = "-r $s";
}
public function setReplyTo($s) {
$this->recipients['reply'] = "Reply-To: $s";
}
public function setCc($s) { // comma separated list
$this->recipients['cc'] = "Cc: $s";
}
public function setBcc($s) { // comma separated list
$this->recipients['bcc'] = "Bcc: $s";
}
public function setMessage($s) { // be carefull to include strategic nl and spaces for text only presentation -- which uses strip_tags()
$this->message = $s;
}
public function setAttachment($fileName, $data) {
$this->attachments[] = array('name' => $fileName, 'data' => $data);
}
public function send() {
$attachments = ( count($this->attachments) > 0 );
$altMarker = '===_Alt_BOUNDRY_' . md5(uniqid(time()));
$mixedMarker = str_replace('Alt', 'Mixed', $altMarker);
$txtMsg = strip_tags($this->message);
$htmlMsg = "<!DOCTYPE html>\n<html>\n<head>\n";
$htmlMsg .= '<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">';
$htmlMsg .= "\n</head>\n<body>\n";
$htmlMsg .= $this->message;
$htmlMsg .= "\n</body>\n</html>";
$h = array();
preg_match('/<([^<>]+)>$|^\bFrom: ([^<>]+)\b$/',$this->recipients['from'], $a);
$nakedFrom = !empty($a[1]) ? $a[1] : $a[2];
if( empty($this->returnPath) )
$this->returnPath = '-r ' . $nakedFrom;
if( empty($this->recipients['reply']) )
$this->recipients['reply'] = 'Reply-To: ' . str_replace('From: ','',$this->recipients['from']);
foreach ($this->recipients as $v)
$h[] = $v;
$h[] = "MIME-Version: 1.0";
if( $attachments ) {
$h[] = 'Content-Type: multipart/mixed; boundary="' . $mixedMarker . '"';
$h[] = '';
$h[] = '--' . $mixedMarker;
}
$h[] = 'Content-Type: multipart/alternative; boundary="' . $altMarker . '"';
$h[] = '';
$h[] = '--' . $altMarker;
$h[] = 'Content-Type: text/plain; charset=iso-8859-1';
$h[] = 'Content-Transfer-Encoding: 7bit';
$h[] = '';
$h[] = $txtMsg;
$h[] = '--' . $altMarker;
$h[] = 'Content-Type: text/html; charset=iso-8859-1';
$h[] = 'Content-Transfer-Encoding: 7bit';
$h[] = '';
$h[] = $htmlMsg;
$h[] = '--' . $altMarker . '--';
$h[] = '';
foreach( $this->attachments as $v ) {
$h[] = '--' . $mixedMarker;
$h[] = 'Content-Type: ' . $this->getMimeType ($v['name']) . ';';
$h[] = ' name="' . $v['name'] . '"';
$h[] = 'Content-Transfer-Encoding: base64';
$h[] = 'Content-Disposition: attachment;';
$h[] = ' filename="' . $v['name'] . '"';
$h[] = ''; /* skip */
$h[] = $v['data'];
}
if( $attachments )
$h[] = '--' . $mixedMarker . '--';
return (mail( $this->to, $this->subject, null, implode("\r\n", $h ), $this->returnPath) ? true : false);
}
}
* - ИСПОЛЬЗОВАНИЕ: *
$mail = new MyMail;
$mail->setSubject( ' Testing 123 Subject' );
$mail->setFrom( 'me <testFrom@abc.com>' );
$mail->setTo( 'Anne Test <atest@example.com>' );
$mail->setCc('Jeff Test <jtest@example.com>, Mary Test <mtest@example.com>');
$mail->setMessage( "<h1>This is a test</h1>\n\n<p>This is a para</p>" ); // note the nl added in case mail opens as pure text...
// dynamically produced file data
$mail->setAttachment( $fileName1,
chunk_split(base64_encode($attachmentData1)) );
// attach actual file
$mail->setAttachment( $fileName2,
chunk_split(base64_encode(file_get_contents('testFile.pdf'))) );
echo ( $mail->send() ) ? 'sent' : 'oops';