2011-04-13 64 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();