Errore invio mail con allegato

Ciao a tutti,

ho casualmente scoperto questo framework e ho deciso di usarlo per un semplice sito di invio documenti tramite email.

Sono riuscito con poco sforzo ad implementare l’autenticazione con ldap e gestire l’autorizzazione per utenti guest/loggati/admin.

Tutto funziona correttamente se non fosse che le email vengono inviate solo se prive d’allegato!

il codice che uso per l’invio è il seguente:




    public function sendEmail() {

        if ($this->validate()) {

            $mail = Yii::$app->mailer->compose()

                    ->setTo($this->receiver)

                    ->setFrom(Yii::$app->params['sender'])

                    ->setSubject($this->subject)

                    ->setTextBody($this->body);

            foreach ($this->docs as $doc) {

                $filename = realpath('.' . DocsController::getDocFullPath($doc));

                $mail->attach(Swift_Attachment::fromPath($filename));

            }

            $mail->send();


            return true;

        }

        return false;

    }



la funzione DocsController::getDocFullPath è semplicemente la seguente




    public static function getDocFullPath($filename) {

        return Yii::$aliases['@web'] . '/docs/' . $filename;

    }



L’errore che ricevo è:




PHP Warning – yii\base\ErrorException


fopen(Content-Type: application/pdf; name=Documento.pdf

Content-Transfer-Encoding: base64

Content-Disposition: attachment; filename=Documento.pdf


JVBERi0xLjUNJeLjz9MNCjQxIDAgb2JqDTw8L0xpbmVhcml6....Rg0K): failed to open stream: Invalid argument

1. in /Users/alessio/Documents/NetBeansProjects/PHP/FaxEmail/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ByteStream/FileByteStream.php at line 142

133134135136137138139140141142143144145146147148149150151    /** Not used */

    protected function _flush()

    {

    }

 

    /** Get the resource for reading */

    private function _getReadHandle()

    {

        if (!isset($this->_reader)) {

            if (!$this->_reader = fopen($this->_path, 'rb')) {  <-------L'ERRORE È IN QUESTA RIGA

                throw new Swift_IoException(

                    'Unable to open file for reading ['.$this->_path.']'

                );

            }

            if ($this->_offset != 0) {

                $this->_getReadStreamSeekableStatus();

                $this->_seekReadStreamToPosition($this->_offset);

            }

        }




Questo errore capita scegliendo qualsiasi file.

I file esistono e la directory che li contiene ha permessi di lettura e scrittura da chiunque.

commentando la riga $mail->attach(Swift_Attachment::fromPath($filename)); l’invio avviene senza problemi.

Qualcuno sa come risolverlo?

Grazie in anticipo.

Alessio

Ciao a tutti,

al momento ho ovviato al problema usando direttamente la libreria Swift_Mailer senza utilizzare gli Helper del framework.

Il problema è che così facendo si perdono i vantaggi della Dependency Injection.

Riporto di seguito il codice relativo al workaround applicato:




    public function sendEmail() {

        if ($this->validate()) {

            $result = false;

            $message = Swift_Message::newInstance()

                    ->setTo($this->receiver)

                    ->setFrom(Yii::$app->params['sender'])

                    ->setSubject($this->subject)

                    ->setBody($this->body);

            foreach ($this->docs as $doc) {

                $filename = realpath('.' . DocsController::getDocFullPath($doc));

                $message->attach(Swift_Attachment::fromPath($filename));

            }

            $mailer = Swift_Mailer::newInstance($this->prepareTransport());

            if ($mailer->send($message) > 0) {

                Yii::$app->session->setFlash('SendDocFormSubmitted', 'Email o fax inviato correttamente.');

                $result = true;

            } else {

                Yii::$app->session->setFlash('SendDocFormSubmittedFailed', 'Email o fax NON inviato.');

            }

        }

        return $result;

    }






    private function prepareTransport() {

        $mailParams = Yii::$app->params['mail'];

        $transport = Swift_SmtpTransport::newInstance($mailParams['host'], $mailParams['port']);

        if (isset($mailParams['username'])) {

            $transport->setUsername($mailParams['username']);

        }

        if (isset($mailParams['password'])) {

            $transport->setPassword($mailParams['password']);

        }

        if (isset($mailParams['timeout']) && is_numeric($mailParams['timeout'])) {

            $transport->setPassword($mailParams['timeout']);

        }

        if (isset($mailParams['encryption'])) {

            $transport->setEncryption($mailParams['encryption']);

        }

        return $transport;

    }



Inoltre nel file web.php ho aggiunto all’array $params i seguenti parametri:




$params['mail'] = [

    'host' => 'your.smtp.server',

    //'username' => '',

    //'password' => '',

    'port' => '25',

    'timeout' => '120',

    //'encryption' => 'tls',

    ];