2011-04-13 58 views
0

嘿,那裏,我無法在我正在工作的服務器上重新編譯PHP,所以我相信我是處理此功能的最佳選擇(我們公司最近已將其移至GoogleApps以獲取電子郵件)是通過一些基於socket的電子郵件。問題似乎是,當我實際發送郵件時,標題和消息以內聯方式顯示,而不是作爲附件顯示。我認爲這可能是一個簡單的修復,我只是缺少一些東西通過Google SMTP在PHP中發送附件的問題

我下載了一個很棒的smtp郵件類,但它沒有附件的任何功能,所以我不得不手動修改這個類。本課最初由@author wooptoo編寫,http://wooptoo.com。在不把自己的工作widly在互聯網上我只打算髮布相關的代碼部分的利益:

function attach($attachments){ 
$semi_rand = md5(time()); 
$this->mimeBoundary = "==Multipart_Boundary_x{$semi_rand}x"; 
$fileatt = $attachments[0]["file"]; // Path to the file  
$fileatt_type = $attachments[0]["content_type"]; // File Type  
$fileatt_name = basename($attachments[0]["file"]); // Filename that will be used for the file as the attachment  
$file = fopen($fileatt,'rb'); 
$data = fread($file,filesize($fileatt)); 
fclose($file); 
$data = chunk_split(base64_encode($data)); 
$email_message = "--{$this->mimeBoundary}\n" . 
"Content-Type: {$fileatt_type};\n" . 
" name=\"{$fileatt_name}\"\n" . 
//"Content-Disposition: attachment;\n" . 
//" filename=\"{$fileatt_name}\"\n" . 
"Content-Transfer-Encoding: base64\n\n" . 
    $data . "\n\n" . 
    "--$this->mimeBoundary\n"; 
$this->hasAttachment = '1'; 
$this->attachmentData = $email_message; 
} 

以上套附件郵件的對象,下面的代碼並將其發送

function send($from, $to, $subject, $message, $headers=null) { 
if($this->hasAttachment == '1') 
{ 
    $headers .= "\nMIME-Version: 1.0\n" . 
    "Content-Type: multipart/mixed;\n" . 
    " boundary=\"{$this->mimeBoundary}\""; 
    $message .= "This is a multi-part message in MIME format.\n\n" . 
    "--{$this->mimeBoundary}\n" . 
    "Content-Type:text/plain; charset=\"iso-8859-1\"\n" . 
    "Content-Transfer-Encoding: 7bit\n\n" . $message ."\n\n" . 
    $this->attachmentData; 
} 
    fputs($this->conn, 'MAIL FROM: <'. $from .'>'. $this->nl); 
    fgets($this->conn); 
    fputs($this->conn, 'RCPT TO: <'. $to .'>'. $this->nl); 
    fgets($this->conn); 
    fputs($this->conn, 'DATA'. $this->nl); 
    fgets($this->conn); 
    fputs($this->conn, 
     'From: '. $from .$this->nl. 
     'To: '. $to .$this->nl. 
     'Subject: '. $subject .$this->nl. 
     $headers .$this->nl. 
     $this->nl. 
     $message . $this->nl. 
     '.' .$this->nl 
    ); 

    fgets($this->conn); 
    return; 
} 
+1

你爲什麼不嘗試phpmailer? – halfdan 2011-04-13 19:07:33

+1

http://phpmailer.worxware.com或http://swiftmailer.org兩者都可以做你正在做的事情,使用FAR更少的麻煩,更好的診斷。 – 2011-04-13 19:08:35

+0

我一直在避免phpmailer,因爲當我去那裏瘋狂的惡意軟件警告谷歌彈出。我會檢查這兩個 – DaOgre 2011-04-13 20:08:11

回答

0

如果您有興趣,我爲Swiftmailer寫了a Facade。下面的例子:

$transport = new Swift_SmtpTransport(...); 

SwiftMail::setDefaultTransport($transport); 

SwiftMail::newInstance($subject, $message) 
    ->attachFile($path, $contentType) 
    ->setFrom(...) 
    ->setTo(...) 
    ->send();