Search code examples
phpemailgmailemail-attachmentsmagento-1.8

Email attachments from outside sources not working


I've recently created a page on our site where users can upload an image and email it to an email address set up specifically to keep the uploaded documents.

I've tested this myself and it works, with the attachments arriving in gmail as expected.

However, whenever someone from outside uses this feature the attachment in the email is unavailable, or not could not be loaded, when we try to open it.

The code is split between 2 files, a controller and a helper. Here's the code (For the sake of saving some space I've removed all error checks, but in the actual code they are all still in place and not picking up any errors whatsoever):

controller

$helper = [GET HELPER];
/** Upload the file to a temp location so that we can attach it to an email */
$uploader = new Varien_File_Uploader('filename');
$uploader->setAllowedExtensions(array(
    'image/jpeg',
    'image/jpg',
    'image/png',
    'application/pdf'
))
    ->setAllowRenameFiles(true)
    ->setFilesDispersion(false);
$path = $helper->getFileStorageLocation(); // Will store files in /tmp

if (!is_dir($path))
{
    mkdir($path, 0775, true);
}
$uploader->save($path, $_FILES['filename']['name']);

$result = $helper->sendMail($_FILES['filename']['name']);

if ($result)
{
    $uploadSuccess = true;
    /** Remove the temp file */
    unlink($path . DS . $_FILES['filename']['name']);
}

helper

/** Declare variables */
$order = Mage::getModel('sales/order')->load($orderId);
$file_incremented_id = $order->getIncrementId();
$copyTo = $this->getCopyTo();
$copyFrom = $this->getCopyFrom();
$subject = 'proof of upload for ' . $file_incremented_id;
$copyTo = explode(',', $copyTo);
$body = '<span>Please see attachment</span>';
$file = $this->getFileStorageLocation() . DS . $filename; // function receives filename from whatever is calling it
$attachment = file_get_contents($file);
$extension = pathinfo($file, PATHINFO_EXTENSION);

if (!$copyTo)
{
    return false;
}

$mail = Mage::getModel('core/email_template');
$mail->setSenderName('Uploader');
$mail->setSenderEmail($copyFrom);
$mail->setTemplateSubject($subject);
$mail->setTemplateText($body);
$mail->getMail()->createAttachment(
    $attachement,
    Zend_Mime::TYPE_OCTETSTREAM,
    Zend_Mime::DISPOSITION_ATTACHMENT,
    Zend_Mime::ENCODING_BASE64,
    $file_incremented_id . '.' . $extension // Set order number as file name
);

try
{
    $mail->send($copyTo);
    return true;
}
catch (Exception $e)
{
    return false;
}

Can anyone see anything that might be causing the issue, or think of what it might be based on my explanation of the setup?


Solution

  • So the problem, in the end, was filesize. My fault for not posting the $_FILES variable.

    I saw it a bit later and the variable had error = 1, meaning that the file's size was larger than what was allowed by the max_upload_filesize in the php.ini