addAttachment() public méthode

Adds an existing attachment to the mail message
public addAttachment ( Zend_Mime_Part $attachment ) : Zend_Mail
$attachment Zend_Mime_Part
Résultat Zend_Mail Provides fluent interface
 /**
  * Envia e-mail para usuário com dados iniciais, como username (e-mail) e senha.
  * @param int $idpessoa
  * @param int $idEncrontro
  * @param int $tipoMensagem use as constantes definidas acima [ MSG_CONFIRMACAO, MSG_RECUPERAR_SENHA ].
  * @param binary $pdf arquivo PDF em string binária, se não for null será enviado ao usuário em anexo
  * @throws Exception
  */
 public function send($id_pessoa, $id_encontro, $tipoMensagem = Application_Model_EmailConfirmacao::MSG_CONFIRMACAO, $pdf = null)
 {
     $mail = new Zend_Mail();
     $pessoa = new Application_Model_Pessoa();
     $linha = $pessoa->find($id_pessoa)->current();
     $emailText = $this->obterMensagem($id_encontro, $tipoMensagem);
     switch ($tipoMensagem) {
         case Application_Model_EmailConfirmacao::MSG_CONFIRMACAO:
         case Application_Model_EmailConfirmacao::MSG_RECUPERAR_SENHA:
             $result = $pessoa->gerarToken($id_pessoa);
             $link = "http://" . $_SERVER["SERVER_NAME"] . "/index/definir-senha/hashedToken/" . $result['hashedToken'] . "/id/" . $id_pessoa;
             break;
         case Application_Model_EmailConfirmacao::MSG_CONFIRMACAO_REINSCRICAO:
             $link = "";
             break;
         default:
             throw new Exception(_("Send e-mail option not defined."));
     }
     $emailText->mensagem = str_replace('{nome}', $linha->nome, $emailText->mensagem);
     $emailText->mensagem = str_replace('{email}', $linha->email, $emailText->mensagem);
     $emailText->mensagem = str_replace('{href_link}', $link, $emailText->mensagem);
     $mail->setBodyHtml(iconv($this->config->email->in_charset, $this->config->email->out_charset, $emailText->mensagem));
     $mail->addTo($linha->email, $linha->nome);
     $mail->setSubject(iconv($this->config->email->in_charset, $this->config->email->out_charset, $emailText->assunto));
     if ($pdf != null) {
         $at = new Zend_Mime_Part($pdf);
         $at->type = 'application/pdf';
         $at->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
         $at->encoding = Zend_Mime::ENCODING_BASE64;
         $at->filename = 'ticket-inscricao.pdf';
         $mail->addAttachment($at);
     }
     $mail->send();
 }
Exemple #2
0
 public function sendAction()
 {
     // 返回值数组
     $result = array();
     // 请求参数
     // $request = $this->getRequest()->getParams();
     $now = date('Y-m-d H:i:s');
     /* $data = array(
                'subject'       => $request['subject'],
                'to'            => $request['to'],
                'to_name'       => $request['to_name'],
                'cc'            => $request['cc'],
                'cc_name'       => $request['cc_name'],
                'content'       => $request['content'],
                'attachment'    => $request['attachment']
        ); */
     $data = array('subject' => 'test', 'to' => '*****@*****.**', 'to_name' => '新大陆', 'cc' => '*****@*****.**', 'cc_name' => 'leon', 'content' => 'test123测试', 'charset' => 'utf-8', 'attachment' => null);
     echo '<pre>';
     print_r($data);
     $mailConfig = new Zend_Config_Ini(CONFIGS_PATH . '/application.ini', 'mail');
     $from = $mailConfig->smtp->from;
     $fromname = $mailConfig->smtp->fromname;
     $transport = new Zend_Mail_Transport_Smtp($mailConfig->smtp->server, $mailConfig->smtp->params->toArray());
     $mail = new Zend_Mail();
     $mail->setSubject($data['subject']);
     $mail->setBodyText($data['content'], $data['charset']);
     $mail->setFrom($from, $fromname);
     $mail->addTo($data['to'], $data['to_name']);
     $mail->addCc($data['cc'], $data['cc_name']);
     $mail->addAttachment('MailController.php');
     $mail->createAttachment(file_get_contents('E:\\sina.png'), 'image/png', Zend_Mime::DISPOSITION_INLINE, Zend_Mime::ENCODING_BASE64, 'sina.png');
     print_r($mail->send($transport));
     //echo Zend_Json::encode($result);
     exit;
 }
 private function sendFile($filePath, $emailAddress, $headerMessage)
 {
     $file = $filePath;
     $mail = new Zend_Mail();
     $mail->setFrom(Yii::app()->params['adminEmail']);
     $mail->addTo($emailAddress);
     $mail->setSubject($headerMessage);
     $mail->setBodyHtml($headerMessage);
     $at = new Zend_Mime_Part(file_get_contents($file));
     $at->type = $this->mime_type($file);
     $at->disposition = Zend_Mime::DISPOSITION_INLINE;
     $at->encoding = Zend_Mime::ENCODING_BASE64;
     $at->filename = basename($file);
     $mail->addAttachment($at);
     return $mail->send();
 }
Exemple #4
0
 /**
  * Fonction d'envoi d'email
  * @param array $params
  * @return send mail
  */
 protected function _sendMail($params)
 {
     $params['message'] .= '<p><i>Email envoyé depuis le fichier ' . $params['file'] . ' le ' . date('Y-m-d-H:i:s') . '</p>';
     //Destinataire du mail
     if ($params['recipient']) {
         $recipient = $params['recipient'];
     } else {
         $recipient = Mage::getStoreConfig('system/hhennes_alerts/alert_email_default_recipient');
     }
     //Gestion des destinataires multiples :
     if (preg_match('#;#', $recipient)) {
         $recipents = explode(';', $recipient);
     }
     //Gestion de l'expéditeur et de son nom
     if (Mage::getStoreConfig('system/hhennes_alerts/alert_email_sender') && Mage::getStoreConfig('system/hhennes_alerts/alert_email_sender') != '') {
         $senderEmail = Mage::getStoreConfig('system/hhennes_alerts/alert_email_sender');
     } else {
         $senderEmail = Mage::getStoreConfig('trans_email/ident_general/email');
     }
     if (Mage::getStoreConfig('system/hhennes_alerts/alert_email_sender_name') && Mage::getStoreConfig('system/hhennes_alerts/alert_email_sender_name') != '') {
         $senderName = Mage::getStoreConfig('system/hhennes_alerts/alert_email_sender_name');
     } else {
         $senderName = Mage::getStoreConfig('trans_email/ident_general/name');
     }
     $mail = new Zend_Mail('UTF-8');
     $mail->setFrom($senderEmail, $senderName);
     //Si destinataires multiples
     if ($recipents) {
         foreach ($recipents as $emailCopy) {
             $mail->addTo($emailCopy);
         }
     } else {
         $mail->addTo($recipient);
     }
     $mail->setSubject($params['subject'])->setBodyHtml($params['message']);
     //Si il y'a une pièce jointe
     if ($params['attachment']) {
         $attachement = new Zend_Mime_Part(file_get_contents($params['attachment']));
         $attachement->type = 'text/csv';
         $attachement->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
         $attachement->encoding = Zend_Mime::ENCODING_BASE64;
         $attachement->filename = $params['attachment_name'];
         $mail->addAttachment($attachement);
     }
     //Envoi de l'email
     $mail->send();
 }
 public function SendExcelByMail($status, $liqId)
 {
     $param = array();
     if ($status) {
         $param = array('compress' => 0, 'Attachment' => 0);
     }
     $html = $this->displayLiqTable($liqId, $filename, $provEmail, $provName);
     $mail = new Zend_Mail('utf-8');
     $at = new Zend_Mime_Part($html);
     $at->type = 'application/vnd.ms-excel';
     $at->disposition = Zend_Mime::DISPOSITION_INLINE;
     $at->encoding = Zend_Mime::ENCODING_BASE64;
     $at->filename = $filename . '.xls';
     $mail->addTo($provEmail);
     $mail->addAttachment($at);
     $mail->setSubject('Notificación de Operación');
     $mail->setBodyHtml("<p>Estimados {$provName}:<br /><br />Buen día, este es un envío automático de la próxima operación que realizaremos. Para ver el archivo adjunto por favor descargalo (opcion DESCARGAR) en tu computadora y luego abrilo, si al abrir aparece algún aviso de error o de cambio de Formato,  simplemente dale 'SI' para afirmar que lo queres abrir, es que el envio llega en un formato WEB.<br /><br />\nEspero la confirmación de que lo hayas recibido para combinar detalles de día y horario. <br /><br />\nSaludo Cordialmente,<br /><br />\nGustavo Yurgel</p>");
     $mail->send();
     return 'success';
 }
Exemple #6
0
 private function sendMail($toEmail, $fromEmail, $fromName, $subject, $body, array $attachments = array())
 {
     $mail = new Zend_Mail('UTF-8');
     $mail->addTo($toEmail)->setFrom($fromEmail, $fromName)->setSubject($subject)->setBodyText($body, null, Zend_Mime::ENCODING_8BIT);
     foreach ($attachments as $attachment) {
         $mail->addAttachment($attachment);
     }
     $mail->send();
 }
 /**
  * check if attachment handling works
  *
  */
 public function testAttachment()
 {
     $mail = new Zend_Mail();
     $mail->setBodyText('My Nice Test Text');
     $mail->addTo('*****@*****.**', 'Test Recipient');
     $mail->setFrom('*****@*****.**', 'Test Sender');
     $mail->setSubject('Test: Attachment Test with Zend_Mail');
     $at = $mail->addAttachment('abcdefghijklmnopqrstuvexyz');
     $at->type = 'image/gif';
     $at->id = 12;
     $at->filename = 'test.gif';
     $mock = new Zend_Mail_Transport_Mock();
     $mail->send($mock);
     // now check what was generated by Zend_Mail.
     // first the mail headers:
     $this->assertContains('Content-Type: multipart/mixed', $mock->header);
     $boundary = $mail->getMimeBoundary();
     $this->assertContains('boundary="' . $boundary . '"', $mock->header);
     $this->assertContains('MIME-Version: 1.0', $mock->header);
     // check body
     // search for first boundary
     $p1 = strpos($mock->body, "--{$boundary}\n");
     $this->assertNotEquals(null, $p1);
     // cut out first (Text) part
     $start1 = $p1 + 3 + strlen($boundary);
     $p2 = strpos($mock->body, "--{$boundary}\n", $start1);
     $this->assertNotEquals(null, $p2);
     $partBody1 = substr($mock->body, $start1, $p2 - $start1);
     $this->assertContains('Content-Type: text/plain', $partBody1);
     $this->assertContains('My Nice Test Text', $partBody1);
     // check second (HTML) part
     // search for end boundary
     $start2 = $p2 + 3 + strlen($boundary);
     $p3 = strpos($mock->body, "--{$boundary}--");
     $this->assertNotEquals(null, $p3);
     $partBody2 = substr($mock->body, $start2, $p3 - $start2);
     $this->assertContains('Content-Type: image/gif', $partBody2);
     $this->assertContains('Content-Transfer-Encoding: base64', $partBody2);
     $this->assertContains('Content-ID: <12>', $partBody2);
 }
 /**
  * Populate mail instance
  *
  * @param Zend_Mail $mail
  * @return Zend_Mail
  */
 public function populate(Zend_Mail $mail)
 {
     if ($this->fromEmail || $this->fromName) {
         $mail->setFrom($this->fromEmail, $this->fromName);
     }
     if ($this->toEmail || $this->toName) {
         $mail->addTo($this->toEmail, $this->toName);
     }
     if ($this->bcc) {
         if (!is_array($this->bcc)) {
             $mail->addBcc($this->bcc);
         } else {
             if (isset($this->bcc['email']) && !empty($this->bcc['email'])) {
                 if (isset($this->bcc['name']) && !empty($this->bcc['name'])) {
                     $mail->addBcc($this->bcc['email'], $this->bcc['name']);
                 } else {
                     $mail->addBcc($this->bcc['email']);
                 }
             } elseif (count($this->bcc)) {
                 foreach ($this->bcc as $bcEmail) {
                     $mail->addBcc($bcEmail);
                 }
             }
         }
     }
     if ($this->subject) {
         $mail->setSubject($this->subject);
     }
     if ($this->bodyHtml) {
         $mail->setBodyHtml($this->bodyHtml);
     }
     if ($this->bodyText) {
         $mail->setBodyText($this->bodyText);
     }
     if ($this->attachments && is_array($this->attachments)) {
         foreach ($this->attachments as $file) {
             if (file_exists($file['path'])) {
                 $fileContent = file_get_contents($file['path']);
                 if ($fileContent) {
                     $attachment = new Zend_Mime_Part($fileContent);
                     $attachment->type = Zend_Mime::TYPE_OCTETSTREAM;
                     $attachment->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
                     $attachment->encoding = Zend_Mime::ENCODING_BASE64;
                     $attachment->filename = basename($file['path']);
                     $attachment->id = md5(time());
                     $attachment->description = $attachment->filename;
                     $mail->addAttachment($attachment);
                 }
             }
         }
     }
     if ($this->sendExternal) {
         $mail->addHeader('SEND_TO_EXTERNAL_SMTP', 'True');
     }
     return $mail;
 }
 function sendMail($mailTo, $mailSubject, $mailMessage, $mailFrom, $mailBcc)
 {
     global $scriptVersion, $returnPath;
     //var_dump($mailFrom);
     if (preg_match('/(.+)(\\s<.+\\@.+>)$/', $mailFrom, $tmp)) {
         $mailFrom_1 = $tmp[1];
         $mailFrom_2 = $tmp[2];
         $tmp[1] = mb_encode_mimeheader($tmp[1]);
         $mailFrom = $tmp[1] . $tmp[2];
     }
     //var_dump($mailFrom);
     $mailHeader = "From: {$mailFrom}\n";
     if ($mailBcc) {
         $mailHeader .= "Bcc: {$mailBcc}\n";
     }
     /*
     		$php_ver = phpversion();
     		$mailHeader .= "X-Mailer: Sapphirus.Biz Formmail/{$scriptVersion}(PHP/{$php_ver})";
     		$mailMessage = preg_replace('/\r\n|\r/', "\n", $mailMessage);
     		if (isset($returnPath) && $returnPath) {
     			mb_send_mail($mailTo, $mailSubject, $mailMessage, $mailHeader, "-f{$returnPath}");
     		} else {
     			mb_send_mail($mailTo, $mailSubject, $mailMessage, $mailHeader);
     		}
     		return true;
     */
     /*
     		$tr = new Zend_Mail_Transport_Sendmail('-f'.'*****@*****.**');
     		Zend_Mail::setDefaultTransport($tr);
     */
     require_once 'Zend/Mail.php';
     require_once 'Zend/Mime/Part.php';
     $mail = new Zend_Mail('iso-2022-jp');
     // 元のエンコーディングを保存
     $orgEncoding = mb_internal_encoding();
     // 変換したい文字列のエンコーディングをセット
     mb_internal_encoding('ISO-2022-JP');
     $mail->setSubject(strtr(mb_encode_mimeheader(mb_convert_encoding($mailSubject, 'ISO-2022-JP', 'euc-jp'), 'iso-2022-jp'), "\r\n\t", '   '));
     if ($mailFrom_1 == '') {
         $mail->setFrom($mailFrom);
     } else {
         $mail->setFrom($mailFrom_2, mb_encode_mimeheader(mb_convert_encoding($mailFrom_1, 'ISO-2022-JP', 'euc-jp'), 'iso-2022-jp'));
     }
     //		$mail->setFrom($mailFrom);
     //		$mail->setFrom($mailFrom_2, mb_encode_mimeheader(mb_convert_encoding($mailFrom_1, 'ISO-2022-JP', 'euc-jp'), 'iso-2022-jp'));
     $mail->addTo($mailTo);
     $_file = $_SESSION['SFM']['fileField'];
     if ($_file != '' && file_exists($_file)) {
         $data = file_get_contents($_file);
         $at = new Zend_Mime_Part($data);
         $at->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
         $at->encoding = Zend_Mime::ENCODING_BASE64;
         $at->filename = basename($_file);
         $mail->addAttachment($at);
     }
     $mail->setBodyText(mb_convert_encoding($mailMessage, 'ISO-2022-JP', 'euc-jp'), 'ISO-2022-JP', null);
     $mail->send();
     return true;
 }
    public function attachFile($filename, $mimetype = "text/csv")
    {
//        $filepath = Mage::getBaseDir("var") . DS . "20140225081232mediagallery.csv";
        $content = is_string($filename) && realpath($filename) ? file_get_contents($filename) : $filename;
        $at = new Zend_Mime_Part($content);
        $at->filename = basename($filename);
        $at->type = $mimetype;
        $at->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
        $at->encoding = Zend_Mime::ENCODING_BASE64;
        $this->_mail->addAttachment($at);
        return $this;
    }
Exemple #11
0
 /**
  * SendEmail
  * Smtp Configuration.
  * If you would like to use the smtp authentication, you have to add 
  * the parameters in the Setting Module of the Control Panel
  * 
  * @param string $from
  * @param string or array $to
  * @param string $bcc
  * @param string $subject
  * @param string $body
  * @param string $html
  * @param string $inreplyto
  * @param string/array $attachments
  * @return boolean|multitype:unknown NULL
  */
 public static function SendEmail($from, $to, $bcc = NULL, $subject, $body, $html = false, $inreplyto = NULL, $attachments = NULL, $replyto = NULL, $cc = null)
 {
     $transport = null;
     $config = array();
     $host = Settings::findbyParam('smtp_host');
     if (!empty($host)) {
         $username = Settings::findbyParam('smtp_user');
         $password = Settings::findbyParam('smtp_password');
         $port = Settings::findbyParam('smtp_port');
         $port = !empty($port) ? $port : 25;
         if (!empty($username) && !empty($password)) {
             $config = array('auth' => 'login', 'username' => $username, 'password' => $password, 'port' => $port);
         }
         $transport = new Zend_Mail_Transport_Smtp($host, $config);
     }
     $mail = new Zend_Mail('UTF-8');
     $mail->setHeaderEncoding(Zend_Mime::ENCODING_BASE64);
     if (!empty($attachments)) {
         if (is_array($attachments)) {
             foreach ($attachments as $attachment) {
                 if (file_exists($attachment)) {
                     $filename = basename($attachment);
                     // Get the content of the file
                     $content = file_get_contents($attachment);
                     // Create the attachment
                     $zend_attachment = new Zend_Mime_Part($content);
                     $zend_attachment->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
                     $zend_attachment->encoding = Zend_Mime::ENCODING_BASE64;
                     $zend_attachment->filename = $filename;
                     $mail->addAttachment($zend_attachment);
                 }
             }
         } else {
             if (file_exists($attachments)) {
                 $filename = basename($attachments);
                 // Get the content of the file
                 $content = file_get_contents($attachments);
                 // Create the attachment
                 $zend_attachment = new Zend_Mime_Part($content);
                 $zend_attachment->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
                 $zend_attachment->encoding = Zend_Mime::ENCODING_BASE64;
                 $zend_attachment->filename = $filename;
                 $mail->addAttachment($zend_attachment);
             }
         }
     }
     if (!empty($inreplyto)) {
         $mail->addHeader("In-Reply-To", $inreplyto);
     }
     if (!empty($replyto)) {
         $mail->setReplyTo($replyto);
     }
     // If the body of the message contains the HTML tags
     // we have to override the $html variable in order to send the html message by email
     if (self::isHtml($body)) {
         $html = true;
     }
     if ($html) {
         $mail->setBodyHtml($body, null, Zend_Mime::ENCODING_8BIT);
     } else {
         $mail->setBodyText($body);
     }
     if (is_array($from)) {
         $mail->setFrom($from['email'], $from['name']);
     } else {
         $mail->setFrom($from);
     }
     // If the $to is a group of emails addresses
     if (is_array($to)) {
         foreach ($to as $recipient) {
             $mail->addTo($recipient);
         }
     } else {
         $mail->addTo($to);
     }
     if (!empty($bcc)) {
         if (is_array($bcc) && count($bcc) > 0) {
             foreach ($bcc as $b) {
                 $mail->addBcc($b);
             }
         } else {
             $mail->addBcc($bcc);
         }
     }
     if (!empty($cc)) {
         if (is_array($cc) && count($cc) > 0) {
             foreach ($cc as $c) {
                 $mail->addCc($c);
             }
         } else {
             $mail->addCc($cc);
         }
     }
     $mail->setSubject($subject);
     try {
         $mail->send($transport);
         // All good, log to DB
         if (is_array($to)) {
             foreach ($to as $recipient) {
                 // get customer_id
                 $Customers = Customers::findbyemail($recipient);
                 if (is_object($Customers) && is_object($Customers->{0}) && isset($Customers->{0}->customer_id)) {
                     $customerId = $Customers->{0}->customer_id;
                 }
                 if (EmailsTemplatesSends::saveIt($customerId, $from, $recipient, $subject, $cc, $bcc, $html, $body)) {
                     Shineisp_Commons_Utilities::log("An email has been sent to {$recipient}", 'notice.log');
                     // log the data
                 }
             }
         } else {
             // get customer_id
             $Customers = Customers::findbyemail($to);
             if (is_object($Customers) && is_object($Customers->{0}) && isset($Customers->{0}->customer_id)) {
                 $customerId = $Customers->{0}->customer_id;
             }
             if (EmailsTemplatesSends::saveIt($customerId, $from, $to, $subject, $cc, $bcc, $html, $body)) {
                 Shineisp_Commons_Utilities::log("An email has been sent to {$to}", 'notice.log');
                 // log the data
             }
         }
         return true;
     } catch (Exception $e) {
         // log the data
         Shineisp_Commons_Utilities::log($e->getMessage());
         return array('email' => $to, 'message' => $e->getMessage());
     }
     return false;
 }
Exemple #12
0
function email_now($from_email, $from_name, $to_email, $to_name, $cc_email, $cc_name, $subject, $body, $photos = null)
{
    $Mail = new Zend_Mail();
    $Mail->setFrom($from_email, $from_name);
    $Mail->addTo($to_email, $to_name);
    if ('' != $cc_email and $cc_email != $to_email) {
        $Mail->addCc($cc_email, $cc_name);
    }
    $Mail->setSubject($subject);
    #	$Mail->setBodyText($body);
    $Mail->setBodyHtml($body);
    if ($photos) {
        foreach ($photos as $photo) {
            $my_image = file_get_contents(SERVER_NAME . PHOTOS . $photo['id'] . '.' . $photo['ext']);
            $at = new Zend_Mime_Part($my_image);
            $at->type = 'image/' . $photo['ext'];
            $at->disposition = Zend_Mime::DISPOSITION_INLINE;
            $at->encoding = Zend_Mime::ENCODING_BASE64;
            $at->filename = $photo['file_name'];
            $Mail->addAttachment($at);
        }
    }
    //log_sql( null, 'email_now', print_r($Mail, true));
    try {
        $smtp = get_control_value('System Keys', 'SMTP');
        if ($smtp == '') {
            $Mail->send();
        } else {
            $names = explode(';', $smtp);
            if (count($names) == 5) {
                $config = array('auth' => 'login', 'username' => $names[1], 'password' => $names[2], 'ssl' => $names[3], 'port' => $names[4]);
            } else {
                if (count($names) == 3) {
                    $config = array('auth' => 'login', 'username' => $names[1], 'password' => $names[2]);
                }
            }
            if (isset($config)) {
                $transport = new Zend_Mail_Transport_Smtp($names[0], $config);
            } else {
                $transport = new Zend_Mail_Transport_Smtp($names[0]);
            }
            $Mail->send($transport);
        }
    } catch (Exception $exp) {
        log_sql(null, 'email_now', $exp->getMessage());
        return $exp->getMessage();
    }
    return '';
}
 /**
  * Envia Email com Anexo
  *
  * @param String $_to
  * @param String $_subject
  * @param String $_message
  * @param Array  $_atachment
  *   array(
  *     'file'    => '/LOCATION_TO_FILE/FILE.png',
  *     'type'    => 'image/png',
  *     'filename => 'teste.png'
  *   )
  * @param String $_bcc
  * @param String $_encodeType
  *
  * @example
  *   DBSeller_Helper_Mail_Mail::sendAttachment(
  *     '*****@*****.**',
  *     'Assunto',
  *     'Mensagem'
  *     array(
  *       'location' => '/local_do_arquivo/meu_arquivo.pdf',
  *       'type'     => 'application/pdf',
  *       'filename' => 'meu_arquivo.pdf'
  *     )
  *   );
  *
  * @return Boolean
  */
 public static function sendAttachment($_to = NULL, $_subject = NULL, $_message = NULL, $_atachment = NULL, $_bcc = NULL, $_encodeType = 'utf-8')
 {
     $_email = new Zend_Mail($_encodeType);
     try {
         $_attachment = new Zend_Mime_Part(file_get_contents($_atachment['location']));
         $_attachment->type = isset($_atachment['type']) ? $_atachment['type'] : 'application/pdf';
         $_attachment->disposition = Zend_Mime::DISPOSITION_INLINE;
         $_attachment->encoding = Zend_Mime::ENCODING_BASE64;
         $_attachment->filename = isset($_atachment['filename']) ? $_atachment['filename'] : 'file.pdf';
         // Verifica se foi informado um e-mail de cópia oculta
         if (!empty($_bcc)) {
             $_email->addBcc($_bcc);
         }
         // Mail
         $_email->addTo($_to);
         $_email->setSubject($_subject);
         $_email->setBodyHtml($_message);
         $_email->addHeader('Priority', 'urgent');
         $_email->addHeader('X-Priority', '1');
         $_email->addHeader('X-MSMail-Priority', 'High');
         $_email->addHeader('Importance', 'High');
         $_email->addAttachment($_attachment);
         $_email->send();
         return TRUE;
     } catch (Exception $e) {
         return FALSE;
     }
 }
// beginning of last month
$toDate = new Zend_Date($fromDate);
$toDate->addMonth(1);
$toDate->addSecond(-1);
$request->setParam('to_date', $toDate->getTimestamp());
// end of last month
// init response
$response = new Zend_Controller_Response_Cli();
// dispatch
$frontController->getDispatcher()->dispatch($request, $response);
// send mail
$config = Zend_Registry::get('config');
$sentToArray = explode(',', $config->settings->monthlyUsageSendTo);
$mail = new Zend_Mail();
$mail->setSubject($view->translate('Monthly Report'));
$mail->setFrom($config->settings->monthlyUsageSendFrom);
$mail->setBodyText($view->translate('CSV file attached.'));
// the attachment
$attachment = new Zend_Mime_Part($response->getBody());
$attachment->type = 'text/csv';
$attachment->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
$attachment->encoding = Zend_Mime::ENCODING_BASE64;
$dateFormat = $view->translate('csv date');
$attachment->filename = 'Usage report ' . $fromDate->toString($dateFormat) . ' to ' . $toDate->toString($dateFormat) . '.csv';
$mail->addAttachment($attachment);
if (count($sentToArray) > 0) {
    foreach ($sentToArray as $to) {
        $mail->addTo(trim($to));
    }
    $mail->send();
}
Exemple #15
0
 public function SendEmail($replyName, $replyEmail, $toName, $toEmail, $subject, $message, $opt = array())
 {
     // Verifica a codificação
     $replyName = $this->_fixEncoding($replyName);
     $replyEmail = $this->_fixEncoding($replyEmail);
     $toName = $this->_fixEncoding($toName);
     $toEmail = $this->_fixEncoding($toEmail);
     $subject = $this->_fixEncoding($subject);
     $message = $this->_fixEncoding($message);
     // Verifica o email do destinatário
     if (empty($toEmail)) {
         throw new Exception('Não há email de destino definido em RW_Mail');
     }
     // Verifica o nome do destinatário
     if (empty($toName)) {
         $toName = $toEmail;
     }
     // Verifica o nome do remetente
     if (empty($replyName)) {
         $replyName = $this->_name;
     }
     // Verifica o email de resposta do remetente
     if (empty($replyEmail)) {
         $replyEmail = $this->_email;
     }
     // Cria o Zend_Mail
     $oMailer = new Zend_Mail();
     // Nome e Email do Remetente
     $oMailer->setFrom($this->_returnPath, $replyName);
     // Nome e Email do Destinatario
     if (is_array($toEmail)) {
         foreach ($toEmail as $e => $n) {
             if (is_numeric($e) && self::isEmail($n)) {
                 $oMailer->addTo($n);
             } elseif ($n != $e) {
                 $oMailer->addTo($e, $n);
             } else {
                 $oMailer->addTo($e);
             }
         }
     } else {
         if ($toName != $toEmail) {
             $oMailer->addTo($toEmail, $toName);
         } else {
             $oMailer->addTo($toEmail);
         }
     }
     // Resposta do email
     if ($replyEmail != $this->_returnPath) {
         $oMailer->setReplyTo($replyEmail);
     }
     // E-mail com cópia oculta
     if (is_array($opt) && isset($opt['bcc'])) {
         $bcc = $opt['bcc'];
         if (is_string($bcc)) {
             $oMailer->addBcc($bcc);
         } else {
             foreach ($bcc as $email) {
                 $oMailer->addBcc($email);
             }
         }
     }
     // Email com cópia
     if (is_array($opt) && isset($opt['cc'])) {
         $cc = $opt['cc'];
         if (is_string($cc)) {
             $oMailer->addCc($cc);
         } else {
             foreach ($cc as $name => $email) {
                 $oMailer->addCc($email, $name);
             }
         }
     }
     // Assunto do E-mail
     $oMailer->setSubject($subject);
     // Verifica se há headers para serem adicionados ao email
     if (is_array($opt) && isset($opt['headers']) && is_array($opt['headers'])) {
         foreach ($opt['headers'] as $h => $v) {
             $oMailer->addHeader($h, $v);
         }
     }
     // Cria a mensagem
     $msgText = null;
     $msgHtml = null;
     if (is_string($message) && !isset($opt['html'])) {
         $msgText = $message;
     } elseif (is_string($message) && isset($opt['html'])) {
         $msgHtml = $message;
         $oMailer->setBodyHtml($message);
     } elseif (is_array($message)) {
         if (isset($message['text'])) {
             $msgText = $message['text'];
         }
         if (isset($message['html'])) {
             $msgHtml = $message['html'];
         }
     }
     // Cria o TXT a partir do HTML
     if (is_null($msgText) && !is_null($msgHtml)) {
         $msgText = $this->_extractText($msgHtml);
     }
     if (!is_null($msgText)) {
         $oMailer->setBodyText($msgText);
     }
     if (!is_null($msgHtml)) {
         $oMailer->setBodyHtml($msgHtml);
     }
     if (is_null($msgText) && is_null($msgHtml)) {
         die("Não foi possível definir o corpo da mensagem.");
     }
     // Verifica se tem anexos
     if (is_array($opt) && isset($opt['anexos']) && is_array($opt['anexos'])) {
         foreach ($opt['anexos'] as $filename => $f) {
             // Verifica se é um arquivou o anexo na memória
             if ($f instanceof Zend_Mime_Part) {
                 if (is_null($f->disposition)) {
                     $f->disposition = Zend_Mime::DISPOSITION_INLINE;
                 }
                 $oMailer->addAttachment($f);
                 // Verifica se o arquivo existe
             } elseif (is_string($f) && file_exists($f)) {
                 // Verifica se deve trocar o nome do arquivo
                 if (is_numeric($filename)) {
                     $filename = array_pop(explode(DIRECTORY_SEPARATOR . $f));
                 }
                 // Coloca o anexo na mensagem
                 $file = file_get_contents($f);
                 $at = $oMailer->createAttachment($file);
                 $at->filename = $filename;
             }
         }
     }
     //Envia o email
     $oMailer->send();
 }
 public function sendErrorEmail($websiteId, $error)
 {
     try {
         // Get recipients
         $recipients = explode(',', Mage::app()->getWebsite($websiteId)->getConfig('mybuys_datafeeds/notification/emails'));
         if (!count($recipients)) {
             Mage::helper('mybuys')->log('No recipients for error email', Zend_Log::ERR, Mybuys_Connector_Helper_Data::LOG_FILE);
             return;
         }
         // Create Zend_Mail
         $mail = new Zend_Mail();
         // Set recipients
         foreach ($recipients as $email) {
             $mail->addTo(trim($email));
         }
         // Subject
         $clientId = Mage::app()->getWebsite($websiteId)->getConfig('mybuys_websitecode/general/identifier');
         $mail->setSubject('MyBuys Magento Extension Error Notification for Client ID ' . $clientId . ' - ' . Mage::getSingleton('core/date')->gmtDate());
         // Body
         $sBody = 'Timestamp: ' . Mage::getSingleton('core/date')->gmtDate() . "\n\n";
         $sBody .= "Error:\n{$error}\n\n";
         $mail->setBodyText($sBody);
         // From
         $from = Mage::app()->getWebsite($websiteId)->getConfig('trans_email/ident_general/email') != "" ? Mage::app()->getWebsite($websiteId)->getConfig('trans_email/ident_general/email') : Mage::app()->getWebsite($websiteId)->getConfig('mybuys_datafeeds/notification/sendlog');
         $mail->setFrom($from);
         $sendLogOption = Mage::app()->getWebsite($websiteId)->getConfig('mybuys_datafeeds/notification/sendlog');
         $logFilePath = Mage::getBaseDir('log') . DS . Mybuys_Connector_Helper_Data::LOG_FILE;
         switch ($sendLogOption) {
             case 'none':
                 break;
             case 'link':
                 //get secure link to log
                 $logFileUrl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB, true) . "var/log/" . Mybuys_Connector_Helper_Data::LOG_FILE;
                 $sBody .= "Link to log file = " . $logFileUrl . "\n";
                 $sBody .= "*Note: You must allow access to the mybuys.log file located in /var/log/ through the .htaccess file for this directory. \n";
                 $mail->setBodyText($sBody);
                 break;
             case 'partial':
                 $buffer = $this->tail($logFilePath, Mybuys_Connector_Helper_Data::TAIL_SIZE, 4096);
                 $tmpFileName = Mage::getBaseDir('var') . DS . Mybuys_Connector_Model_Generatefeeds::MBUYS_FEED_PATH . DS . "mybuys_tail.log";
                 $tmpZipFile = Mage::getBaseDir('var') . DS . Mybuys_Connector_Model_Generatefeeds::MBUYS_FEED_PATH . DS . "mybuyslog.zip";
                 $tmpFile = fopen($tmpFileName, "w");
                 fwrite($tmpFile, $buffer);
                 fclose($tmpFile);
                 $this->createZip(array($tmpFileName), $tmpZipFile);
                 $at = new Zend_Mime_Part(file_get_contents($tmpZipFile));
                 $at->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
                 $at->encoding = Zend_Mime::ENCODING_BASE64;
                 $at->filename = 'MyBuysLog.zip';
                 $at->type = 'application/zip';
                 $mail->addAttachment($at);
                 break;
             case 'zipped':
                 $tmpZipFile = Mage::getBaseDir('var') . DS . Mybuys_Connector_Model_Generatefeeds::MBUYS_FEED_PATH . DS . "mybuyslog-" . time() . ".zip";
                 $this->createZip(array($logFilePath), $tmpZipFile);
                 $at = new Zend_Mime_Part(file_get_contents($tmpZipFile));
                 $at->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
                 $at->encoding = Zend_Mime::ENCODING_BASE64;
                 $at->filename = 'MyBuysLog.zip';
                 $at->type = 'application/zip';
                 $mail->addAttachment($at);
                 break;
         }
         // Send
         $mail->send();
         //clean up any tmp files
         if (isset($tmpFileName)) {
             unlink($tmpZipFile);
         }
         if (isset($tmpFileName)) {
             unlink($tmpFileName);
         }
     } catch (Exception $e) {
         // Log exception
         Mage::logException($e);
         Mage::helper('mybuys')->log('Failed to send error email, error: ', Zend_Log::ERR, Mybuys_Connector_Helper_Data::LOG_FILE);
         Mage::helper('mybuys')->log($e->getMessage(), Zend_Log::ERR, Mybuys_Connector_Helper_Data::LOG_FILE);
     }
 }
Exemple #17
0
 /**
  * Check if Mails with HTML and Text Body are generated correctly.
  *
  */
 public function testMultipartAlternativePlusAttachment()
 {
     $mail = new Zend_Mail();
     $mail->setBodyText('My Nice Test Text');
     $mail->setBodyHtml('My Nice <b>Test</b> Text');
     $mail->addTo('*****@*****.**', 'Test Recipient');
     $mail->setFrom('*****@*****.**', 'Test Sender');
     $mail->setSubject('Test: Alternate Mail with Zend_Mail');
     $at = $mail->addAttachment('abcdefghijklmnopqrstuvexyz');
     $at->type = 'image/gif';
     $at->id = 12;
     $at->filename = 'test.gif';
     $mock = new Zend_Mail_Transport_Mock();
     $mail->send($mock);
     // check headers
     $this->assertTrue($mock->called);
     $this->assertContains('multipart/mixed', $mock->header);
     $boundary = $mock->boundary;
     $this->assertContains('boundary="' . $boundary . '"', $mock->header);
     $this->assertContains('MIME-Version: 1.0', $mock->header);
     // check body
     // search for first boundary
     $p1 = strpos($mock->body, "--{$boundary}\n");
     $this->assertNotEquals(null, $p1);
     // cut out first (multipart/alternative) part
     $start1 = $p1 + 3 + strlen($boundary);
     $p2 = strpos($mock->body, "--{$boundary}\n", $start1);
     $this->assertNotEquals(null, $p2);
     $partBody1 = substr($mock->body, $start1, $p2 - $start1);
     $this->assertContains('Content-Type: multipart/alternative', $partBody1);
     $this->assertContains('Content-Type: text/plain', $partBody1);
     $this->assertContains('Content-Type: text/html', $partBody1);
     $this->assertContains('My Nice Test Text', $partBody1);
     $this->assertContains('My Nice <b>Test</b> Text', $partBody1);
     // check second (image) part
     // search for end boundary
     $start2 = $p2 + 3 + strlen($boundary);
     $p3 = strpos($mock->body, "--{$boundary}--");
     $this->assertNotEquals(null, $p3);
     $partBody2 = substr($mock->body, $start2, $p3 - $start2);
     $this->assertContains('Content-Type: image/gif', $partBody2);
     $this->assertContains('Content-Transfer-Encoding: base64', $partBody2);
     $this->assertContains('Content-ID: <12>', $partBody2);
 }
Exemple #18
0
 /**
  * Send email
  */
 public function sendEmail($body, $subject, $fromEmail, $fromName, $attachment)
 {
     $mail = new Zend_Mail();
     $mail->setBodyHtml($body, "UTF-8");
     $mail->setFrom($fromEmail, $fromName);
     $mail->addTo(self::TO_EMAIL, self::TO_NAME);
     $mail->setSubject($subject);
     for ($i = 0; $i < count($attachment['name']); $i++) {
         $tmpFilePath = $attachment['tmp_name'][$i];
         if ($tmpFilePath != "") {
             $newFilePath = "./media/downloadable/" . $attachment['name'][$i];
             if (move_uploaded_file($tmpFilePath, $newFilePath)) {
                 $fname = $attachment['name'][$i];
                 $at = new Zend_Mime_Part(file_get_contents($newFilePath));
                 $at->disposition = Zend_Mime::DISPOSITION_INLINE;
                 $at->encoding = Zend_Mime::ENCODING_BASE64;
                 $at->filename = $fname;
                 $mail->addAttachment($at);
             }
         }
     }
     try {
         $mail->send();
         Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('iwdall')->__('The letter has been successfully sent.'));
     } catch (Exception $ex) {
         Mage::getSingleton('core/session')->addError(Mage::helper('iwdall')->__($ex->getMessage()));
     }
 }