public function set_mime_body($text_body, $html_body, $attachments, $embeds) { if (!class_exists('Mail_mime')) { @(include_once 'Mail/mime.php'); } if (!class_exists('Mail_mime')) { debug_add('Mail_mime does not exist, setting text body and aborting', MIDCOM_LOG_WARN); $this->_body = $text_body; return false; } $this->__mime = new Mail_mime("\n"); $this->__mime->_build_params['html_charset'] = strtoupper($this->_encoding); $this->__mime->_build_params['text_charset'] = strtoupper($this->_encoding); $this->__mime->_build_params['head_charset'] = strtoupper($this->_encoding); $this->__mime->_build_params['text_encoding'] = '8bit'; reset($this->__mime); if (strlen($html_body) > 0) { $this->__mime->setHTMLBody($html_body); } if (strlen($text_body) > 0) { $this->__mime->setTxtBody($text_body); } if (!empty($attachments)) { $this->_process_attachments($attachments, 'addAttachment'); } if (!empty($embeds)) { $this->_process_attachments($embeds, 'addHTMLImage'); } $this->_body = $this->__mime->get(); $this->_headers = $this->__mime->headers($this->_headers); // some MTAs manage to mangle multiline headers (RFC "folded"), // here we make sure at least the content type is in single line $this->_headers['Content-Type'] = preg_replace('/\\s+/', ' ', $this->_headers['Content-Type']); }
/** * Compose a message. * * @param int $job_id * ID of the Job associated with this message. * @param int $event_queue_id * ID of the EventQueue. * @param string $hash * Hash of the EventQueue. * @param string $contactId * ID of the Contact. * @param string $email * Destination address. * @param string $recipient * To: of the recipient. * @param bool $test * Is this mailing a test?. * @param $contactDetails * @param $attachments * @param bool $isForward * Is this mailing compose for forward?. * @param string $fromEmail * Email address of who is forwardinf it. * * @param null $replyToEmail * * @return Mail_mime The mail object */ public function compose($job_id, $event_queue_id, $hash, $contactId, $email, &$recipient, $test, $contactDetails, &$attachments, $isForward = FALSE, $fromEmail = NULL, $replyToEmail = NULL) { $config = CRM_Core_Config::singleton(); $this->getTokens(); if ($this->_domain == NULL) { $this->_domain = CRM_Core_BAO_Domain::getDomain(); } list($verp, $urls, $headers) = $this->getVerpAndUrlsAndHeaders($job_id, $event_queue_id, $hash, $email, $isForward); //set from email who is forwarding it and not original one. if ($fromEmail) { unset($headers['From']); $headers['From'] = "<{$fromEmail}>"; } if ($replyToEmail && $fromEmail != $replyToEmail) { $headers['Reply-To'] = "{$replyToEmail}"; } if ($contactDetails) { $contact = $contactDetails; } elseif ($contactId === 0) { //anonymous user $contact = array(); CRM_Utils_Hook::tokenValues($contact, $contactId, $job_id); } else { $params = array(array('contact_id', '=', $contactId, 0, 0)); list($contact) = CRM_Contact_BAO_Query::apiQuery($params); //CRM-4524 $contact = reset($contact); if (!$contact || is_a($contact, 'CRM_Core_Error')) { CRM_Core_Error::debug_log_message(ts('CiviMail will not send email to a non-existent contact: %1', array(1 => $contactId))); // setting this because function is called by reference //@todo test not calling function by reference $res = NULL; return $res; } // also call the hook to get contact details CRM_Utils_Hook::tokenValues($contact, $contactId, $job_id); } $pTemplates = $this->getPreparedTemplates(); $pEmails = array(); foreach ($pTemplates as $type => $pTemplate) { $html = $type == 'html' ? TRUE : FALSE; $pEmails[$type] = array(); $pEmail =& $pEmails[$type]; $template =& $pTemplates[$type]['template']; $tokens =& $pTemplates[$type]['tokens']; $idx = 0; if (!empty($tokens)) { foreach ($tokens as $idx => $token) { $token_data = $this->getTokenData($token, $html, $contact, $verp, $urls, $event_queue_id); array_push($pEmail, $template[$idx]); array_push($pEmail, $token_data); } } else { array_push($pEmail, $template[$idx]); } if (isset($template[$idx + 1])) { array_push($pEmail, $template[$idx + 1]); } } $html = NULL; if (isset($pEmails['html']) && is_array($pEmails['html']) && count($pEmails['html'])) { $html =& $pEmails['html']; } $text = NULL; if (isset($pEmails['text']) && is_array($pEmails['text']) && count($pEmails['text'])) { $text =& $pEmails['text']; } // push the tracking url on to the html email if necessary if ($this->open_tracking && $html) { array_push($html, "\n" . '<img src="' . $config->userFrameworkResourceURL . "extern/open.php?q={$event_queue_id}\" width='1' height='1' alt='' border='0'>"); } $message = new Mail_mime("\n"); $useSmarty = defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY ? TRUE : FALSE; if ($useSmarty) { $smarty = CRM_Core_Smarty::singleton(); // also add the contact tokens to the template $smarty->assign_by_ref('contact', $contact); } $mailParams = $headers; if ($text && ($test || $contact['preferred_mail_format'] == 'Text' || $contact['preferred_mail_format'] == 'Both' || $contact['preferred_mail_format'] == 'HTML' && !array_key_exists('html', $pEmails))) { $textBody = implode('', $text); if ($useSmarty) { $textBody = $smarty->fetch("string:{$textBody}"); } $mailParams['text'] = $textBody; } if ($html && ($test || ($contact['preferred_mail_format'] == 'HTML' || $contact['preferred_mail_format'] == 'Both'))) { $htmlBody = implode('', $html); if ($useSmarty) { $htmlBody = $smarty->fetch("string:{$htmlBody}"); } $mailParams['html'] = $htmlBody; } if (empty($mailParams['text']) && empty($mailParams['html'])) { // CRM-9833 // something went wrong, lets log it and return null (by reference) CRM_Core_Error::debug_log_message(ts('CiviMail will not send an empty mail body, Skipping: %1', array(1 => $email))); $res = NULL; return $res; } $mailParams['attachments'] = $attachments; $mailingSubject = CRM_Utils_Array::value('subject', $pEmails); if (is_array($mailingSubject)) { $mailingSubject = implode('', $mailingSubject); } $mailParams['Subject'] = $mailingSubject; $mailParams['toName'] = CRM_Utils_Array::value('display_name', $contact); $mailParams['toEmail'] = $email; // Add job ID to mailParams for external email delivery service to utilise $mailParams['job_id'] = $job_id; CRM_Utils_Hook::alterMailParams($mailParams, 'civimail'); // CRM-10699 support custom email headers if (!empty($mailParams['headers'])) { $headers = array_merge($headers, $mailParams['headers']); } //cycle through mailParams and set headers array foreach ($mailParams as $paramKey => $paramValue) { //exclude values not intended for the header if (!in_array($paramKey, array('text', 'html', 'attachments', 'toName', 'toEmail'))) { $headers[$paramKey] = $paramValue; } } if (!empty($mailParams['text'])) { $message->setTxtBody($mailParams['text']); } if (!empty($mailParams['html'])) { $message->setHTMLBody($mailParams['html']); } if (!empty($mailParams['attachments'])) { foreach ($mailParams['attachments'] as $fileID => $attach) { $message->addAttachment($attach['fullPath'], $attach['mime_type'], $attach['cleanName']); } } //pickup both params from mail params. $toName = trim($mailParams['toName']); $toEmail = trim($mailParams['toEmail']); if ($toName == $toEmail || strpos($toName, '@') !== FALSE) { $toName = NULL; } else { $toName = CRM_Utils_Mail::formatRFC2822Name($toName); } $headers['To'] = "{$toName} <{$toEmail}>"; $headers['Precedence'] = 'bulk'; // Will test in the mail processor if the X-VERP is set in the bounced email. // (As an option to replace real VERP for those that can't set it up) $headers['X-CiviMail-Bounce'] = $verp['bounce']; //CRM-5058 //token replacement of subject $headers['Subject'] = $mailingSubject; CRM_Utils_Mail::setMimeParams($message); $headers = $message->headers($headers); //get formatted recipient $recipient = $headers['To']; // make sure we unset a lot of stuff unset($verp); unset($urls); unset($params); unset($contact); unset($ids); return $message; }
/** * Ask a contact for subscription confirmation (opt-in) * * @param string $email * The email address. * * @return void */ public function send_confirm_request($email) { $config = CRM_Core_Config::singleton(); $domain = CRM_Core_BAO_Domain::getDomain(); //get the default domain email address. list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail(); $localpart = CRM_Core_BAO_MailSettings::defaultLocalpart(); $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain(); $confirm = implode($config->verpSeparator, array($localpart . 'c', $this->contact_id, $this->id, $this->hash)) . "@{$emailDomain}"; $group = new CRM_Contact_BAO_Group(); $group->id = $this->group_id; $group->find(TRUE); $component = new CRM_Mailing_BAO_Component(); $component->is_default = 1; $component->is_active = 1; $component->component_type = 'Subscribe'; $component->find(TRUE); $headers = array('Subject' => $component->subject, 'From' => "\"{$domainEmailName}\" <{$domainEmailAddress}>", 'To' => $email, 'Reply-To' => $confirm, 'Return-Path' => "do-not-reply@{$emailDomain}"); $url = CRM_Utils_System::url('civicrm/mailing/confirm', "reset=1&cid={$this->contact_id}&sid={$this->id}&h={$this->hash}", TRUE); $html = $component->body_html; if ($component->body_text) { $text = $component->body_text; } else { $text = CRM_Utils_String::htmlToText($component->body_html); } $bao = new CRM_Mailing_BAO_Mailing(); $bao->body_text = $text; $bao->body_html = $html; $tokens = $bao->getTokens(); $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, TRUE, $tokens['html']); $html = CRM_Utils_Token::replaceSubscribeTokens($html, $group->title, $url, TRUE); $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, FALSE, $tokens['text']); $text = CRM_Utils_Token::replaceSubscribeTokens($text, $group->title, $url, FALSE); // render the & entities in text mode, so that the links work $text = str_replace('&', '&', $text); $message = new Mail_mime("\n"); $message->setHTMLBody($html); $message->setTxtBody($text); $b = CRM_Utils_Mail::setMimeParams($message); $h = $message->headers($headers); CRM_Mailing_BAO_Mailing::addMessageIdHeader($h, 's', $this->contact_id, $this->id, $this->hash); $mailer = \Civi::service('pear_mail'); if (is_object($mailer)) { $errorScope = CRM_Core_TemporaryErrorScope::ignoreException(); $mailer->send($email, $h, $b); unset($errorScope); } }
/** * Send a response email informing the contact of the groups from which he. * has been unsubscribed. * * @param string $queue_id * The queue event ID. * @param array $groups * List of group IDs. * @param bool $is_domain * Is this domain-level?. * @param int $job * The job ID. */ public static function send_unsub_response($queue_id, $groups, $is_domain = FALSE, $job) { $config = CRM_Core_Config::singleton(); $domain = CRM_Core_BAO_Domain::getDomain(); $jobObject = new CRM_Mailing_BAO_MailingJob(); $jobTable = $jobObject->getTableName(); $mailingObject = new CRM_Mailing_DAO_Mailing(); $mailingTable = $mailingObject->getTableName(); $contactsObject = new CRM_Contact_DAO_Contact(); $contacts = $contactsObject->getTableName(); $emailObject = new CRM_Core_DAO_Email(); $email = $emailObject->getTableName(); $queueObject = new CRM_Mailing_Event_BAO_Queue(); $queue = $queueObject->getTableName(); //get the default domain email address. list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail(); $dao = new CRM_Mailing_BAO_Mailing(); $dao->query(" SELECT * FROM {$mailingTable}\n INNER JOIN {$jobTable} ON\n {$jobTable}.mailing_id = {$mailingTable}.id\n WHERE {$jobTable}.id = {$job}"); $dao->fetch(); $component = new CRM_Mailing_BAO_Component(); if ($is_domain) { $component->id = $dao->optout_id; } else { $component->id = $dao->unsubscribe_id; } $component->find(TRUE); $html = $component->body_html; if ($component->body_text) { $text = $component->body_text; } else { $text = CRM_Utils_String::htmlToText($component->body_html); } $eq = new CRM_Core_DAO(); $eq->query("SELECT {$contacts}.preferred_mail_format as format,\n {$contacts}.id as contact_id,\n {$email}.email as email,\n {$queue}.hash as hash\n FROM {$contacts}\n INNER JOIN {$queue} ON {$queue}.contact_id = {$contacts}.id\n INNER JOIN {$email} ON {$queue}.email_id = {$email}.id\n WHERE {$queue}.id = " . CRM_Utils_Type::escape($queue_id, 'Integer')); $eq->fetch(); if ($groups) { foreach ($groups as $key => $value) { if (!$value) { unset($groups[$key]); } } } $message = new Mail_mime("\n"); list($addresses, $urls) = CRM_Mailing_BAO_Mailing::getVerpAndUrls($job, $queue_id, $eq->hash, $eq->email); $bao = new CRM_Mailing_BAO_Mailing(); $bao->body_text = $text; $bao->body_html = $html; $tokens = $bao->getTokens(); if ($eq->format == 'HTML' || $eq->format == 'Both') { $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, TRUE, $tokens['html']); $html = CRM_Utils_Token::replaceUnsubscribeTokens($html, $domain, $groups, TRUE, $eq->contact_id, $eq->hash); $html = CRM_Utils_Token::replaceActionTokens($html, $addresses, $urls, TRUE, $tokens['html']); $html = CRM_Utils_Token::replaceMailingTokens($html, $dao, NULL, $tokens['html']); $message->setHTMLBody($html); } if (!$html || $eq->format == 'Text' || $eq->format == 'Both') { $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, FALSE, $tokens['text']); $text = CRM_Utils_Token::replaceUnsubscribeTokens($text, $domain, $groups, FALSE, $eq->contact_id, $eq->hash); $text = CRM_Utils_Token::replaceActionTokens($text, $addresses, $urls, FALSE, $tokens['text']); $text = CRM_Utils_Token::replaceMailingTokens($text, $dao, NULL, $tokens['text']); $message->setTxtBody($text); } $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain(); $headers = array('Subject' => $component->subject, 'From' => "\"{$domainEmailName}\" <do-not-reply@{$emailDomain}>", 'To' => $eq->email, 'Reply-To' => "do-not-reply@{$emailDomain}", 'Return-Path' => "do-not-reply@{$emailDomain}"); CRM_Mailing_BAO_Mailing::addMessageIdHeader($headers, 'u', $job, $queue_id, $eq->hash); $b = CRM_Utils_Mail::setMimeParams($message); $h = $message->headers($headers); $mailer = \Civi::service('pear_mail'); if (is_object($mailer)) { $errorScope = CRM_Core_TemporaryErrorScope::ignoreException(); $mailer->send($eq->email, $h, $b); unset($errorScope); } }
/** * Wrapper function to send mail in CiviCRM. Hooks are called from this function. The input parameter * is an associateive array which holds the values of field needed to send an email. These are: * * from : complete from envelope * toName : name of person to send email * toEmail : email address to send to * cc : email addresses to cc * bcc : email addresses to bcc * subject : subject of the email * text : text of the message * html : html version of the message * replyTo : reply-to header in the email * attachments: an associative array of * fullPath : complete pathname to the file * mime_type: mime type of the attachment * cleanName: the user friendly name of the attachmment * * @param array $params (by reference) * * @access public * * @return boolean true if a mail was sent, else false */ static function send(&$params) { $returnPath = CRM_Core_BAO_MailSettings::defaultReturnPath(); $includeMessageId = CRM_Core_BAO_MailSettings::includeMessageId(); $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain(); $from = CRM_Utils_Array::value('from', $params); if (!$returnPath) { $returnPath = self::pluckEmailFromHeader($from); } $params['returnPath'] = $returnPath; // first call the mail alter hook CRM_Utils_Hook::alterMailParams($params); // check if any module has aborted mail sending if (CRM_Utils_Array::value('abortMailSend', $params) || !CRM_Utils_Array::value('toEmail', $params)) { return FALSE; } $textMessage = CRM_Utils_Array::value('text', $params); $htmlMessage = CRM_Utils_Array::value('html', $params); $attachments = CRM_Utils_Array::value('attachments', $params); // CRM-6224 if (trim(CRM_Utils_String::htmlToText($htmlMessage)) == '') { $htmlMessage = FALSE; } $headers = array(); // CRM-10699 support custom email headers if (CRM_Utils_Array::value('headers', $params)) { $headers = array_merge($headers, $params['headers']); } $headers['From'] = $params['from']; $headers['To'] = self::formatRFC822Email(CRM_Utils_Array::value('toName', $params), CRM_Utils_Array::value('toEmail', $params), FALSE); $headers['Cc'] = CRM_Utils_Array::value('cc', $params); $headers['Bcc'] = CRM_Utils_Array::value('bcc', $params); $headers['Subject'] = CRM_Utils_Array::value('subject', $params); $headers['Content-Type'] = $htmlMessage ? 'multipart/mixed; charset=utf-8' : 'text/plain; charset=utf-8'; $headers['Content-Disposition'] = 'inline'; $headers['Content-Transfer-Encoding'] = '8bit'; $headers['Return-Path'] = CRM_Utils_Array::value('returnPath', $params); // CRM-11295: Omit reply-to headers if empty; this avoids issues with overzealous mailservers $replyTo = CRM_Utils_Array::value('replyTo', $params, $from); if (!empty($replyTo)) { $headers['Reply-To'] = $replyTo; } $headers['Date'] = date('r'); if ($includeMessageId) { $headers['Message-ID'] = '<' . uniqid('civicrm_', TRUE) . "@{$emailDomain}>"; } if (CRM_Utils_Array::value('autoSubmitted', $params)) { $headers['Auto-Submitted'] = "Auto-Generated"; } //make sure we has to have space, CRM-6977 foreach (array('From', 'To', 'Cc', 'Bcc', 'Reply-To', 'Return-Path') as $fld) { if (isset($headers[$fld])) { $headers[$fld] = str_replace('"<', '" <', $headers[$fld]); } } // quote FROM, if comma is detected AND is not already quoted. CRM-7053 if (strpos($headers['From'], ',') !== FALSE) { $from = explode(' <', $headers['From']); $headers['From'] = self::formatRFC822Email($from[0], substr(trim($from[1]), 0, -1), TRUE); } require_once 'Mail/mime.php'; $msg = new Mail_mime("\n"); if ($textMessage) { $msg->setTxtBody($textMessage); } if ($htmlMessage) { $msg->setHTMLBody($htmlMessage); } if (!empty($attachments)) { foreach ($attachments as $fileID => $attach) { $msg->addAttachment($attach['fullPath'], $attach['mime_type'], $attach['cleanName']); } } $message = self::setMimeParams($msg); $headers =& $msg->headers($headers); $to = array($params['toEmail']); //get emails from headers, since these are //combination of name and email addresses. if (CRM_Utils_Array::value('Cc', $headers)) { $to[] = CRM_Utils_Array::value('Cc', $headers); } if (CRM_Utils_Array::value('Bcc', $headers)) { $to[] = CRM_Utils_Array::value('Bcc', $headers); unset($headers['Bcc']); } $result = NULL; $mailer = CRM_Core_Config::getMailer(); CRM_Core_Error::ignoreException(); if (is_object($mailer)) { $result = $mailer->send($to, $headers, $message); CRM_Core_Error::setCallback(); if (is_a($result, 'PEAR_Error')) { $message = self::errorMessage($mailer, $result); // append error message in case multiple calls are being made to // this method in the course of sending a batch of messages. CRM_Core_Session::setStatus($message, TRUE); return FALSE; } // CRM-10699 CRM_Utils_Hook::postEmailSend($params); return TRUE; } return FALSE; }
/** * Forward a mailing reply. * * @param int $queue_id * Queue event ID of the sender. * @param string $mailing * The mailing object. * @param string $bodyTxt * Text part of the body (ignored if $fullEmail provided). * @param string $replyto * Reply-to of the incoming message. * @param string $bodyHTML * HTML part of the body (ignored if $fullEmail provided). * @param string $fullEmail * Whole email to forward in one string. * * @return void */ public static function send($queue_id, &$mailing, &$bodyTxt, $replyto, &$bodyHTML = NULL, &$fullEmail = NULL) { $domain = CRM_Core_BAO_Domain::getDomain(); $emails = CRM_Core_BAO_Email::getTableName(); $queue = CRM_Mailing_Event_BAO_Queue::getTableName(); $contacts = CRM_Contact_BAO_Contact::getTableName(); $eq = new CRM_Core_DAO(); $eq->query("SELECT {$contacts}.display_name as display_name,\n {$emails}.email as email,\n {$queue}.job_id as job_id,\n {$queue}.hash as hash\n FROM {$queue}\n INNER JOIN {$contacts}\n ON {$queue}.contact_id = {$contacts}.id\n INNER JOIN {$emails}\n ON {$queue}.email_id = {$emails}.id\n WHERE {$queue}.id = " . CRM_Utils_Type::escape($queue_id, 'Integer')); $eq->fetch(); if ($fullEmail) { // parse the email and set a new destination $parser = new ezcMailParser(); $set = new ezcMailVariableSet($fullEmail); $parsed = array_shift($parser->parseMail($set)); $parsed->to = array(new ezcMailAddress($mailing->replyto_email)); // CRM-5567: we need to set Reply-To: so that any response // to the forward goes to the sender of the reply $parsed->setHeader('Reply-To', $replyto instanceof ezcMailAddress ? $replyto : $parsed->from->__toString()); // $h must be an array, so we can't use generateHeaders()'s result, // but we have to regenerate the headers because we changed To $parsed->generateHeaders(); $h = $parsed->headers->getCaseSensitiveArray(); $b = $parsed->generateBody(); // strip Return-Path of possible bounding brackets, CRM-4502 if (!empty($h['Return-Path'])) { $h['Return-Path'] = trim($h['Return-Path'], '<>'); } // FIXME: ugly hack - find the first MIME boundary in // the body and make the boundary in the header match it $ct = $h['Content-Type']; if (substr_count($ct, 'boundary=')) { $matches = array(); preg_match('/^--(.*)$/m', $b, $matches); $boundary = rtrim($matches[1]); $parts = explode('boundary=', $ct); $ct = "{$parts[0]} boundary=\"{$boundary}\""; } } else { $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain(); if (empty($eq->display_name)) { $from = $eq->email; } else { $from = "\"{$eq->display_name}\" <{$eq->email}>"; } $message = new Mail_mime("\n"); $headers = array('Subject' => "Re: {$mailing->subject}", 'To' => $mailing->replyto_email, 'From' => $from, 'Reply-To' => empty($replyto) ? $eq->email : $replyto, 'Return-Path' => "do-not-reply@{$emailDomain}"); $message->setTxtBody($bodyTxt); $message->setHTMLBody($bodyHTML); $b = CRM_Utils_Mail::setMimeParams($message); $h = $message->headers($headers); } CRM_Mailing_BAO_Mailing::addMessageIdHeader($h, 'r', $eq->job_id, $queue_id, $eq->hash); $config = CRM_Core_Config::singleton(); $mailer = $config->getMailer(); if (is_object($mailer)) { $errorScope = CRM_Core_TemporaryErrorScope::ignoreException(); $mailer->send($mailing->replyto_email, $h, $b); unset($errorScope); } }
/** * Send a reponse email informing the contact of the groups to which he/she * has been resubscribed. * * @param string $queue_id The queue event ID * @param array $groups List of group IDs * @param bool $is_domain Is this domain-level? * @param int $job The job ID * @return void * @access public * @static */ public static function send_resub_response($queue_id, $groups, $is_domain = false, $job) { // param is_domain is not supported as of now. $config = CRM_Core_Config::singleton(); $domain =& CRM_Core_BAO_Domain::getDomain(); $jobTable = CRM_Mailing_BAO_Job::getTableName(); $mailingTable = CRM_Mailing_DAO_Mailing::getTableName(); $contacts = CRM_Contact_DAO_Contact::getTableName(); $email = CRM_Core_DAO_Email::getTableName(); $queue = CRM_Mailing_Event_BAO_Queue::getTableName(); //get the default domain email address. list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail(); $dao = new CRM_Mailing_BAO_Mailing(); $dao->query(" SELECT * FROM {$mailingTable} \n INNER JOIN {$jobTable} ON\n {$jobTable}.mailing_id = {$mailingTable}.id \n WHERE {$jobTable}.id = {$job}"); $dao->fetch(); $component = new CRM_Mailing_BAO_Component(); $component->id = $dao->resubscribe_id; $component->find(true); $html = $component->body_html; if ($component->body_text) { $text = $component->body_text; } else { $text = CRM_Utils_String::htmlToText($component->body_html); } $eq = new CRM_Core_DAO(); $eq->query("SELECT {$contacts}.preferred_mail_format as format,\n {$contacts}.id as contact_id,\n {$email}.email as email,\n {$queue}.hash as hash\n FROM {$contacts}\n INNER JOIN {$queue} ON {$queue}.contact_id = {$contacts}.id\n INNER JOIN {$email} ON {$queue}.email_id = {$email}.id\n WHERE {$queue}.id = " . CRM_Utils_Type::escape($queue_id, 'Integer')); $eq->fetch(); foreach ($groups as $key => $value) { if (!$value) { unset($groups[$key]); } } $message = new Mail_mime("\n"); list($addresses, $urls) = CRM_Mailing_BAO_Mailing::getVerpAndUrls($job, $queue_id, $eq->hash, $eq->email); $bao = new CRM_Mailing_BAO_Mailing(); $bao->body_text = $text; $bao->body_html = $html; $tokens = $bao->getTokens(); require_once 'CRM/Utils/Token.php'; if ($eq->format == 'HTML' || $eq->format == 'Both') { $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, true, $tokens['html']); $html = CRM_Utils_Token::replaceResubscribeTokens($html, $domain, $groups, true, $eq->contact_id, $eq->hash); $html = CRM_Utils_Token::replaceActionTokens($html, $addresses, $urls, true, $tokens['html']); $html = CRM_Utils_Token::replaceMailingTokens($html, $dao, null, $tokens['html']); $message->setHTMLBody($html); } if (!$html || $eq->format == 'Text' || $eq->format == 'Both') { $text = CRM_Utils_Token::replaceDomainTokens($html, $domain, true, $tokens['text']); $text = CRM_Utils_Token::replaceResubscribeTokens($text, $domain, $groups, false, $eq->contact_id, $eq->hash); $text = CRM_Utils_Token::replaceActionTokens($text, $addresses, $urls, false, $tokens['text']); $text = CRM_Utils_Token::replaceMailingTokens($text, $dao, null, $tokens['text']); $message->setTxtBody($text); } require_once 'CRM/Core/BAO/MailSettings.php'; $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain(); $headers = array('Subject' => $component->subject, 'From' => "\"{$domainEmailName}\" <do-not-reply@{$emailDomain}>", 'To' => $eq->email, 'Reply-To' => "do-not-reply@{$emailDomain}", 'Return-Path' => "do-not-reply@{$emailDomain}"); $b =& CRM_Utils_Mail::setMimeParams($message); $h =& $message->headers($headers); $mailer =& $config->getMailer(); PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array('CRM_Core_Error', 'nullHandler')); if (is_object($mailer)) { $mailer->send($eq->email, $h, $b); CRM_Core_Error::setCallback(); } }
</table> ', $_LABELS['par30']); if ($bAlertFlag) { $subject = sprintf('Accion inmediata - PAR 30 Report: %s', $_CONF['client_name']); } else { $subject = sprintf('Normal - PAR 30 Report: %s', $_CONF['client_name']); } // finishing message $subject = strip_tags($subject); $message = $subject; $attachment = $_html . '</body></html>'; $recipients = explode(';', $_CONF['par30rpt_emailto']); // Additional headers $headers["From"] = 'cgomez <*****@*****.**>'; // $headers["To"] = '*****@*****.**'; $headers["Subject"] = $subject; $crlf = "\n"; $mime = new Mail_mime($crlf); $mime->setTxtBody($message); $mime->setHTMLBody($attachment); //do not ever try to call these lines in reverse order $body = $mime->get(); $hdr = $mime->headers($headers, true); $params["username"] = '******'; $params["password"] = '******'; $params["auth"] = true; $mail =& Mail::factory('mail', $params); $res = $mail->send($recipients, $hdr, $body); if (PEAR::isError($res)) { echo 'error enviando el email'; }
/** * Confirm a pending subscription * * @param int $contact_id The id of the contact * @param int $subscribe_id The id of the subscription event * @param string $hash The hash * @return boolean True on success * @access public * @static */ public static function confirm($contact_id, $subscribe_id, $hash) { require_once 'CRM/Mailing/Event/BAO/Subscribe.php'; $se =& CRM_Mailing_Event_BAO_Subscribe::verify($contact_id, $subscribe_id, $hash); if (!$se) { return false; } require_once 'CRM/Core/Transaction.php'; $transaction = new CRM_Core_Transaction(); $ce = new CRM_Mailing_Event_BAO_Confirm(); $ce->event_subscribe_id = $se->id; $ce->time_stamp = date('YmdHis'); $ce->save(); require_once 'CRM/Contact/BAO/GroupContact.php'; CRM_Contact_BAO_GroupContact::updateGroupMembershipStatus($contact_id, $se->group_id, 'Email', $ce->id); $transaction->commit(); $config = CRM_Core_Config::singleton(); require_once 'CRM/Core/BAO/Domain.php'; $domain =& CRM_Core_BAO_Domain::getDomain(); list($domainEmailName, $_) = CRM_Core_BAO_Domain::getNameAndEmail(); require_once 'CRM/Contact/BAO/Contact/Location.php'; list($display_name, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($se->contact_id); require_once 'CRM/Contact/DAO/Group.php'; $group = new CRM_Contact_DAO_Group(); $group->id = $se->group_id; $group->find(true); require_once 'CRM/Mailing/BAO/Component.php'; $component = new CRM_Mailing_BAO_Component(); $component->is_default = 1; $component->is_active = 1; $component->component_type = 'Welcome'; $component->find(true); require_once 'CRM/Core/BAO/MailSettings.php'; $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain(); $headers = array('Subject' => $component->subject, 'From' => "\"{$domainEmailName}\" <do-not-reply@{$emailDomain}>", 'To' => $email, 'Reply-To' => "do-not-reply@{$emailDomain}", 'Return-Path' => "do-not-reply@{$emailDomain}"); $html = $component->body_html; if ($component->body_text) { $text = $component->body_text; } else { $text = CRM_Utils_String::htmlToText($component->body_html); } require_once 'CRM/Mailing/BAO/Mailing.php'; $bao = new CRM_Mailing_BAO_Mailing(); $bao->body_text = $text; $bao->body_html = $html; $tokens = $bao->getTokens(); require_once 'CRM/Utils/Token.php'; $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, true, $tokens['html']); $html = CRM_Utils_Token::replaceWelcomeTokens($html, $group->title, true); $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, false, $tokens['text']); $text = CRM_Utils_Token::replaceWelcomeTokens($text, $group->title, false); $message = new Mail_mime("\n"); $message->setHTMLBody($html); $message->setTxtBody($text); $b =& CRM_Utils_Mail::setMimeParams($message); $h =& $message->headers($headers); $mailer =& $config->getMailer(); require_once 'CRM/Mailing/BAO/Mailing.php'; PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array('CRM_Core_Error', 'nullHandler')); if (is_object($mailer)) { $mailer->send($email, $h, $b); CRM_Core_Error::setCallback(); } return $group->title; }
/** * Compose a message * * @param int $job_id ID of the Job associated with this message * @param int $event_queue_id ID of the EventQueue * @param string $hash Hash of the EventQueue * @param string $contactId ID of the Contact * @param string $email Destination address * @param string $recipient To: of the recipient * @param boolean $test Is this mailing a test? * @param boolean $isForward Is this mailing compose for forward? * @param string $fromEmail email address of who is forwardinf it. * @return object The mail object * @access public */ public function &compose($job_id, $event_queue_id, $hash, $contactId, $email, &$recipient, $test, $contactDetails, &$attachments, $isForward = false, $fromEmail = null) { require_once 'api/v2/Contact.php'; require_once 'CRM/Utils/Token.php'; require_once 'CRM/Activity/BAO/Activity.php'; $config = CRM_Core_Config::singleton(); $knownTokens = $this->getTokens(); if ($this->_domain == null) { require_once 'CRM/Core/BAO/Domain.php'; $this->_domain =& CRM_Core_BAO_Domain::getDomain(); } list($verp, $urls, $headers) = $this->getVerpAndUrlsAndHeaders($job_id, $event_queue_id, $hash, $email, $isForward); //set from email who is forwarding it and not original one. if ($fromEmail) { unset($headers['From']); $headers['From'] = "<{$fromEmail}>"; } if (defined('CIVICRM_MAIL_SMARTY')) { require_once 'CRM/Core/Smarty/resources/String.php'; civicrm_smarty_register_string_resource(); } if ($contactDetails) { $contact = $contactDetails; } else { $params = array('contact_id' => $contactId); $contact =& civicrm_contact_get($params); //CRM-4524 $contact = reset($contact); if (!$contact || is_a($contact, 'CRM_Core_Error')) { return null; } // also call the hook to get contact details require_once 'CRM/Utils/Hook.php'; CRM_Utils_Hook::tokenValues($contact, $contactId, $job_id); } $pTemplates = $this->getPreparedTemplates(); $pEmails = array(); foreach ($pTemplates as $type => $pTemplate) { $html = $type == 'html' ? true : false; $pEmails[$type] = array(); $pEmail =& $pEmails[$type]; $template =& $pTemplates[$type]['template']; $tokens =& $pTemplates[$type]['tokens']; $idx = 0; if (!empty($tokens)) { foreach ($tokens as $idx => $token) { $token_data = $this->getTokenData($token, $html, $contact, $verp, $urls, $event_queue_id); array_push($pEmail, $template[$idx]); array_push($pEmail, $token_data); } } else { array_push($pEmail, $template[$idx]); } if (isset($template[$idx + 1])) { array_push($pEmail, $template[$idx + 1]); } } $html = null; if (isset($pEmails['html']) && is_array($pEmails['html']) && count($pEmails['html'])) { $html =& $pEmails['html']; } $text = null; if (isset($pEmails['text']) && is_array($pEmails['text']) && count($pEmails['text'])) { $text =& $pEmails['text']; } // push the tracking url on to the html email if necessary if ($this->open_tracking && $html) { array_push($html, "\n" . '<img src="' . $config->userFrameworkResourceURL . "extern/open.php?q={$event_queue_id}\" width='1' height='1' alt='' border='0'>"); } $message = new Mail_mime("\n"); if (defined('CIVICRM_MAIL_SMARTY')) { $smarty = CRM_Core_Smarty::singleton(); // also add the contact tokens to the template $smarty->assign_by_ref('contact', $contact); } $mailParams = $headers; if ($text && ($test || $contact['preferred_mail_format'] == 'Text' || $contact['preferred_mail_format'] == 'Both' || $contact['preferred_mail_format'] == 'HTML' && !array_key_exists('html', $pEmails))) { $textBody = join('', $text); if (defined('CIVICRM_MAIL_SMARTY')) { $smarty->security = true; $textBody = $smarty->fetch("string:{$textBody}"); $smarty->security = false; } $mailParams['text'] = $textBody; } if ($html && ($test || ($contact['preferred_mail_format'] == 'HTML' || $contact['preferred_mail_format'] == 'Both'))) { $htmlBody = join('', $html); if (defined('CIVICRM_MAIL_SMARTY')) { $smarty->security = true; $htmlBody = $smarty->fetch("string:{$htmlBody}"); $smarty->security = false; } $mailParams['html'] = $htmlBody; } $mailParams['attachments'] = $attachments; $mailingSubject = CRM_Utils_Array::value('subject', $pEmails); if (is_array($mailingSubject)) { $mailingSubject = join('', $mailingSubject); } $mailParams['Subject'] = $mailingSubject; $mailParams['toName'] = $contact['display_name']; $mailParams['toEmail'] = $email; require_once 'CRM/Utils/Hook.php'; CRM_Utils_Hook::alterMailParams($mailParams); if (!empty($mailParams['text'])) { $message->setTxtBody($mailParams['text']); } if (!empty($mailParams['html'])) { $message->setHTMLBody($mailParams['html']); } if (!empty($mailParams['attachments'])) { foreach ($mailParams['attachments'] as $fileID => $attach) { $message->addAttachment($attach['fullPath'], $attach['mime_type'], $attach['cleanName']); } } $headers['To'] = "{$mailParams['toName']} <{$mailParams['toEmail']}>"; $headers['Precedence'] = 'bulk'; // Will test in the mail processor if the X-VERP is set in the bounced email. // (As an option to replace real VERP for those that can't set it up) $headers['X-CiviMail-Bounce'] = $verp['bounce']; //CRM-5058 //token replacement of subject $headers['Subject'] = $mailingSubject; CRM_Utils_Mail::setMimeParams($message); $headers = $message->headers($headers); //get formatted recipient $recipient = $headers['To']; // make sure we unset a lot of stuff unset($verp); unset($urls); unset($params); unset($contact); unset($ids); return $message; }
/** * Construct and send mime mail * * @param string $to * @param string $subject * @param string $message * @param array $header */ public function mail_mime(&$adresses, &$subject, &$message, &$header) { require_once 'Mail.php'; require_once 'Mail/mime.php'; $mime = new Mail_mime("\n"); $message = preg_replace('/(\\\r)?\\\n/', "\n", $message); $mime->setHTMLBody(nl2br($message)); $mime->setTxtBody($message); $body = $mime->get(array('head_charset' => 'UTF-8' , 'text_charset' => 'UTF-8', 'html_charset' => 'UTF-8')); $hdrs = $mime->headers(array_merge($header, array('Subject' => $subject))); $mail = Mail::factory('mail'); foreach ($adresses as $to) { $mail->send($to, $hdrs, $body); } }
/** * Ask a contact for subscription confirmation (opt-in) * * @param string $email The email address * @return void * @access public */ public function send_confirm_request($email) { $config = CRM_Core_Config::singleton(); require_once 'CRM/Core/BAO/Domain.php'; $domain =& CRM_Core_BAO_Domain::getDomain(); //get the default domain email address. list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail(); require_once 'CRM/Core/BAO/MailSettings.php'; $localpart = CRM_Core_BAO_MailSettings::defaultLocalpart(); $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain(); require_once 'CRM/Utils/Verp.php'; $confirm = implode($config->verpSeparator, array($localpart . 'c', $this->contact_id, $this->id, $this->hash)) . "@{$emailDomain}"; require_once 'CRM/Contact/BAO/Group.php'; $group = new CRM_Contact_BAO_Group(); $group->id = $this->group_id; $group->find(true); require_once 'CRM/Mailing/BAO/Component.php'; $component = new CRM_Mailing_BAO_Component(); $component->is_default = 1; $component->is_active = 1; $component->component_type = 'Subscribe'; $component->find(true); $headers = array('Subject' => $component->subject, 'From' => "\"{$domainEmailName}\" <{$domainEmailAddress}>", 'To' => $email, 'Reply-To' => $confirm, 'Return-Path' => "do-not-reply@{$emailDomain}"); $url = CRM_Utils_System::url('civicrm/mailing/confirm', "reset=1&cid={$this->contact_id}&sid={$this->id}&h={$this->hash}", true); $html = $component->body_html; if ($component->body_text) { $text = $component->body_text; } else { $text = CRM_Utils_String::htmlToText($component->body_html); } require_once 'CRM/Mailing/BAO/Mailing.php'; $bao = new CRM_Mailing_BAO_Mailing(); $bao->body_text = $text; $bao->body_html = $html; $tokens = $bao->getTokens(); require_once 'CRM/Utils/Token.php'; $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, true, $tokens['html']); $html = CRM_Utils_Token::replaceSubscribeTokens($html, $group->title, $url, true); $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, false, $tokens['text']); $text = CRM_Utils_Token::replaceSubscribeTokens($text, $group->title, $url, false); // render the & entities in text mode, so that the links work $text = str_replace('&', '&', $text); $message = new Mail_mime("\n"); $message->setHTMLBody($html); $message->setTxtBody($text); $b =& CRM_Utils_Mail::setMimeParams($message); $h =& $message->headers($headers); $mailer =& $config->getMailer(); require_once 'CRM/Mailing/BAO/Mailing.php'; PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array('CRM_Core_Error', 'nullHandler')); if (is_object($mailer)) { $mailer->send($email, $h, $b); CRM_Core_Error::setCallback(); } }
require_once 'Mail/mime.php'; $mimeparams['text_encoding'] = "8bit"; $mimeparams['text_charset'] = "UTF-8"; $mimeparams['html_charset'] = "UTF-8"; $hash = base64_encode(password_hash(time() . $form['firstname'] . $form['lastname'], PASSWORD_BCRYPT)); $mail_object =& Mail::factory('smtp', $mail_config); $mime_object = new Mail_mime("\n"); $form = $obfuscator->decode_form($_POST['__A'], $_POST); $smarty->assign('form', $form); $smarty->assign('url', 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['SCRIPT_NAME']) . '/confirm.php?id=' . $hash); $body_html = $smarty->fetch('email.tpl'); $headers['From'] = '*****@*****.**'; $headers['To'] = $form['email']; $headers['Subject'] = 'Dein Mitgliedschaftsantrag bei Freifunk Mainz e.V.'; $mime_object->setHTMLBody($body_html); $mime_object->setTxtBody(ltrim(rtrim(html_entity_decode(strip_tags($body_html))))); $body = $mime_object->get($mimeparams); $hdrs = $mime_object->headers($headers); SmartyValidate::disconnect(); $f_handle = fopen('./pending_members/' . $hash . ".csv", 'w'); fputs($f_handle, utf8_decode("Mitglieds_Nr;Personenart;Anrede;Titel;Nachname;Vorname;Adressierungszusatz;Strasse;Plz;Ort;Geburtsdatum;Geschlecht;BIC;IBAN;Bankleitzahl;Kontonummer;Mandat_Datum;Zahlungsart;Telefon_privat;Telefon_dienstlich;Email;Zahler;Eintritt;Beitragsart_1;Beitrag_1;Austritt;Kuendigung;pgpkeyid;nick;sonstiges;Sterbetag\n")); fputs($f_handle, utf8_decode(";" . ($form['beitrag'] == 100 ? "j" : "n") . ";;;" . $form['lastname'] . ";" . $form['firstname'] . ";" . $form['addr_extra'] . ";" . $form['street'] . ";" . $form['zip'] . ";" . $form['city'] . ";;;" . str_replace(' ', '', $form['bic']) . ";" . str_replace(' ', '', $form['iban']) . ";;;" . date("d.m.Y") . ";l;" . $form['phone'] . ";;" . $form['email'] . ";" . $form['account_owner'] . ";" . "01/" . $form['entry_date'] . ";" . ($form['beitrag'] == 100 ? "Test" : "Beitrag " . $form['beitrag'] . "€") . ";" . $form['beitrag'] . ";;;" . $form['pgpid'] . ";" . $form['nick'] . ";;\n")); fclose($f_handle); $mail_object->send($form['email'], $hdrs, $body); $message = "Deine Daten sind bei uns angekommen. Für den nächsten Schritt prüfe bitte deine Emails und klicke auf den darin enthaltenen Bestätigungslink."; $smarty->assign('message', $message); $smarty->display('success.tpl'); } else { // error, redraw the form //print_r ($_POST); $form = $obfuscator->decode_form($_POST['__A'], $_POST);
function sendmail_sendmsg($account_no, $subject, $rcpt, $fromname, $msg, $debug_flag) { // account list array, from config.php global $arrAccountsSmtp; // $account_noの範囲チェック if ($account_no <= 0 || $account_no > count($arrAccountsSmtp)) { printf("<p>アカウント指定Noが範囲外です<br/>account=%d</p>\n", $account_no); return; } // メールアカウント情報(サーバ名、ユーザ名、パスワード等)を得る $arr_mail_account = GetMailAccount($arrAccountsSmtp[$account_no - 1][1], 'smtp'); if (!isset($arr_mail_account['server']) || !isset($arr_mail_account['user']) || !isset($arr_mail_account['password']) || strcmp($arr_mail_account['protocol'], 'smtp')) { print "<p>メールアカウント管理エラー(server/user/password値が得られないか、protocolがsmtpでない)</p>\n"; return; } // 送信者のアドレス(user@example.com)の文字列を作成する $from = ''; if (strpos($arr_mail_account['user'], '@') === false) { $from = $arr_mail_account['user'] . '@' . $arr_mail_account['server']; } else { $from = $arr_mail_account['user']; } // mime形式のヘッダ、メール本文 $mime = new Mail_mime(); // mime構造規定の配列を初期化(エンコード別の処理が必要ない場合は値も初期化時に設定) $mime_param = array(); $mime_header = array('User-Agent' => 'PHP Pear Net_mime', 'To' => $rcpt); // 送信者名(From),タイトル(Subject)をエンコードする $internal_charset_save = mb_internal_encoding(); // 現在の内部エンコードを一旦保存 switch ($_POST['subj_transfer']) { case 'mime-base64': $mime_param['head_encoding'] = 'base64'; mb_internal_encoding($_POST['msg_encode']); // 送信者名(From) $mime_header['From'] = mb_encode_mimeheader(mb_convert_encoding($fromname, $_POST['msg_encode'], 'UTF-8'), $_POST['msg_encode'], 'B') . "<" . $from . ">"; // タイトル(Subject) $mime_header['Subject'] = mb_encode_mimeheader(mb_convert_encoding($subject, $_POST['msg_encode'], 'UTF-8'), $_POST['msg_encode'], 'B'); break; case 'mime-quoted-printable': $mime_param['head_encoding'] = 'quoted-printable'; mb_internal_encoding($_POST['msg_encode']); // 送信者名(From) $mime_header['From'] = mb_encode_mimeheader(mb_convert_encoding($fromname, $_POST['msg_encode'], 'UTF-8'), $_POST['msg_encode'], 'Q') . "<" . $from . ">"; // タイトル(Subject) $mime_header['Subject'] = mb_encode_mimeheader(mb_convert_encoding($subject, $_POST['msg_encode'], 'UTF-8'), $_POST['msg_encode'], 'Q'); break; case 'plain': $mime_param['head_encoding'] = '7bit'; $mime_header['From'] = mb_convert_encoding($fromname, $_POST['msg_encode'], 'UTF-8') . "<" . $from . ">"; $mime_header['Subject'] = mb_convert_encoding($subject, $_POST['msg_encode'], 'UTF-8'); break; default: printf("<p>送信者名(From)とタイトル(Subject)転送方式の指定が範囲外 (value=%s)</p>", htmlspecialchars($_POST['subj_transfer'])); return; } mb_internal_encoding($internal_charset_save); // 本文のエンコード $str_temp = ''; switch ($_POST['msg_encode']) { case 'ISO-2022-JP': $mime_param['head_charset'] = 'iso-2022-jp'; $mime_param['text_charset'] = 'iso-2022-jp'; $str_temp = mb_convert_encoding($msg . "\n\n", 'ISO-2022-JP', 'UTF-8'); break; case 'UTF-8': $mime_param['head_charset'] = 'utf8'; $mime_param['text_charset'] = 'utf8'; //$str_temp = mb_convert_encoding($msg . "\n\n", 'UTF-8', 'UTF-8'); $str_temp = $msg; break; case 'SJIS': $mime_param['head_charset'] = 'shift-jis'; $mime_param['text_charset'] = 'shift-jis'; $str_temp = mb_convert_encoding($msg . "\n\n", 'SJIS', 'UTF-8'); break; case 'EUC-JP': $mime_param['head_charset'] = 'euc-jp'; $mime_param['text_charset'] = 'euc-jp'; $str_temp = mb_convert_encoding($msg . "\n\n", 'EUC-JP', 'UTF-8'); break; default: printf("<p>本文エンコード形式の指定が範囲外 (value=%s)</p>", htmlspecialchars($_POST['msg_encode'])); return; } // 本文の転送エンコードは、$mime_param['text_encoding']を設定することで自動的に行われる /* switch($_POST['msg_transfer']) { case '7bit' : break; case '8bit' : break; case 'quoted-printable' : quoted_printable_encode_self($str_temp, $_POST['msg_transfer']); break; case 'base64' : $str_temp = base64_encode($str_temp); break; case 'binay' : break; default : printf("<p>本文転送形式の指定が範囲外 (value=%s)</p>", htmlspecialchars($_POST['msg_transfer'])); return; } */ $mime->setTxtBody($str_temp); $mime_param['text_encoding'] = $_POST['msg_transfer']; /* Mail_Mime オブジェクトを構築 */ $smtp_body = $mime->get($mime_param); $smtp_header = $mime->headers($mime_header); $smtp_auth = array('host' => $arr_mail_account['server'], 'port' => $arr_mail_account['port'], 'auth' => true, 'username' => $arr_mail_account['user'], 'password' => $arr_mail_account['password'], 'debug' => $debug_flag ? true : false); /* 新しいMailオブジェクトを作成 */ $mail =& Mail::factory('smtp', $smtp_auth); /* メールの送信 */ if (PEAR::isError($e = $mail->send($rcpt, $smtp_header, $smtp_body))) { printf("<p>送信エラー発生<br/>エラーメッセージ:%s</p>\n", $e->getMessage()); } else { print "<p>送信完了</p>\n<p>詳細情報<br/>===========</p>\n<pre>\n"; print htmlspecialchars(print_r($smtp_header, true)); printf("</pre>\n<p>本文 : %d バイト</p>\n", strlen($smtp_body)); } }
//------------------------------------------------------------------------------ EOT; unset($tmp1); unset($tmp2); unset($tmp3); //------------------------------------------------------------------------------ $mime = new Mail_mime(); // method 'addTo' exists in Mail_Mime-1.8.0+ if (method_exists('Mail_mime', 'addTo')) { $mime->addTo($to); } $mime->setFrom($from); $mime->setSubject($subject); //$mime->addCc($cc); $mime->setTxtBody($body_text); //$mime->setHTMLBody($body_html); //------------------------------------------------------------------------------ // get() must be called before headers() $body = $mime->get(); // headers() must be called after get() $headers = $mime->txtHeaders(); //$headers = $mime->headers(); //------------------------------------------------------------------------------ // send the problem if (!mail($to, $subject, $body, $headers)) { throw new Exception('"mail" function failed.'); } $tmp1 = $e->getMessage(); print <<<EOT <p>There was an error. Your results were <b>not</b> submitted.</p>
/** * Wrapper function to send mail in CiviCRM. Hooks are called from this function. The input parameter * is an associateive array which holds the values of field needed to send an email. These are: * * from : complete from envelope * toName : name of person to send email * toEmail : email address to send to * cc : email addresses to cc * bcc : email addresses to bcc * subject : subject of the email * text : text of the message * html : html version of the message * replyTo : reply-to header in the email * attachments: an associative array of * fullPath : complete pathname to the file * mime_type: mime type of the attachment * cleanName: the user friendly name of the attachmment * * @param array $params (by reference) * * @access public * @return boolean true if a mail was sent, else false */ static function send(&$params) { require_once 'CRM/Core/BAO/MailSettings.php'; $returnPath = CRM_Core_BAO_MailSettings::defaultReturnPath(); $from = CRM_Utils_Array::value('from', $params); if (!$returnPath) { $returnPath = self::pluckEmailFromHeader($from); } $params['returnPath'] = $returnPath; // first call the mail alter hook require_once 'CRM/Utils/Hook.php'; CRM_Utils_Hook::alterMailParams($params); // check if any module has aborted mail sending if (CRM_Utils_Array::value('abortMailSend', $params) || !CRM_Utils_Array::value('toEmail', $params)) { return false; } $textMessage = CRM_Utils_Array::value('text', $params); $htmlMessage = CRM_Utils_Array::value('html', $params); $attachments = CRM_Utils_Array::value('attachments', $params); // CRM-6224 if (trim(CRM_Utils_String::htmlToText($htmlMessage)) == '') { $htmlMessage = false; } $headers = array(); $headers['From'] = $params['from']; $headers['To'] = "{$params['toName']} <{$params['toEmail']}>"; $headers['Cc'] = CRM_Utils_Array::value('cc', $params); $headers['Bcc'] = CRM_Utils_Array::value('bcc', $params); $headers['Subject'] = CRM_Utils_Array::value('subject', $params); $headers['Content-Type'] = $htmlMessage ? 'multipart/mixed; charset=utf-8' : 'text/plain; charset=utf-8'; $headers['Content-Disposition'] = 'inline'; $headers['Content-Transfer-Encoding'] = '8bit'; $headers['Return-Path'] = CRM_Utils_Array::value('returnPath', $params); $headers['Reply-To'] = CRM_Utils_Array::value('replyTo', $params, $from); $headers['Date'] = date('r'); if (CRM_Utils_Array::value('autoSubmitted', $params)) { $headers['Auto-Submitted'] = "Auto-Generated"; } //make sure we has to have space, CRM-6977 foreach (array('From', 'To', 'Cc', 'Bcc', 'Reply-To', 'Return-Path') as $fld) { $headers[$fld] = str_replace('"<', '" <', $headers[$fld]); } // quote FROM, if comma is detected AND is not already quoted. CRM-7053 if (strpos($headers['From'], ',') !== false) { $from = explode(' <', $headers['From']); if (substr($from[0], 0, 1) != '"' || substr($from[0], -1, 1) != '"') { $from[0] = str_replace('"', '\\"', $from[0]); $headers['From'] = "\"{$from[0]}\" <{$from[1]}"; } } require_once 'Mail/mime.php'; $msg = new Mail_mime("\n"); if ($textMessage) { $msg->setTxtBody($textMessage); } if ($htmlMessage) { $msg->setHTMLBody($htmlMessage); } if (!empty($attachments)) { foreach ($attachments as $fileID => $attach) { $msg->addAttachment($attach['fullPath'], $attach['mime_type'], $attach['cleanName']); } } $message =& self::setMimeParams($msg); $headers =& $msg->headers($headers); $to = array($params['toEmail']); //get emails from headers, since these are //combination of name and email addresses. if (CRM_Utils_Array::value('Cc', $headers)) { $to[] = CRM_Utils_Array::value('Cc', $headers); } if (CRM_Utils_Array::value('Bcc', $headers)) { $to[] = CRM_Utils_Array::value('Bcc', $headers); unset($headers['Bcc']); } $result = null; $mailer =& CRM_Core_Config::getMailer(); CRM_Core_Error::ignoreException(); if (is_object($mailer)) { $result = $mailer->send($to, $headers, $message); CRM_Core_Error::setCallback(); if (is_a($result, 'PEAR_Error')) { $message = self::errorMessage($mailer, $result); CRM_Core_Session::setStatus($message, false); return false; } return true; } return false; }