Problems Sending Attachments in PHP through Google SMTP
Hey there, I'm unable to recompile PHP on the server I'm working on, so I believe my best option for handling this functionality (our company recently moved to GoogleApps for email) is via some socket based email. The issue seems to be that when I actually send the mail, the headers and message appear inline, and not as an attachment. I think this is probably an easy fix and I'm just missing something
I downloaded a great smtp mail class, but it didn't have any functionality for attachments so I had to manually alter the class. This class was originally written by @author wooptoo, http://wooptoo.com. In the interest of not putting their work widly out on the internet I'm only going to post the relevant code portions:
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->a开发者_StackOverflow中文版ttachmentData = $email_message;
}
The above sets the attachment to the mail object, and the below code sends it
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;
}
If you're interested I wrote a Facade for Swiftmailer. Below an example:
$transport = new Swift_SmtpTransport(...);
SwiftMail::setDefaultTransport($transport);
SwiftMail::newInstance($subject, $message)
->attachFile($path, $contentType)
->setFrom(...)
->setTo(...)
->send();
精彩评论