/** * Send a message via MailGun * * @param MessageInterface $message * @return string newly created message identifier (Message-Id) on success * @throws Exception\RuntimeException */ public function send(MessageInterface $message) { $client = $this->getHttpClient(); $data = $this->messageToPost($message); $uri = sprintf($this->getOptions()->getBaseUri(), $this->getOptions()->getDomain()); if (!empty($data['message'])) { $client->setFileUpload('message.mime', 'message', $data['message'], 'message/rfc2822'); unset($data['message']); $uri .= '.mime'; } $client->setMethod('POST'); $client->setUri($uri); $client->setParameterPost($data); foreach ($message->getAttachments() as $attachment) { $client->setFileUpload($attachment['name'], 'attachment', StreamUtils::file_get_contents($attachment['tmp_name']), $attachment['type']); } $response = $client->send(); $result = $response->getBody(); if ($response->getHeaders()->get('Content-Type')->getFieldValue() == 'application/json') { $result = Json::decode($result, Json::TYPE_ARRAY); } if (!$response->isSuccess()) { $errorstr = $response->getReasonPhrase(); if (is_array($result) && !empty($result['message'])) { $errorstr = $result['message']; } throw new Exception\RuntimeException('Unable to send mail: ' . $errorstr); } if (!is_array($result) || empty($result['id'])) { throw new Exception\RuntimeException('Unexpected response from API'); } return $result['id']; }
/** * {@inheritdoc} */ public function setAttachments($attachments) { $this->attachments = array(); if (is_array($attachments)) { return parent::setAttachments($attachments); } foreach (Json::decode($attachments, Json::TYPE_ARRAY) as $attachment) { $tmp = tempnam(sys_get_temp_dir(), 'attach_'); $url = str_replace('://', '://api:' . $this->apikey . '@', $attachment['url']); $error = UPLOAD_ERR_NO_FILE; if (file_put_contents($tmp, StreamUtils::file_get_contents($url))) { $error = UPLOAD_ERR_OK; } $this->attachments[] = array('tmp_name' => $tmp, 'name' => $attachment['name'], 'size' => $attachment['size'], 'type' => $attachment['content-type'], 'error' => $error); } return $this; }