示例#1
0
 public function send(MessageInterface $message)
 {
     if (count($message->getToList()) === 0) {
         // TODO FIXED EXCEPTION
         throw new \Exception();
     }
     foreach ($message->getToList() as $email) {
         if (!$this->validateEmail($email)) {
             // TODO FIXED EXCEPTION
             throw new \Exception();
         }
     }
     $sendgrid = new \SendGrid(env("SENDGRID_USERNAME"), env("SENDGRID_PASSWORD"));
     $email = new \SendGrid\Email();
     $email->addTo($message->getToList())->setFrom($message->getFrom())->setSubject($message->getSubject())->setText($message->getTextBody())->setHtml($message->getHtmlBody());
     if (is_array($message->getBccList())) {
         $email->addBcc($message->getBccList());
     }
     $email->setAttachments($message->getAttachments());
     try {
         $sendgrid->send($email);
     } catch (\Exception $e) {
         throw $e;
     }
 }
示例#2
0
 public function send(array $options)
 {
     $connection = $this->getConnection();
     $email = new \SendGrid\Email();
     $options = array_replace_recursive($this->defaults, $options);
     foreach ((array) $options['to'] as $to) {
         $email->addTo($to);
     }
     foreach ((array) $options['cc'] as $cc) {
         $email->addCc($cc);
     }
     foreach ((array) $options['bcc'] as $bcc) {
         $email->addBcc($bcc);
     }
     $email->setSubject($options['subject']);
     $email->setFrom($this->getFrom($options));
     if (!empty($options['category'])) {
         $email->setCategory($options['category']);
     }
     if (!empty($options['categories'])) {
         $email->setCategories($options['categories']);
     }
     if (!empty($options['text'])) {
         $email->setText($options['text']);
     }
     if (!empty($options['html'])) {
         $email->setHtml($options['html']);
     } elseif (!empty($options['layout']) && !empty($options['data'])) {
         $path = $this->_app->basePath . '/mail/sendgrid/' . $options['layout'] . '.html';
         if (!file_exists($path)) {
             $message = 'Layout "' . $options['layout'] . '" cannot be found in "/mail/sendgrid/".';
             if ($this->_version == 2) {
                 throw new \yii\web\NotFoundHttpException($message);
             } else {
                 throw new \CHttpException(404, $message);
             }
         }
         $params = array('subject' => $options['subject']);
         foreach ($options['data'] as $key => $value) {
             $params['{{' . $key . '}}'] = $value;
         }
         $html = file_get_contents($path);
         $html = strtr($html, $params);
         $email->setHtml($html);
     }
     return $response = $connection->send($email);
 }
 private function processEmailHeaders($headers, SendGrid\Email $email)
 {
     if ($headers && is_array($headers)) {
         if (isset($headers[self::Header_CC])) {
             foreach (explode(',', $headers[self::Header_CC]) as $cc) {
                 $email->addCc(trim($cc));
             }
         }
         if (isset($headers[self::Header_BCC])) {
             foreach (explode(',', $headers[self::Header_BCC]) as $bcc) {
                 $email->addBcc(trim($bcc));
             }
         }
         if (isset($headers[self::Header_ReplyTo])) {
             $email->setReplyTo($headers[self::Header_ReplyTo]);
         }
     }
     return $email;
 }
示例#4
0
 public function testToWebFormatWithSmtpapiToAndBcc()
 {
     $email = new \SendGrid\Email();
     $email->addSmtpapiTo('*****@*****.**');
     $email->addBcc('*****@*****.**');
     $json = $email->toWebFormat();
     $this->assertEquals($json['bcc'], ['*****@*****.**']);
     $this->assertEquals($json['x-smtpapi'], '{"to":["*****@*****.**"]}');
 }
 public function testToWebFormatWithToAndBcc()
 {
     $email = new SendGrid\Email();
     $email->addTo('*****@*****.**');
     $email->addBcc('*****@*****.**');
     $json = $email->toWebFormat();
     $this->assertEquals($json['to'], array('*****@*****.**'));
     $this->assertEquals($json['bcc'], array('*****@*****.**'));
     $this->assertEquals($json["x-smtpapi"], '{}');
 }
 /**
  * Send email.
  */
 public function sendEmail()
 {
     $emailMessage = $this->emailMessage;
     if ($this->emailAccount == null) {
         $apiUser = Yii::app()->sendGridEmailHelper->apiUsername;
         $apiPassword = Yii::app()->sendGridEmailHelper->apiPassword;
     } else {
         $apiUser = $this->emailAccount->apiUsername;
         $apiPassword = ZurmoPasswordSecurityUtil::decrypt($this->emailAccount->apiPassword);
     }
     $itemData = EmailMessageUtil::getCampaignOrAutoresponderDataByEmailMessage($this->emailMessage);
     $sendgrid = new SendGrid($apiUser, $apiPassword, array("turn_off_ssl_verification" => true));
     $email = new SendGrid\Email();
     $email->setFrom($this->fromUserEmailData['address'])->setFromName($this->fromUserEmailData['name'])->setSubject($emailMessage->subject)->setText($emailMessage->content->textContent)->setHtml($emailMessage->content->htmlContent)->addUniqueArg("zurmoToken", md5(ZURMO_TOKEN))->addHeader('X-Sent-Using', 'SendGrid-API')->addHeader('X-Transport', 'web');
     //Check if campaign and if yes, associate to email.
     if ($itemData != null) {
         list($itemId, $itemClass, $personId) = $itemData;
         $email->addUniqueArg("itemId", $itemId);
         $email->addUniqueArg("itemClass", $itemClass);
         $email->addUniqueArg("personId", $personId);
     }
     foreach ($this->toAddresses as $emailAddress => $name) {
         $email->addTo($emailAddress, $name);
     }
     foreach ($this->ccAddresses as $emailAddress => $name) {
         $email->addCc($emailAddress);
     }
     foreach ($this->bccAddresses as $emailAddress => $name) {
         $email->addBcc($emailAddress);
     }
     //Attachments
     $attachmentsData = array();
     $tempAttachmentPath = Yii::app()->getRuntimePath() . DIRECTORY_SEPARATOR . 'emailAttachments';
     if (!file_exists($tempAttachmentPath)) {
         mkdir($tempAttachmentPath);
     }
     if (!empty($emailMessage->files)) {
         foreach ($emailMessage->files as $file) {
             $fileName = tempnam($tempAttachmentPath, 'zurmo_');
             $fp = fopen($fileName, 'wb');
             fwrite($fp, $file->fileContent->content);
             fclose($fp);
             $email->addAttachment($fileName, $file->name);
             $attachmentsData[] = $fileName;
         }
     }
     $emailMessage->sendAttempts = $emailMessage->sendAttempts + 1;
     $response = $sendgrid->send($email);
     if ($response->message == 'success') {
         //Here we need to check if
         $emailMessage->error = null;
         $emailMessage->folder = EmailFolder::getByBoxAndType($emailMessage->folder->emailBox, EmailFolder::TYPE_SENT);
         $emailMessage->sentDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time());
     } elseif ($response->message == 'error') {
         $content = Zurmo::t('EmailMessagesModule', 'Response from Server') . "\n";
         foreach ($response->errors as $error) {
             $content .= $error;
         }
         $emailMessageSendError = new EmailMessageSendError();
         $data = array();
         $data['message'] = $content;
         $emailMessageSendError->serializedData = serialize($data);
         $emailMessage->folder = EmailFolder::getByBoxAndType($emailMessage->folder->emailBox, EmailFolder::TYPE_OUTBOX_ERROR);
         $emailMessage->error = $emailMessageSendError;
     }
     if (count($attachmentsData) > 0) {
         foreach ($attachmentsData as $path) {
             unlink($path);
         }
     }
     $saved = $emailMessage->save(false);
     if (!$saved) {
         throw new FailedToSaveModelException();
     }
 }
 /**
  * @param SendGrid\Email $email
  * @param Swift_Mime_Message $message
  */
 protected function setBcc($email, Swift_Mime_Message $message)
 {
     if ($bcc = $message->getBcc()) {
         foreach ($bcc as $bcc_email => $bcc_name) {
             $email->addBcc($bcc_email, $bcc_name);
         }
     }
 }
示例#8
0
 public function send()
 {
     //ARCHIVE THIS EMAIL
     if ($this->archive) {
         $rand = substr(md5(rand(0, 100) . date("dmyHis")), -10);
         //Set url in HTML body
         $this->HTMLBody = str_replace("[[ARCHIVE]]", LINK_BASE . "archive/" . $rand . ".html", $this->HTMLBody);
     }
     //Remove all variables ([[var]]) in template, if necessairy
     while (($startpos = strpos($this->HTMLBody, "[[")) !== false) {
         $endpos = strpos(substr($this->HTMLBody, $startpos), "]]") + $startpos;
         $temp = substr($this->HTMLBody, 0, $startpos) . substr($this->HTMLBody, $endpos + 2);
         $this->HTMLBody = $temp;
     }
     //Create the archived document
     if ($this->archive) {
         $doc = new Document("archive/", $rand . '.html');
         if (STAGE == "test") {
             $string = "From: " . $this->from['name'] . ' (' . $this->from['email'] . ')<br/>To: ' . print_r($this->recipients, true) . "<br/>Subject: " . $this->subject . '<br/>';
         } else {
             $string = "";
         }
         $string .= $this->HTMLBody;
         $doc->write($string);
     }
     $email = new SendGrid\Email();
     $email->setFrom($this->from["email"])->setFromName($this->from["name"])->setSubject($this->subject)->setText($this->plainBody)->setHTML($this->HTMLBody)->setHeaders($this->headers);
     //Add recipients
     foreach ($this->recipients as $recipient) {
         switch ($recipient["type"]) {
             case "to":
             default:
                 $email->addTo($recipient['email'], $recipient["name"]);
                 break;
             case "cc":
                 $email->addCc($recipient['email'], $recipient["name"]);
                 break;
             case "bcc":
                 $email->addBcc($recipient['email'], $recipient["name"]);
                 break;
         }
     }
     switch (STAGE) {
         case 'deploy':
         case 'test':
             $result = [];
             try {
                 $result = $this->sendgrid->send($email);
             } catch (\SendGrid\Exception $e) {
                 foreach ($e->getErrors() as $er) {
                     trigger_error("A mail error occured: " . $e->getCode() . " - " . $er, E_USER_ERROR);
                 }
             }
             $sent = array();
             $rejected = array();
             if ($result->code == 200) {
                 array_push($sent, true);
             } else {
                 array_push($rejected, $result->body->message);
             }
             return array("sent" => $sent, "rejected" => $rejected);
             break;
         case 'dev':
         default:
             //Display email in browser, don't send
             print_r($email);
             break;
     }
 }
 /**
  * Repair data for send message
  *
  * @param array $args
  *
  * @return array
  */
 function generate_postdata($args = array())
 {
     $emailData = new SendGrid\Email();
     $is_force = aem_get_option('aem_force_header', FALSE);
     $header = $this->process_header($args['headers']);
     /**
      * generate postFile
      */
     $emailData->setSubject($args['subject']);
     $emailData->setText($args['subject']);
     //From email
     if (!$is_force && isset($header['from_name'])) {
         $from_email = $header['from_email'];
     } else {
         $from_email = AEM_Option()->get_from_email();
     }
     $from_email = apply_filters('wp_mail_from', $from_email);
     $emailData->setFrom($from_email);
     //From name
     if (!$is_force && isset($header['from_name'])) {
         $from_name = $header['from_name'];
     } else {
         $from_name = AEM_Option()->get_from_name();
     }
     $from_name = apply_filters('wp_mail_from_name', $from_name);
     $emailData->setFromName($from_name);
     //to
     if (!is_array($args['to'])) {
         $args['to'] = explode(',', $args['to']);
     }
     foreach ((array) $args['to'] as $recipient) {
         try {
             // Break $recipient into name and address parts if in the format "Foo <*****@*****.**>"
             $recipient_name = '';
             if (preg_match('/(.*)<(.+)>/', $recipient, $matches)) {
                 if (count($matches) == 3) {
                     $recipient_name = $matches[1];
                     $recipient = $matches[2];
                 }
             }
             $emailData->addTo($recipient, $recipient_name);
         } catch (phpmailerException $e) {
             continue;
         }
     }
     //cc
     if (!empty($header['cc'])) {
         //header cc not empty
         if (empty($args['cc'])) {
             //arg cc empty, override agr cc
             $args['cc'] = $header['cc'];
         } else {
             //arg cc not empty
             if (!is_array($args['cc'])) {
                 $args['cc'] = explode(',', $args['cc']);
             }
             //merge them
             $args['cc'] = array_merge($header['cc']);
         }
     }
     if (!empty($args['cc'])) {
         foreach ((array) $args['cc'] as $recipient) {
             try {
                 // Break $recipient into name and address parts if in the format "Foo <*****@*****.**>"
                 $recipient_name = '';
                 if (preg_match('/(.*)<(.+)>/', $recipient, $matches)) {
                     if (count($matches) == 3) {
                         $recipient_name = $matches[1];
                         $recipient = $matches[2];
                     }
                 }
                 $emailData->addCc($recipient);
             } catch (phpmailerException $e) {
                 continue;
             }
         }
     }
     //bcc
     if (!empty($header['bcc'])) {
         //header bcc not empty
         if (empty($args['bcc'])) {
             //arg bcc empty, override agr cc
             $args['bcc'] = $header['bcc'];
         } else {
             //arg bcc not empty
             if (!is_array($args['bcc'])) {
                 $args['bcc'] = explode(',', $args['bcc']);
             }
             //merge them
             $args['bcc'] = array_merge($header['bcc']);
         }
     }
     if (!empty($args['bcc'])) {
         foreach ((array) $args['bcc'] as $recipient) {
             try {
                 // Break $recipient into name and address parts if in the format "Foo <*****@*****.**>"
                 $recipient_name = '';
                 if (preg_match('/(.*)<(.+)>/', $recipient, $matches)) {
                     if (count($matches) == 3) {
                         $recipient_name = $matches[1];
                         $recipient = $matches[2];
                     }
                 }
                 $emailData->addBcc($recipient);
             } catch (Exception $e) {
                 continue;
             }
         }
     }
     if (!isset($header['content_type'])) {
         $content_type = 'text/plain';
     } else {
         $content_type = $header['content_type'];
     }
     $content_type = apply_filters('wp_mail_content_type', $content_type);
     if ($content_type == "text/html") {
         $emailData->setHtml($args['message']);
     }
     //custom header
     if (isset($args['headers']) && is_array($args['headers'])) {
         //extract header line
         $header_arr = explode("\r\n", $args['headers']);
         foreach ($header_arr as $header) {
             //extract header key:value
             $tmp = explode(':', $header);
             if (count($tmp) > 1) {
                 if ($tmp[1] != NULL) {
                     if (strtolower($tmp[0]) == 'from') {
                         if (aem_get_option('aem_force_header')) {
                             continue;
                         }
                     }
                     $emailData->addHeader($tmp[0], $tmp[1]);
                 }
             }
         }
     }
     //$args['attachments'] = array ( plugin_dir_path( AEM_PLUGIN_FILE )."/inc/ae/assets/img/slider.png" );
     if (!empty($args['attachments'])) {
         $emailData->setAttachments($args['attachments']);
     }
     $postData = apply_filters("aem_postdata", $emailData);
     return $postData;
 }