【问题标题】:Problems Sending Attachments in PHP through Google SMTP通过 Google SMTP 在 PHP 中发送附件的问题
【发布时间】:2011-04-13 19:03:29
【问题描述】:

嘿,我无法在我正在使用的服务器上重新编译 PHP,所以我相信我处理此功能的最佳选择(我们公司最近转移到 GoogleApps 的电子邮件)是通过一些基于套接字的电子邮件。问题似乎是当我实际发送邮件时,标题和消息显示为内联,而不是作为附件。我认为这可能是一个简单的解决方法,我只是缺少一些东西

我下载了一个很棒的 smtp 邮件类,但它没有任何附件功能,所以我不得不手动更改该类。此类最初由@author woptoo,http://wooptoo.com 编写。为了不将他们的工作大量发布在互联网上,我只会发布相关的代码部分:

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;
}

【问题讨论】:

  • phpmailer.worxware.comswiftmailer.org 中的任何一个都可以完成您正在做的事情,FAR 更少麻烦,FAR 更好的诊断。
  • 我一直在避免使用 phpmailer,因为当我去那里时,谷歌弹出了疯狂的恶意软件警告。不过我会检查这两个

标签: php email smtp gmail


【解决方案1】:

如果您有兴趣,我为 Swiftmailer 写了a Facade。下面是一个例子:

$transport = new Swift_SmtpTransport(...);

SwiftMail::setDefaultTransport($transport);

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

【讨论】:

    猜你喜欢
    • 2023-03-19
    • 2012-12-13
    • 2014-04-25
    • 2011-12-10
    • 1970-01-01
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多