protected function _swiftMail($to, $from, $subject, $message, $attachments = [], $html = true) { $mailer = $this->__getSwiftMailer($from); if (is_array($to) && isset($to['email'])) { if (isset($to['name'])) { $to = [$to['email'] => $to['name']]; } else { $to = $to['email']; } } $mail = new \Swift_Message(); $mail->setSubject($subject)->setFrom($from['email'], $from['name'])->setTo($to); if (isset($from['reply-to'])) { if (is_array($from['reply-to']) && isset($from['email'])) { $mail->setReplyTo($from['reply-to']['email'], $from['reply-to']['name']); } else { $mail->setReplyTo($from['reply-to']); } } $mail->setBody($message, $html ? 'text/html' : 'text/plain'); foreach ($attachments as $attachment) { $mail->attach(\Swift_Attachment::fromPath($attachment)); } return $mailer->send($mail); }
public function __construct() { parent::__construct(); $this->prependSiteTitle(lang('Recover log in')); if ($this->isPostBack()) { $this->post->email->addValidation(new ValidateInputNotNullOrEmpty()); if (!$this->hasErrors()) { $user = ModelUser::getByUsername($this->input('email')); if (!$user->hasRow()) { $this->setMessage('No user found', 'warning'); response()->refresh(); } if (!$this->hasErrors()) { $reset = new UserReset($user->id); $reset->save(); // TODO: Move this shit to seperate html template $text = "Dear customer!\n\nYou are receiving this mail, because you (or someone else) has requested a password reset for your user on NinjaImg.com.\n\nTo continue with the password reset, please click the link below to confirm the reset:\n\n" . sprintf('https://%s/reset/%s', $_SERVER['HTTP_HOST'], $reset->key) . "\n\nIf you have any questions, feel free to contact us any time.\n\nKind regards,\nThe NinjaImg Team"; $transport = \Swift_SendmailTransport::newInstance(env('MAIL_TRANSPORT') . ' -bs'); $swift = \Swift_Mailer::newInstance($transport); $message = new \Swift_Message(lang('Confirm password reset on NinjaImg')); $message->setFrom(env('MAIL_FROM')); $message->setSender(env('MAIL_FROM')); $message->setReplyTo(env('MAIL_FROM')); $message->setBody($text, 'text/plain'); $message->setTo($user->username); $swift->send($message); $this->setMessage('A password reset link has been sent to your e-mail', 'success'); // Send mail to user confirming reset... // Maybe show message with text that are active even when session disappear response()->refresh(); } } } }
/** * Creates a swift message from a ParsedMessage, handles defaults * * @param ParsedMessage $parsedMessage * * @return \Swift_Message */ protected function transformMessage(ParsedMessage $parsedMessage) { $message = new \Swift_Message(); if ($from = $parsedMessage->getFrom()) { $message->setFrom($from); } // handle to with defaults if ($to = $parsedMessage->getTo()) { $message->setTo($to); } // handle cc with defaults if ($cc = $parsedMessage->getCc()) { $message->setCc($cc); } // handle bcc with defaults if ($bcc = $parsedMessage->getBcc()) { $message->setBcc($bcc); } // handle reply to with defaults if ($replyTo = $parsedMessage->getReplyTo()) { $message->setReplyTo($replyTo); } // handle subject with default if ($subject = $parsedMessage->getSubject()) { $message->setSubject($subject); } // handle body, no default values here $message->setBody($parsedMessage->getMessageText()); if ($parsedMessage->getMessageHtml()) { $message->addPart($parsedMessage->getMessageHtml(), 'text/html'); } return $message; }
/** * @inheritDoc */ public static function fromWrappedMessage(MailWrappedMessage $wrappedMessage = null, $transport = null) { if (!$wrappedMessage instanceof MailWrappedMessage) { throw new MailWrapperSetupException('Not MailWrappedMessage'); } $message = new \Swift_Message(); foreach ($wrappedMessage->getToRecipients() as $address) { $message->addTo($address); } foreach ($wrappedMessage->getCcRecipients() as $address) { $message->addCc($address); } foreach ($wrappedMessage->getBccRecipients() as $address) { $message->addBcc($address); } $message->setReplyTo($wrappedMessage->getReplyTo()); $message->setFrom($wrappedMessage->getFrom()); $message->setSubject($wrappedMessage->getSubject()); if ($wrappedMessage->getContentText()) { $message->setBody($wrappedMessage->getContentText()); } if ($wrappedMessage->getContentHtml()) { $message->setBody($wrappedMessage->getContentHtml(), 'text/html'); } return $message; }
protected function _mapToSwift(SendGrid\Email $mail) { $message = new \Swift_Message($mail->getSubject()); /* * Since we're sending transactional email, we want the message to go to one person at a time, rather * than a bulk send on one message. In order to do this, we'll have to send the list of recipients through the headers * but Swift still requires a 'to' address. So we'll falsify it with the from address, as it will be * ignored anyway. */ $message->setTo($mail->to); $message->setFrom($mail->getFrom(true)); $message->setCc($mail->getCcs()); $message->setBcc($mail->getBccs()); if ($mail->getHtml()) { $message->setBody($mail->getHtml(), 'text/html'); if ($mail->getText()) { $message->addPart($mail->getText(), 'text/plain'); } } else { $message->setBody($mail->getText(), 'text/plain'); } if ($replyto = $mail->getReplyTo()) { $message->setReplyTo($replyto); } $attachments = $mail->getAttachments(); //add any attachments that were added if ($attachments) { foreach ($attachments as $attachment) { $message->attach(\Swift_Attachment::fromPath($attachment['file'])); } } $message_headers = $message->getHeaders(); $message_headers->addTextHeader("x-smtpapi", $mail->smtpapi->jsonString()); return $message; }
public function __construct($key) { parent::__construct(); $newPassword = uniqid(); $reset = \Pecee\Model\User\UserReset::confirm($key, $newPassword); if ($reset) { $user = ModelUser::getById($reset); if ($user->hasRow()) { // Send mail with new password // TODO: Move this shit to separate html template $user->setEmailConfirmed(true); $user->update(); $text = "Dear customer!\n\nWe've reset your password - you can login with your e-mail and the new password provided below:\nNew password: "******"\n\nIf you have any questions, feel free to contact us any time.\n\nKind regards,\nThe NinjaImg Team"; $transport = \Swift_SendmailTransport::newInstance(env('MAIL_TRANSPORT') . ' -bs'); $swift = \Swift_Mailer::newInstance($transport); $message = new \Swift_Message(lang('New password for NinjaImg')); $message->setFrom(env('MAIL_FROM')); $message->setSender(env('MAIL_FROM')); $message->setReplyTo(env('MAIL_FROM')); $message->setBody($text, 'text/plain'); $message->setTo($user->username); $swift->send($message); $this->setMessage('A new password has been sent to your e-mail.', 'success'); redirect(url('user.login')); } redirect(url('home')); } }
/** * {@inheritdoc} */ public function send($from, $to, $subject, $body, $replyTo = null, $attachments = []) { $message = new \Swift_Message($subject, $body); // set from and to $message->setFrom($from); $message->setTo($to); // set attachments if (count($attachments) > 0) { foreach ($attachments as $file) { if ($file instanceof \SplFileInfo) { $path = $file->getPathName(); $name = $file->getFileName(); // if uploadedfile get original name if ($file instanceof UploadedFile) { $name = $file->getClientOriginalName(); } $message->attach(\Swift_Attachment::fromPath($path)->setFilename($name)); } } } // set replyTo if ($replyTo != null) { $message->setReplyTo($replyTo); } return $this->mailer->send($message); }
protected function _mapToSwift(Mail $mail) { $message = new \Swift_Message($mail->getSubject()); /* * Since we're sending transactional email, we want the message to go to one person at a time, rather * than a bulk send on one message. In order to do this, we'll have to send the list of recipients through the headers * but Swift still requires a 'to' address. So we'll falsify it with the from address, as it will be * ignored anyway. */ $message->setTo($mail->getFrom()); $message->setFrom($mail->getFrom(true)); $message->setCc($mail->getCcs()); $message->setBcc($mail->getBccs()); if ($mail->getHtml()) { $message->setBody($mail->getHtml(), 'text/html'); if ($mail->getText()) { $message->addPart($mail->getText(), 'text/plain'); } } else { $message->setBody($mail->getText(), 'text/plain'); } if ($replyto = $mail->getReplyTo()) { $message->setReplyTo($replyto); } // determine whether or not we can use SMTP recipients (non header based) if ($mail->useHeaders()) { //send header based email $message->setTo($mail->getFrom()); //here we'll add the recipients list to the headers $headers = $mail->getHeaders(); $headers['to'] = $mail->getTos(); $mail->setHeaders($headers); } else { $recipients = array(); foreach ($mail->getTos() as $recipient) { if (preg_match("/(.*)<(.*)>/", $recipient, $results)) { $recipients[trim($results[2])] = trim($results[1]); } else { $recipients[] = $recipient; } } $message->setTo($recipients); } $attachments = $mail->getAttachments(); //add any attachments that were added if ($attachments) { foreach ($attachments as $attachment) { $message->attach(\Swift_Attachment::fromPath($attachment['file'])); } } //add all the headers $headers = $message->getHeaders(); $headers->addTextHeader('X-SMTPAPI', $mail->getHeadersJson()); return $message; }
function sendMail($mail, $subject, $text) { $transport = \Swift_SendmailTransport::newInstance(env('MAIL_TRANSPORT') . ' -bs'); $swift = \Swift_Mailer::newInstance($transport); $message = new \Swift_Message($subject); $message->setFrom(env('MAIL_FROM')); $message->setSender(env('MAIL_FROM')); $message->setReplyTo(env('MAIL_FROM')); $message->setBody($text, 'text/plain'); $message->addTo($mail); $swift->send($message); }
/** * send * * @return void */ public function send() { try { $this->message = Swift_Message::newInstance()->setSubject($this->template->getSubject())->setCharset("utf-8"); switch ($this->type) { case self::TYPE_PLAIN: $this->message->setBody($this->template->getPlain(), 'text/plain'); break; case self::TYPE_HTML: $html_body = $this->template->getHtml(); if ($this->hasEmbedImage()) { $html_body = $this->embedImages($html_body); } $this->message->setBody($html_body, 'text/html'); break; case self::TYPE_BOTH: default: $html_body = $this->template->getHtml(); if ($this->hasEmbedImage()) { $html_body = $this->embedImages($html_body); } $this->message->setBody($html_body, 'text/html'); $this->message->addPart($this->template->getPlain(), 'text/plain'); break; } if ($this->getAttribute('reply')) { $this->message->setReplyTo($this->getAttribute('reply')); } $this->message->setFrom($this->getAttribute('from'))->setTo($this->getAttribute('to')); $this->getMailer()->send($this->message); } catch (Exception $exception) { if ($this->getTransport() && $this->getTransport()->isStarted()) { $this->disconnect(); } throw $exception; } }
/** * Send mail. * * @param array $from From address array('*****@*****.**' => 'John Doe'). * @param array $to To address '*****@*****.**' or array('*****@*****.**' => 'A name'). * @param string $subject Subject. * @param string $body Content body. * @param array $contentType Content type for body, default 'text/plain'. * @param array $cc CC to, array('*****@*****.**', '*****@*****.**' => 'A name'). * @param array $bcc BCC to, array('*****@*****.**', '*****@*****.**' => 'A name'). * @param array $replyTo Reply to, array('*****@*****.**', '*****@*****.**' => 'A name'). * @param mixed $altBody Alternate body. * @param string $altBodyContentType Alternate content type default 'text/html'. * @param array $header Associative array of headers array('header1' => 'value1', 'header2' => 'value2'). * @param array &$failedRecipients Array. * @param string $charset Null means leave at default. * @param array $attachments Array of files. * * @return integet */ function send(array $from, array $to, $subject, $body, $contentType = 'text/plain', array $cc=null, array $bcc=null, array $replyTo=null, $altBody = null, $altBodyContentType = 'text/html', array $header = array(), &$failedRecipients = array(), $charset=null, array $attachments=array()) { $message = new Swift_Message($subject, $body, $contentType); $message->setTo($to); $message->setFrom($from); if ($attachments) { foreach ($attachments as $attachment) { $message->attach(Swift_Attachment::fromPath($attachment)); } } if ($cc) { $message->setCc($cc); } if ($bcc) { $message->setBcc($bcc); } if ($replyTo) { $message->setReplyTo($replyTo); } if ($charset) { $message->setCharset($charset); } if ($altBody) { $message->addPart($altBody, $altBodyContentType); } if ($headers) { $headers = $message->getHeaders(); foreach ($headers as $key => $value) { $headers->addTextHeader($key, $value); } } if ($this->serviceManager['swiftmailer.preferences.sendmethod'] == 'normal') { return $this->mailer->send($message, $failedRecipients); } else if ($this->serviceManager['swiftmailer.preferences.sendmethod'] == 'single_recipient') { return $this->mailer->sendBatch($message, $failedRecipients); } }
protected function inviteUser() { if ($this->input('email')) { if ($this->currentUser->getRole() !== UserRole::TYPE_OWNER) { $this->setError(lang('You dont have permissions to invite users')); response()->refresh(); } $this->post->email->addValidation([new ValidateInputNotNullOrEmpty(), new ValidateInputEmail()]); $this->post->role->addValidation(new ValidateInputNotNullOrEmpty()); if (!$this->hasErrors()) { $user = ModelUser::getByUsername($this->input('email')); if ($user->hasRow() && $user->hasAccess($this->activeOrganisation->id)) { if ($user->getRole() === $this->input('role')) { $this->setMessage(lang('The user already has access to this organisation'), 'danger'); } else { $user->setRole($this->input('role')); $this->setMessage(lang('The role has been updated'), 'success'); // TODO: sent mail notifying about role-change } response()->refresh(); } // Save invitation $invitation = new OrganisationInvite(); $invitation->user_id = $this->currentUser->id; $invitation->email = $this->input('email'); $invitation->organisation_id = $this->activeOrganisation->id; $invitation->role = $this->input('role'); $invitation->save(); // This point we send out a confirmation mail to accept the organisation invite. // TODO: move this shit to separate template $transport = \Swift_SendmailTransport::newInstance(env('MAIL_TRANSPORT') . ' -bs'); $swift = \Swift_Mailer::newInstance($transport); $message = new \Swift_Message(lang('Invite to join ' . $this->activeOrganisation->name . ' on NinjaImg')); $message->setFrom(env('MAIL_FROM')); $message->setSender(env('MAIL_FROM')); $message->setReplyTo(env('MAIL_FROM')); $message->setBody("Dear customer!\n\n{$this->currentUser->data->name} has invited you to join the organisation {$this->activeOrganisation->name} on NinjaImg!\n\nClick on the link below to accept the invite:\nhttps://{$_SERVER['HTTP_HOST']}" . url('user.register') . "?email=" . $this->input('email') . "\n\nIf you have any questions, feel free to contact us any time.\n\nKind regards,\nThe NinjaImg Team", 'text/plain'); $message->setTo($this->input('email')); $swift->send($message); $this->setMessage('An invite has been sent to the user.', 'success'); } } }
protected function sendCustomerMail(OrganisationInvoice $invoice) { $users = ModelUser::getByOrganisationId($this->organisation->id, UserRole::TYPE_OWNER); if ($users->hasRows()) { foreach ($users as $user) { $transport = \Swift_SendmailTransport::newInstance(env('MAIL_TRANSPORT') . ' -bs'); $swift = \Swift_Mailer::newInstance($transport); $message = new \Swift_Message(lang('New invoice available for ' . $this->organisation->name)); $currency = ModelSettings::getInstance()->data->default_currency_character; $message->setFrom(env('MAIL_FROM')); $message->setSender(env('MAIL_FROM')); $message->setReplyTo(env('MAIL_FROM')); $message->setBody("Dear {$user->data->name}!\n\nAttached is the latest invoice from NinjaImg.\n\nThe amount for invoice {$invoice->invoice_id} is {$invoice->amount_total}{$currency} with payment date {$invoice->due_date}.\n\nYou can always view your invoices at your controlpanel on ninjaimg.com.\n\nThanks for supporting our service, we really appreciate it!\n\nIf you have any questions, feel free to contact us any time.\n\nKind regards,\nThe NinjaImg Team", 'text/plain'); $message->setTo($user->username); $attachment = new \Swift_Attachment(file_get_contents($invoice->path), basename($invoice->path), File::getMime($invoice->path)); $message->attach($attachment); $swift->send($message); } } }
/** * Sends notifications *now* * @param mixed $to string or array...the type of address (email, task ID, user ID) is specified below * @param integer $to_type type of $to address * @param integer $type type of notification * @param array $data additional info needed for notification * @access public * @return bool */ function send_now($to, $to_type, $type, $data = array()) { global $db, $fs, $proj; $emails = array(); $jids = array(); $result = true; if (defined('FS_NO_MAIL')) { return true; } switch ($to_type) { case ADDRESS_DONE: // from send_stored() list($emails, $jids) = $to; $data = unserialize($data['message_data']); $subject = $data['subject']; $body = $data['body']; break; case ADDRESS_EMAIL: // this happens on email confirmation, when no user exists $emails = is_array($to) ? $to : array($to); break; case ADDRESS_USER: // list of user IDs list($emails, $jids) = Notifications::user_to_address($to, $type); break; case ADDRESS_TASK: // now we need everyone on the notification list and the assignees list($emails, $jids) = Notifications::task_notifications($to, $type, ADDRESS_EMAIL); $data['task_id'] = $to; break; } if (isset($data['task_id'])) { $data['task'] = Flyspray::getTaskDetails($data['task_id']); // we have project specific options $pid = $db->x->GetOne('SELECT project_id FROM {tasks} WHERE task_id = ?', null, $data['task_id']); $data['project'] = new Project($pid); } if ($to_type != ADDRESS_DONE) { list($subject, $body) = Notifications::generate_message($type, $data); } if (isset($data['task_id'])) { // Now, we add the project contact addresses, // but only if the task is public $data['task'] = Flyspray::getTaskDetails($data['task_id']); if ($data['task']['mark_private'] != '1' && in_array($type, explode(' ', $data['project']->prefs['notify_types']))) { $proj_emails = preg_split('/[\\s,;]+/', $proj->prefs['notify_email'], -1, PREG_SPLIT_NO_EMPTY); $proj_jids = preg_split('/[\\s,;]+/', $proj->prefs['notify_jabber'], -1, PREG_SPLIT_NO_EMPTY); $emails = array_merge($proj_emails, $emails); if ($fs->prefs['global_email']) { $emails[] = $fs->prefs['global_email']; } if ($fs->prefs['global_jabber']) { $jids[] = $fs->prefs['global_jabber']; } $jids = array_merge($proj_jids, $emails); } } // Now we start sending if (count($emails)) { Swift_ClassLoader::load('Swift_Connection_Multi'); Swift_ClassLoader::load('Swift_Connection_SMTP'); $pool = new Swift_Connection_Multi(); // first choose method if ($fs->prefs['smtp_server']) { $split = explode(':', $fs->prefs['smtp_server']); $port = null; if (count($split) == 2) { $fs->prefs['smtp_server'] = $split[0]; $port = $split[1]; } // connection... SSL, TLS or none if ($fs->prefs['email_ssl']) { $smtp = new Swift_Connection_SMTP($fs->prefs['smtp_server'], $port ? $port : SWIFT_SMTP_PORT_SECURE, SWIFT_SMTP_ENC_SSL); } else { if ($fs->prefs['email_tls']) { $smtp = new Swift_Connection_SMTP($fs->prefs['smtp_server'], $port ? $port : SWIFT_SMTP_PORT_SECURE, SWIFT_SMTP_ENC_TLS); } else { $smtp = new Swift_Connection_SMTP($fs->prefs['smtp_server'], $port); } } if ($fs->prefs['smtp_user']) { $smtp->setUsername($fs->prefs['smtp_user']); $smtp->setPassword($fs->prefs['smtp_pass']); } if (defined('FS_SMTP_TIMEOUT')) { $smtp->setTimeout(FS_SMTP_TIMEOUT); } $pool->addConnection($smtp); } else { Swift_ClassLoader::load('Swift_Connection_NativeMail'); // a connection to localhost smtp server as fallback, discarded if there is no such thing available. $pool->addConnection(new Swift_Connection_SMTP()); $pool->addConnection(new Swift_Connection_NativeMail()); } $swift = new Swift($pool); if (isset($data['task_id'])) { $swift->attachPlugin(new NotificationsThread($data['task_id'], $emails, $db), 'MessageThread'); } if (defined('FS_MAIL_DEBUG')) { $swift->log->enable(); Swift_ClassLoader::load('Swift_Plugin_VerboseSending'); $view = new Swift_Plugin_VerboseSending_DefaultView(); $swift->attachPlugin(new Swift_Plugin_VerboseSending($view), "verbose"); } $message = new Swift_Message($subject, $body); // check for reply-to if (isset($data['project']) && $data['project']->prefs['notify_reply']) { $message->setReplyTo($data['project']->prefs['notify_reply']); } if (isset($data['project']) && isset($data['project']->prefs['bounce_address'])) { $message->setReturnPath($data['project']->prefs['bounce_address']); } $message->headers->setCharset('utf-8'); $message->headers->set('Precedence', 'list'); $message->headers->set('X-Mailer', 'Flyspray'); // Add custom headers, possibly if (isset($data['headers'])) { $headers = array_map('trim', explode("\n", $data['headers'])); if ($headers = array_filter($headers)) { foreach ($headers as $header) { list($name, $value) = explode(':', $header); $message->headers->set(sprintf('X-Flyspray-%s', $name), $value); } } } $recipients = new Swift_RecipientList(); $recipients->addTo($emails); // && $result purpose: if this has been set to false before, it should never become true again // to indicate an error $result = $swift->batchSend($message, $recipients, $fs->prefs['admin_email']) === count($emails) && $result; if (isset($data['task_id'])) { $plugin =& $swift->getPlugin('MessageThread'); if (count($plugin->thread_info)) { $stmt = $db->x->autoPrepare('{notification_threads}', array('task_id', 'recipient_id', 'message_id')); $db->x->executeMultiple($stmt, $plugin->thread_info); $stmt->free(); } } $swift->disconnect(); } if (count($jids)) { $jids = array_unique($jids); if (!$fs->prefs['jabber_username'] || !$fs->prefs['jabber_password']) { return $result; } // nothing that can't be guessed correctly ^^ if (!$fs->prefs['jabber_port']) { $fs->prefs['jabber_port'] = 5222; } require_once 'class.jabber2.php'; $jabber = new Jabber($fs->prefs['jabber_username'], $fs->prefs['jabber_password'], $fs->prefs['jabber_security'], $fs->prefs['jabber_port'], $fs->prefs['jabber_server']); $jabber->SetResource('flyspray'); $jabber->login(); foreach ($jids as $jid) { $result = $jabber->send_message($jid, $body, $subject, 'normal') && $result; } } return $result; }
function SendEmail($to, $subject, $body, $task_id = null) { global $fs, $proj, $user; if (empty($to) || empty($to[0])) { return; } // Do we want to use a remote mail server? if (!empty($fs->prefs['smtp_server'])) { // connection... SSL, TLS or none if ($fs->prefs['email_tls']) { $swiftconn = Swift_SmtpTransport::newInstance($fs->prefs['smtp_server'], 587, 'tls'); } else { if ($fs->prefs['email_ssl']) { $swiftconn = Swift_SmtpTransport::newInstance($fs->prefs['smtp_server'], 465, 'ssl'); } else { $swiftconn = Swift_SmtpTransport::newInstance($fs->prefs['smtp_server']); } } if ($fs->prefs['smtp_user']) { $swiftconn->setUsername($fs->prefs['smtp_user']); } if ($fs->prefs['smtp_pass']) { $swiftconn->setPassword($fs->prefs['smtp_pass']); } if (defined('FS_SMTP_TIMEOUT')) { $swiftconn->setTimeout(FS_SMTP_TIMEOUT); } // Use php's built-in mail() function } else { $swiftconn = Swift_MailTransport::newInstance(); } if (defined('FS_MAIL_LOGFILE')) { // FIXME: Swift_LogContainer exists no more??? // See http://swiftmailer.org/docs/plugins.html#logger-plugin // for the new implementation. // $log = Swift_LogContainer::getLog(); // $log->setLogLevel(SWIFT_LOG_EVERYTHING); } // Make plaintext URLs into hyperlinks, but don't disturb existing ones! $htmlbody = preg_replace("/(?<!\")(https?:\\/\\/)([a-zA-Z0-9\\-.]+\\.[a-zA-Z0-9\\-]+([\\/]([a-zA-Z0-9_\\/\\-.?&%=+#])*)*)/", '<a href="$1$2">$2</a>', $body); $htmlbody = str_replace("\n", "<br>", $htmlbody); // Those constants used were introduced in 5.4. if (version_compare(phpversion(), '5.4.0', '<')) { $plainbody = html_entity_decode(strip_tags($body)); } else { $plainbody = html_entity_decode(strip_tags($body), ENT_COMPAT | ENT_HTML401, 'utf-8'); } $swift = Swift_Mailer::newInstance($swiftconn); $message = new Swift_Message($subject); if (isset($fs->prefs['emailNoHTML']) && $fs->prefs['emailNoHTML'] == '1') { $message->setBody($plainbody, 'text/plain'); } else { $message->setBody($htmlbody, 'text/html'); $message->addPart($plainbody, 'text/plain'); } $type = $message->getHeaders()->get('Content-Type'); $type->setParameter('charset', 'utf-8'); $message->getHeaders()->addTextHeader('Precedence', 'list'); $message->getHeaders()->addTextHeader('X-Mailer', 'Flyspray'); if ($proj->prefs['notify_reply']) { $message->setReplyTo($proj->prefs['notify_reply']); } if (isset($task_id)) { $hostdata = parse_url($GLOBALS['baseurl']); $inreplyto = sprintf('<FS%d@%s>', $task_id, $hostdata['host']); // see http://cr.yp.to/immhf/thread.html this does not seems to work though :( $message->getHeaders()->addTextHeader('In-Reply-To', $inreplyto); $message->getHeaders()->addTextHeader('References', $inreplyto); } // now accepts string , array or Swift_Address. $message->setTo($to); $message->setFrom(array($fs->prefs['admin_email'] => $proj->prefs['project_title'])); $swift->send($message); /* FIXME: Swift_LogContainer exists no more??? if(defined('FS_MAIL_LOGFILE')) { if(is_writable(dirname(FS_MAIL_LOGFILE))) { if($fh = fopen(FS_MAIL_LOGFILE, 'ab')) { fwrite($fh, $log->dump(true)); fwrite($fh, php_uname()); fclose($fh); } } } */ return true; }
/** * Returns a Swift_Message instance that can be sent * * @return \Swift_Message */ public function getSwiftMessage() { $message = new \Swift_Message(); $message->setDate($this->getDate()->getTimestamp()); $message->setFrom($this->getFrom()); $message->setReplyTo($this->getReplyTo()); $message->setReturnPath($this->getReturnPath()); $message->setTo($this->getTo()); $message->setCc($this->getCc()); $message->setBcc($this->getBcc()); $message->setSubject($this->getSubject()); $message->setBody($this->getBody()); return $message; }
/** * Set the reply-to address of this message. * * You may pass an array of addresses if replies will go to multiple people. * * If $name is passed and the first parameter is a string, this name will be * associated with the address. * * @param string|array $addresses * @param string $name optional * @return \TYPO3\CMS\Core\Mail\MailMessage */ public function setReplyTo($addresses, $name = null) { $addresses = $this->idnaEncodeAddresses($addresses); return parent::setReplyTo($addresses, $name); }
/** * Add ReplyTo e-mail addresses * * Friendly name portions (e.g. Admin <*****@*****.**>) are allowed. The * method takes an unlimited number of recipient addresses. */ public function replyTo() { $this->objMessage->setReplyTo($this->compileRecipients(func_get_args())); }
/** * {@inheritdoc} * * @return $this|self */ public function setReplyTo($addresses, $name = null) : self { $this->message->setReplyTo($addresses, $name); return $this; }
public function setReplyTo(Email $replyTo) { $this->message->setReplyTo($replyTo->email, $replyTo->name); return $this; }
/** * Set the reply-to header * @param mixed The address replies come to. String, or Swift_Address, or an array of either. */ public function setReplyTo($address) { return $this->message->setReplyTo($address); }
/** * Send an email message. * * @param string|array recipient email (and name), or an array of To, Cc, Bcc names * @param string|array sender email (and name) * @param string message subject * @param string message body * @param boolean send email as HTML * @return integer number of emails sent */ public static function send($to, $from, $subject, $message, $html = FALSE) { // Connect to SwiftMailer (email::$mail === NULL) and email::connect(); // Determine the message type $html = ($html === TRUE) ? 'text/html' : 'text/plain'; // Create the message $message = new Swift_Message($subject, $message, $html, '8bit', 'utf-8'); if (is_string($to)) { // Single recipient $recipients = new Swift_Address($to); } elseif (is_array($to)) { if (isset($to[0]) AND isset($to[1])) { // Create To: address set $to = array('to' => $to); } // Create a list of recipients $recipients = new Swift_RecipientList; foreach ($to as $method => $set) { if ( ! in_array($method, array('to', 'cc', 'bcc'))) { // Use To: by default $method = 'to'; } // Create method name $method = 'add'.ucfirst($method); if (is_array($set)) { // Add a recipient with name $recipients->$method($set[0], $set[1]); } else { // Add a recipient without name $recipients->$method($set); } } } if (is_string($from)) { // From without a name $from = new Swift_Address($from); $message->setReplyTo($from); } elseif (is_array($from)) { // From with a name $from = new Swift_Address($from[0], $from[1]); $message->setReplyTo($from); } return email::$mail->send($message, $recipients, $from); }
/** * FUNCTION: _sendMail * * Proccesses all headers and attachments ready for sending. * * @access private */ function _sendMail() { $message = new Swift_Message($this->subject); if (empty($this->sendto) and (empty($this->body) and empty($this->htmlbody))) { vlibMimeMailError::raiseError('VM_ERROR_CANNOT_SEND', FATAL); } // Attachments for ($index = 0; $index < sizeof($this->attachments); $index++) { $message->attach(new Swift_Message_Attachment(new Swift_File($this->attachments[$index]), $this->attachments[$index], $this->mimetypes[$index])); } // ReplyTo if exists if (!empty($this->replyToEmail)) { $message->setReplyTo(new Swift_Address($this->replyToEmail, $this->replyToName)); } // attach body if exist if (!empty($this->body)) { if (empty($this->htmlbody) and sizeof($this->attachments) == 0) { $message->setData($this->body); Swift_ClassLoader::load('Swift_Message_Encoder'); if (Swift_Message_Encoder::instance()->isUTF8($this->body)) { $message->setCharset('utf-8'); } else { $message->setCharset('iso-8859-1'); } } else { $message->attach(new Swift_Message_Part($this->body, 'text/plain')); } } // attach HTML body if exist if (!empty($this->htmlbody)) { $message->attach(new Swift_Message_Part($this->htmlbody, 'text/html')); } return $this->swift->send($message, $this->swift_recipients, new Swift_Address($this->fromEmail, $this->fromName)); }
/** * @Route("/contact", name="contact") * @Template * * @param Request $request * * @return array|\Symfony\Component\HttpFoundation\RedirectResponse */ public function contactAction(Request $request) { $model = new ContactModel(); $form = $this->createForm(new ContactType(), $model); if ($model = $this->process_form($form, $request)) { /** @var ContactModel $model $message */ $message = new \Swift_Message('Contact message from 21may', $this->renderView('SiteBaseBundle:Contact:mail_contact.html.twig', array('model' => $model)), 'text/html'); $message->setFrom($this->container->getParameter('site.email.from')); $message->setTo($this->container->getParameter('site.email.to')); if ($model->getEmail()) { $message->setReplyTo($model->getEmail(), $model->getName()); } $this->get('mailer')->send($message); $this->get('session')->getFlashBag()->add('contact-success', 'Your form was sent successfully'); return $this->redirect('contact'); } return array('form' => $form->createView()); }
/** * @param string $template * @param array $data * * @throws \InvalidArgumentException * @return \Swift_Mime_Message */ protected function _createMessage($template, &$data) { // Pull out all the message data $_to = array_get($data, 'to'); $_from = array_get($data, 'from'); $_replyTo = array_get($data, 'reply_to'); $_cc = array_get($data, 'cc'); $_bcc = array_get($data, 'bcc'); $_subject = array_get($data, 'subject'); // Get body template... if (false === ($_html = @file_get_contents($template))) { // Something went awry throw new \InvalidArgumentException('Error reading contents of template "' . $template . '".'); } // And the message... $_message = new \Swift_Message(); if (!empty($_subject)) { $_message->setSubject($_subject); } if (!empty($_to)) { $_message->setTo($_to); } if (!empty($_from)) { $_message->setFrom($_from); } if (!empty($_cc)) { $_message->setCc($_cc); } if (!empty($_bcc)) { $_message->setBcc($_bcc); } if (!empty($_replyTo)) { $_message->setReplyTo($_replyTo); } // process generic macros. $_message->setBody($this->replaceMacros($data, $_html), 'text/html'); return $_message; }
/** * Send Email * * @param int $id_lang Language of the email (to translate the template) * @param string $template Template: the name of template not be a var but a string ! * @param string $subject * @param string $template_vars * @param string $to * @param string $to_name * @param string $from * @param string $from_name * @param array $file_attachment Array with three parameters (content, mime and name). You can use an array of array to attach multiple files * @param bool $modeSMTP * @param string $template_path * @param bool $die * @param string $bcc Bcc recipient */ public static function Send($id_lang, $template, $subject, $template_vars, $to, $to_name = null, $from = null, $from_name = null, $file_attachment = null, $mode_smtp = null, $template_path = _PS_MAIL_DIR_, $die = false, $id_shop = null, $bcc = null, $reply_to = null) { if (!$id_shop) { $id_shop = Context::getContext()->shop->id; } $configuration = Configuration::getMultiple(array('PS_SHOP_EMAIL', 'PS_MAIL_METHOD', 'PS_MAIL_SERVER', 'PS_MAIL_USER', 'PS_MAIL_PASSWD', 'PS_SHOP_NAME', 'PS_MAIL_SMTP_ENCRYPTION', 'PS_MAIL_SMTP_PORT', 'PS_MAIL_TYPE'), null, null, $id_shop); // Returns immediatly if emails are deactivated if ($configuration['PS_MAIL_METHOD'] == 3) { return true; } $theme_path = _PS_THEME_DIR_; // Get the path of theme by id_shop if exist if (is_numeric($id_shop) && $id_shop) { $shop = new Shop((int) $id_shop); $theme_name = $shop->getTheme(); if (_THEME_NAME_ != $theme_name) { $theme_path = _PS_ROOT_DIR_ . '/themes/' . $theme_name . '/'; } } if (!isset($configuration['PS_MAIL_SMTP_ENCRYPTION'])) { $configuration['PS_MAIL_SMTP_ENCRYPTION'] = 'off'; } if (!isset($configuration['PS_MAIL_SMTP_PORT'])) { $configuration['PS_MAIL_SMTP_PORT'] = 'default'; } // Sending an e-mail can be of vital importance for the merchant, when his password is lost for example, so we must not die but do our best to send the e-mail if (!isset($from) || !Validate::isEmail($from)) { $from = $configuration['PS_SHOP_EMAIL']; } if (!Validate::isEmail($from)) { $from = null; } // $from_name is not that important, no need to die if it is not valid if (!isset($from_name) || !Validate::isMailName($from_name)) { $from_name = $configuration['PS_SHOP_NAME']; } if (!Validate::isMailName($from_name)) { $from_name = null; } // It would be difficult to send an e-mail if the e-mail is not valid, so this time we can die if there is a problem if (!is_array($to) && !Validate::isEmail($to)) { Tools::dieOrLog(Tools::displayError('Error: parameter "to" is corrupted'), $die); return false; } // if bcc is not null, make sure it's a vaild e-mail if (!is_null($bcc) && !is_array($bcc) && !Validate::isEmail($bcc)) { Tools::dieOrLog(Tools::displayError('Error: parameter "bcc" is corrupted'), $die); $bcc = null; } if (!is_array($template_vars)) { $template_vars = array(); } // Do not crash for this error, that may be a complicated customer name if (is_string($to_name) && !empty($to_name) && !Validate::isMailName($to_name)) { $to_name = null; } if (!Validate::isTplName($template)) { Tools::dieOrLog(Tools::displayError('Error: invalid e-mail template'), $die); return false; } if (!Validate::isMailSubject($subject)) { Tools::dieOrLog(Tools::displayError('Error: invalid e-mail subject'), $die); return false; } /* Construct multiple recipients list if needed */ $to_list = new Swift_RecipientList(); if (is_array($to) && isset($to)) { foreach ($to as $key => $addr) { $addr = trim($addr); if (!Validate::isEmail($addr)) { Tools::dieOrLog(Tools::displayError('Error: invalid e-mail address'), $die); return false; } if (is_array($to_name) && $to_name && is_array($to_name) && Validate::isGenericName($to_name[$key])) { $to_name = $to_name[$key]; } $to_name = $to_name == null || $to_name == $addr ? '' : self::mimeEncode($to_name); $to_list->addTo($addr, $to_name); } $to_plugin = $to[0]; } else { /* Simple recipient, one address */ $to_plugin = $to; $to_name = $to_name == null || $to_name == $to ? '' : self::mimeEncode($to_name); $to_list->addTo($to, $to_name); } if (isset($bcc)) { $to_list->addBcc($bcc); } try { /* Connect with the appropriate configuration */ if ($configuration['PS_MAIL_METHOD'] == 2) { if (empty($configuration['PS_MAIL_SERVER']) || empty($configuration['PS_MAIL_SMTP_PORT'])) { Tools::dieOrLog(Tools::displayError('Error: invalid SMTP server or SMTP port'), $die); return false; } $connection = new Swift_Connection_SMTP($configuration['PS_MAIL_SERVER'], $configuration['PS_MAIL_SMTP_PORT'], $configuration['PS_MAIL_SMTP_ENCRYPTION'] == 'ssl' ? Swift_Connection_SMTP::ENC_SSL : ($configuration['PS_MAIL_SMTP_ENCRYPTION'] == 'tls' ? Swift_Connection_SMTP::ENC_TLS : Swift_Connection_SMTP::ENC_OFF)); $connection->setTimeout(4); if (!$connection) { return false; } if (!empty($configuration['PS_MAIL_USER'])) { $connection->setUsername($configuration['PS_MAIL_USER']); } if (!empty($configuration['PS_MAIL_PASSWD'])) { $connection->setPassword($configuration['PS_MAIL_PASSWD']); } } else { $connection = new Swift_Connection_NativeMail(); } if (!$connection) { return false; } $swift = new Swift($connection, Configuration::get('PS_MAIL_DOMAIN', null, null, $id_shop)); /* Get templates content */ $iso = Language::getIsoById((int) $id_lang); if (!$iso) { Tools::dieOrLog(Tools::displayError('Error - No ISO code for email'), $die); return false; } $iso_template = $iso . '/' . $template; $module_name = false; $override_mail = false; // get templatePath if (preg_match('#' . $shop->physical_uri . 'modules/#', str_replace(DIRECTORY_SEPARATOR, '/', $template_path)) && preg_match('#modules/([a-z0-9_-]+)/#ui', str_replace(DIRECTORY_SEPARATOR, '/', $template_path), $res)) { $module_name = $res[1]; } if ($module_name !== false && (file_exists($theme_path . 'modules/' . $module_name . '/mails/' . $iso_template . '.txt') || file_exists($theme_path . 'modules/' . $module_name . '/mails/' . $iso_template . '.html'))) { $template_path = $theme_path . 'modules/' . $module_name . '/mails/'; } elseif (file_exists($theme_path . 'mails/' . $iso_template . '.txt') || file_exists($theme_path . 'mails/' . $iso_template . '.html')) { $template_path = $theme_path . 'mails/'; $override_mail = true; } if (!file_exists($template_path . $iso_template . '.txt') && ($configuration['PS_MAIL_TYPE'] == Mail::TYPE_BOTH || $configuration['PS_MAIL_TYPE'] == Mail::TYPE_TEXT)) { Tools::dieOrLog(Tools::displayError('Error - The following e-mail template is missing:') . ' ' . $template_path . $iso_template . '.txt', $die); return false; } elseif (!file_exists($template_path . $iso_template . '.html') && ($configuration['PS_MAIL_TYPE'] == Mail::TYPE_BOTH || $configuration['PS_MAIL_TYPE'] == Mail::TYPE_HTML)) { Tools::dieOrLog(Tools::displayError('Error - The following e-mail template is missing:') . ' ' . $template_path . $iso_template . '.html', $die); return false; } $template_html = ''; $template_txt = ''; Hook::exec('actionEmailAddBeforeContent', array('template' => $template, 'template_html' => &$template_html, 'template_txt' => &$template_txt, 'id_lang' => (int) $id_lang), null, true); $template_html .= file_get_contents($template_path . $iso_template . '.html'); $template_txt .= strip_tags(html_entity_decode(file_get_contents($template_path . $iso_template . '.txt'), null, 'utf-8')); Hook::exec('actionEmailAddAfterContent', array('template' => $template, 'template_html' => &$template_html, 'template_txt' => &$template_txt, 'id_lang' => (int) $id_lang), null, true); if ($override_mail && file_exists($template_path . $iso . '/lang.php')) { include_once $template_path . $iso . '/lang.php'; } elseif ($module_name && file_exists($theme_path . 'mails/' . $iso . '/lang.php')) { include_once $theme_path . 'mails/' . $iso . '/lang.php'; } elseif (file_exists(_PS_MAIL_DIR_ . $iso . '/lang.php')) { include_once _PS_MAIL_DIR_ . $iso . '/lang.php'; } else { Tools::dieOrLog(Tools::displayError('Error - The language file is missing for:') . ' ' . $iso, $die); return false; } /* Create mail and attach differents parts */ $subject = '[' . Configuration::get('PS_SHOP_NAME', null, null, $id_shop) . '] ' . $subject; $message = new Swift_Message($subject); $message->setCharset('utf-8'); /* Set Message-ID - getmypid() is blocked on some hosting */ $message->setId(Mail::generateId()); $message->headers->setEncoding('Q'); if (!($reply_to && Validate::isEmail($reply_to))) { $reply_to = $from; } if (isset($reply_to) && $reply_to) { $message->setReplyTo($reply_to); } $template_vars = array_map(array('Tools', 'htmlentitiesDecodeUTF8'), $template_vars); $template_vars = array_map(array('Tools', 'stripslashes'), $template_vars); if (Configuration::get('PS_LOGO_MAIL') !== false && file_exists(_PS_IMG_DIR_ . Configuration::get('PS_LOGO_MAIL', null, null, $id_shop))) { $logo = _PS_IMG_DIR_ . Configuration::get('PS_LOGO_MAIL', null, null, $id_shop); } else { if (file_exists(_PS_IMG_DIR_ . Configuration::get('PS_LOGO', null, null, $id_shop))) { $logo = _PS_IMG_DIR_ . Configuration::get('PS_LOGO', null, null, $id_shop); } else { $template_vars['{shop_logo}'] = ''; } } ShopUrl::cacheMainDomainForShop((int) $id_shop); /* don't attach the logo as */ if (isset($logo)) { $template_vars['{shop_logo}'] = $message->attach(new Swift_Message_EmbeddedFile(new Swift_File($logo), null, ImageManager::getMimeTypeByExtension($logo))); } if (Context::getContext()->link instanceof Link === false) { Context::getContext()->link = new Link(); } $template_vars['{shop_name}'] = Tools::safeOutput(Configuration::get('PS_SHOP_NAME', null, null, $id_shop)); $template_vars['{shop_url}'] = Context::getContext()->link->getPageLink('index', true, Context::getContext()->language->id, null, false, $id_shop); $template_vars['{my_account_url}'] = Context::getContext()->link->getPageLink('my-account', true, Context::getContext()->language->id, null, false, $id_shop); $template_vars['{guest_tracking_url}'] = Context::getContext()->link->getPageLink('guest-tracking', true, Context::getContext()->language->id, null, false, $id_shop); $template_vars['{history_url}'] = Context::getContext()->link->getPageLink('history', true, Context::getContext()->language->id, null, false, $id_shop); $template_vars['{color}'] = Tools::safeOutput(Configuration::get('PS_MAIL_COLOR', null, null, $id_shop)); // Get extra template_vars $extra_template_vars = array(); Hook::exec('actionGetExtraMailTemplateVars', array('template' => $template, 'template_vars' => $template_vars, 'extra_template_vars' => &$extra_template_vars, 'id_lang' => (int) $id_lang), null, true); $template_vars = array_merge($template_vars, $extra_template_vars); $swift->attachPlugin(new Swift_Plugin_Decorator(array($to_plugin => $template_vars)), 'decorator'); if ($configuration['PS_MAIL_TYPE'] == Mail::TYPE_BOTH || $configuration['PS_MAIL_TYPE'] == Mail::TYPE_TEXT) { $message->attach(new Swift_Message_Part($template_txt, 'text/plain', '8bit', 'utf-8')); } if ($configuration['PS_MAIL_TYPE'] == Mail::TYPE_BOTH || $configuration['PS_MAIL_TYPE'] == Mail::TYPE_HTML) { $message->attach(new Swift_Message_Part($template_html, 'text/html', '8bit', 'utf-8')); } if ($file_attachment && !empty($file_attachment)) { // Multiple attachments? if (!is_array(current($file_attachment))) { $file_attachment = array($file_attachment); } foreach ($file_attachment as $attachment) { if (isset($attachment['content']) && isset($attachment['name']) && isset($attachment['mime'])) { $message->attach(new Swift_Message_Attachment($attachment['content'], $attachment['name'], $attachment['mime'])); } } } /* Send mail */ $send = $swift->send($message, $to_list, new Swift_Address($from, $from_name)); $swift->disconnect(); ShopUrl::resetMainDomainCache(); if ($send && Configuration::get('PS_LOG_EMAILS')) { $mail = new Mail(); $mail->template = substr($template, 0, 62); $mail->subject = substr($subject, 0, 254); $mail->id_lang = (int) $id_lang; foreach (array_merge($to_list->getTo(), $to_list->getCc(), $to_list->getBcc()) as $recipient) { /** @var Swift_Address $recipient */ $mail->id = null; $mail->recipient = substr($recipient->getAddress(), 0, 126); $mail->add(); } } return $send; } catch (Swift_Exception $e) { PrestaShopLogger::addLog('Swift Error: ' . $e->getMessage(), 3, null, 'Swift_Message'); return false; } }
protected function invitationAcceptedMail(OrganisationInvite $invite, ModelOrganisation $organisation, ModelUser $user) { $senderUser = ModelUser::getById($invite->user_id); if ($senderUser->hasRow() && !$senderUser->deleted) { $transport = \Swift_SendmailTransport::newInstance(env('MAIL_TRANSPORT') . ' -bs'); $swift = \Swift_Mailer::newInstance($transport); $message = new \Swift_Message(lang('Invitation to ' . $organisation->name . ' accepted')); $message->setFrom(env('MAIL_FROM')); $message->setSender(env('MAIL_FROM')); $message->setReplyTo(env('MAIL_FROM')); $message->setBody("Dear {$senderUser->data->name}!\n\nWe are writing to inform you, that {$user->data->name} has just accepted your invitation to join the organisation {$organisation->name} on NinjaImg.\n\nIf you have any questions, feel free to contact us any time.\n\nKind regards,\nThe NinjaImg Team", 'text/plain'); $message->setTo($senderUser->username); $swift->send($message); } }
function SendEmail($to, $subject, $body, $task_id = null) { global $fs, $proj, $user; if (empty($to) || empty($to[0])) { return; } // Do we want to use a remote mail server? if (!empty($fs->prefs['smtp_server'])) { // connection... SSL, TLS or none if ($fs->prefs['email_tls']) { $swiftconn = Swift_SmtpTransport::newInstance($fs->prefs['smtp_server'], 587, 'tls'); } else { if ($fs->prefs['email_ssl']) { $swiftconn = Swift_SmtpTransport::newInstance($fs->prefs['smtp_server'], 465, 'ssl'); } else { $swiftconn = Swift_SmtpTransport::newInstance($fs->prefs['smtp_server']); } } if ($fs->prefs['smtp_user']) { $swiftconn->setUsername($fs->prefs['smtp_user']); $swiftconn->setPassword($fs->prefs['smtp_pass']); } if (defined('FS_SMTP_TIMEOUT')) { $swiftconn->setTimeout(FS_SMTP_TIMEOUT); } // Use php's built-in mail() function } else { $swiftconn = Swift_MailTransport::newInstance(); } if (defined('FS_MAIL_LOGFILE')) { $log = Swift_LogContainer::getLog(); $log->setLogLevel(SWIFT_LOG_EVERYTHING); } $swift = Swift_Mailer::newInstance($swiftconn); $message = new Swift_Message($subject); $message->setBody($body); $type = $message->getHeaders()->get('Content-Type'); $type->setValue('text/plain'); $type->setParameter('charset', 'utf-8'); $message->getHeaders()->addTextHeader('Precedence', 'list'); $message->getHeaders()->addTextHeader('X-Mailer', 'Flyspray'); if ($proj->prefs['notify_reply']) { $message->setReplyTo($proj->prefs['notify_reply']); } if (isset($task_id)) { $hostdata = parse_url($GLOBALS['baseurl']); $inreplyto = sprintf('<FS%d@%s>', $task_id, $hostdata['host']); // see http://cr.yp.to/immhf/thread.html this does not seems to work though :( $message->getHeaders()->addTextHeader('In-Reply-To', $inreplyto); $message->getHeaders()->addTextHeader('References', $inreplyto); } // now accepts string , array or Swift_Address. $message->setTo($to); $message->setFrom(array($fs->prefs['admin_email'] => $proj->prefs['project_title'])); $swift->send($message); if (defined('FS_MAIL_LOGFILE')) { if (is_writable(dirname(FS_MAIL_LOGFILE))) { if ($fh = fopen(FS_MAIL_LOGFILE, 'ab')) { fwrite($fh, $log->dump(true)); fwrite($fh, php_uname()); fclose($fh); } } } return true; }
/** * Send a message to any number of recipients * @param Swift_Message The message to send. This does not need to (and shouldn't really) have any of the recipient headers set. * @param mixed The recipients to send to. Can be a string, Swift_Address or Swift_RecipientList. Note that all addresses apart from Bcc recipients will appear in the message headers * @param mixed The address to send the message from. Can either be a string or an instance of Swift_Address. * @return int The number of successful recipients * @throws Swift_ConnectionException If sending fails for any reason. */ public function send(Swift_Message $message, $recipients, $from) { Swift_ClassLoader::load("Swift_Message_Encoder"); if (is_string($recipients) && preg_match("/^" . Swift_Message_Encoder::CHEAP_ADDRESS_RE . "\$/", $recipients)) { $recipients = new Swift_Address($recipients); } elseif (!$recipients instanceof Swift_AddressContainer) { throw new Exception("The recipients parameter must either be a valid string email address, " . "an instance of Swift_RecipientList or an instance of Swift_Address."); } if (is_string($from) && preg_match("/^" . Swift_Message_Encoder::CHEAP_ADDRESS_RE . "\$/", $from)) { $from = new Swift_Address($from); } elseif (!$from instanceof Swift_Address) { throw new Exception("The sender parameter must either be a valid string email address or " . "an instance of Swift_Address."); } $log = Swift_LogContainer::getLog(); if (!$message->getEncoding() && !$this->connection->hasExtension("8BITMIME")) { $message->setEncoding("QP", true, true); } $list = $recipients; if ($recipients instanceof Swift_Address) { $list = new Swift_RecipientList(); $list->addTo($recipients); } Swift_ClassLoader::load("Swift_Events_SendEvent"); $send_event = new Swift_Events_SendEvent($message, $list, $from, 0); $this->notifyListeners($send_event, "BeforeSendListener"); $to = $cc = array(); if (!($has_from = $message->getFrom())) { $message->setFrom($from); } if (!($has_return_path = $message->getReturnPath())) { $message->setReturnPath($from->build(true)); } if (!($has_reply_to = $message->getReplyTo())) { $message->setReplyTo($from); } if (!$has_reply_to[0]) { $message->setReplyTo($from->getAddress()); } if (!($has_message_id = $message->getId())) { $message->generateId(); } $this->command("MAIL FROM: " . $message->getReturnPath(true), 250); $failed = 0; $sent = 0; $tmp_sent = 0; $it = $list->getIterator("to"); while ($it->hasNext()) { $it->next(); $address = $it->getValue(); $to[] = $address->build(); try { $this->command("RCPT TO: " . $address->build(true), 250); $tmp_sent++; } catch (Swift_BadResponseException $e) { $failed++; $send_event->addFailedRecipient($address->getAddress()); if ($log->hasLevel(Swift_Log::LOG_FAILURES)) { $log->addfailedRecipient($address->getAddress()); } } } $it = $list->getIterator("cc"); while ($it->hasNext()) { $it->next(); $address = $it->getValue(); $cc[] = $address->build(); try { $this->command("RCPT TO: " . $address->build(true), 250); $tmp_sent++; } catch (Swift_BadResponseException $e) { $failed++; $send_event->addFailedRecipient($address->getAddress()); if ($log->hasLevel(Swift_Log::LOG_FAILURES)) { $log->addfailedRecipient($address->getAddress()); } } } if ($failed == count($to) + count($cc)) { $this->reset(); $this->notifyListeners($send_event, "SendListener"); return 0; } if (!($has_to = $message->getTo()) && !empty($to)) { $message->setTo($to); } if (!($has_cc = $message->getCc()) && !empty($cc)) { $message->setCc($cc); } $this->command("DATA", 354); $data = $message->build(); while (false !== ($bytes = $data->read())) { $this->command($bytes, -1); } if ($log->hasLevel(Swift_Log::LOG_NETWORK)) { $log->add("<MESSAGE DATA>", Swift_Log::COMMAND); } try { $this->command("\r\n.", 250); $sent += $tmp_sent; } catch (Swift_BadResponseException $e) { $failed += $tmp_sent; } $tmp_sent = 0; $has_bcc = $message->getBcc(); $it = $list->getIterator("bcc"); while ($it->hasNext()) { $it->next(); $address = $it->getValue(); if (!$has_bcc) { $message->setBcc($address->build()); } try { $this->command("MAIL FROM: " . $message->getReturnPath(true), 250); $this->command("RCPT TO: " . $address->build(true), 250); $this->command("DATA", 354); $data = $message->build(); while (false !== ($bytes = $data->read())) { $this->command($bytes, -1); } if ($log->hasLevel(Swift_Log::LOG_NETWORK)) { $log->add("<MESSAGE DATA>", Swift_Log::COMMAND); } $this->command("\r\n.", 250); $sent++; } catch (Swift_BadResponseException $e) { $failed++; $send_event->addFailedRecipient($address->getAddress()); if ($log->hasLevel(Swift_Log::LOG_FAILURES)) { $log->addfailedRecipient($address->getAddress()); } $this->reset(); } } $total = count($to) + count($cc) + count($list->getBcc()); $send_event->setNumSent($sent); $this->notifyListeners($send_event, "SendListener"); if (!$has_return_path) { $message->setReturnPath(""); } if (!$has_from) { $message->setFrom(""); } if (!$has_to) { $message->setTo(""); } if (!$has_reply_to) { $message->setReplyTo(null); } if (!$has_cc) { $message->setCc(null); } if (!$has_bcc) { $message->setBcc(null); } if (!$has_message_id) { $message->setId(null); } if ($log->hasLevel(Swift_Log::LOG_NETWORK)) { $log->add("Message sent to " . $sent . "/" . $total . " recipients", Swift_Log::NORMAL); } return $sent; }
/** * @param $email * @param string $nombre */ public function response($email, $nombre = '') { $this->message->setReplyTo([$email => $nombre]); }