public function testHookAlterMailer() { $test = $this; $mockMailer = new CRM_Utils_FakeObject(array('send' => function ($recipients, $headers, $body) use($test) { $test->calls['send']++; $test->assertEquals(array('*****@*****.**'), $recipients); $test->assertEquals('Subject Example', $headers['Subject']); })); CRM_Utils_Hook::singleton()->setHook('civicrm_alterMailer', function (&$mailer, $driver, $params) use($test, $mockMailer) { $test->calls['civicrm_alterMailer']++; $test->assertTrue(is_string($driver) && !empty($driver)); $test->assertTrue(is_array($params)); $test->assertTrue(is_callable(array($mailer, 'send'))); $mailer = $mockMailer; }); $params = array(); $params['groupName'] = 'CRM_Core_Config_MailerTest'; $params['from'] = 'From Example <*****@*****.**>'; $params['toName'] = 'To Example'; $params['toEmail'] = '*****@*****.**'; $params['subject'] = 'Subject Example'; $params['text'] = 'Example text'; $params['html'] = '<p>Example HTML</p>'; CRM_Utils_Mail::send($params); $this->assertEquals(1, $this->calls['civicrm_alterMailer']); $this->assertEquals(1, $this->calls['send']); // once more, just to make sure the hooks are called right #times CRM_Utils_Mail::send($params); CRM_Utils_Mail::send($params); $this->assertEquals(1, $this->calls['civicrm_alterMailer']); $this->assertEquals(3, $this->calls['send']); }
static function sendMailToParents($childID, $subjectTPL, $messageTPL, $templateVars, $additionalCC = null) { require_once 'SFS/Utils/Relationship.php'; $parentInfo = array(); SFS_Utils_Relationship::getParents($childID, $parentInfo, false); // make sure we unset the older parents for ($count = 1; $count < 5; $count++) { $templateVars["parent_{$count}_Name"] = null; } $count = 1; $toDisplayName = $toEmail = $cc = null; foreach ($parentInfo as $parent) { $templateVars["parent_{$count}_Name"] = $parent['name']; if ($parent['email']) { if (!$toEmail) { $toDisplayName = $parent['name']; $toEmail = $parent['email']; } else { if (!empty($cc)) { $cc .= ", "; } $cc .= $parent['email']; } } $count++; } if ($additionalCC) { if (!empty($cc)) { $cc .= ", "; } $cc .= $additionalCC; } // return if we dont have a toEmail if (!$toEmail) { return; } require_once 'SFS/Utils/Query.php'; list($templateVars['childName'], $templateVars['childEmail']) = SFS_Utils_Query::getNameAndEmail($childID); $template = CRM_Core_Smarty::singleton(); $template->assign($templateVars); require_once 'CRM/Utils/Mail.php'; require_once 'CRM/Utils/String.php'; $params = array('from' => self::SFS_FROM_EMAIL, 'toName' => $toDisplayName, 'toEmail' => $toEmail, 'subject' => $template->fetch($subjectTPL), 'text' => $template->fetch($messageTPL), 'cc' => $cc, 'bcc' => self::SFS_BCC_EMAIL); CRM_Utils_Mail::send($params); }
/** * Basic send. */ public function testSend() { $contact_params_1 = array('first_name' => substr(sha1(rand()), 0, 7), 'last_name' => 'Anderson', 'email' => substr(sha1(rand()), 0, 7) . '@example.org', 'contact_type' => 'Individual'); $contact_id_1 = $this->individualCreate($contact_params_1); $contact_params_2 = array('first_name' => substr(sha1(rand()), 0, 7), 'last_name' => 'Xylophone', 'email' => substr(sha1(rand()), 0, 7) . '@example.org', 'contact_type' => 'Individual'); $contact_id_2 = $this->individualCreate($contact_params_2); $subject = 'Test spool'; $params = array('from' => CRM_Utils_Mail::formatRFC822Email($contact_params_1['first_name'] . " " . $contact_params_1['last_name'], $contact_params_1['email']), 'toName' => $contact_params_2['first_name'] . " " . $contact_params_2['last_name'], 'toEmail' => $contact_params_2['email'], 'subject' => $subject, 'text' => self::$bodytext, 'html' => "<p>\n" . self::$bodytext . '</p>'); CRM_Utils_Mail::send($params); $mail = $this->_mut->getMostRecentEmail('raw'); $this->assertContains("Subject: {$subject}", $mail); $this->assertContains(self::$bodytext, $mail); $mail = $this->_mut->getMostRecentEmail('ezc'); $this->assertEquals($subject, $mail->subject); $this->assertContains($contact_params_1['email'], $mail->from->email, 'From address incorrect.'); $this->assertContains($contact_params_2['email'], $mail->to[0]->email, 'Recipient incorrect.'); $context = new ezcMailPartWalkContext(array(get_class($this), 'mailWalkCallback')); $mail->walkParts($context, $mail); }
/** * Take the signature form and send an email to the recipient. * * @param CRM_Campaign_Form_Petition_Signature $form * The petition form. */ public function processSignature($form) { // Get the message. $messageField = $this->findMessageField(); if ($messageField === FALSE) { return; } $message = empty($form->_submitValues[$messageField]) ? $this->petitionEmailVal[$this->fields['Default_Message']] : $form->_submitValues[$messageField]; // If message is left empty and no default message, don't send anything. if (empty($message)) { return; } // Setup email message: $mailParams = array('groupName' => 'Activity Email Sender', 'from' => $this->getSenderLine($form->_contactId), 'toName' => $this->petitionEmailVal[$this->fields['Recipient_Name']], 'toEmail' => $this->petitionEmailVal[$this->fields['Recipient_Email']], 'subject' => $this->petitionEmailVal[$this->fields['Subject']], 'text' => $message); if (!CRM_Utils_Mail::send($mailParams)) { CRM_Core_Session::setStatus(ts('Error sending message to %1', array('domain' => 'com.aghstrategies.petitionemail', 1 => $mailParams['toName']))); } else { CRM_Core_Session::setStatus(ts('Message sent successfully to %1', array('domain' => 'com.aghstrategies.petitionemail', 1 => $mailParams['toName']))); } parent::processSignature($form); }
function civicrm_api3_speakcivi_sendconfirm($params) { $query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format FROM civicrm_msg_template mt WHERE mt.id = %1 AND mt.is_default = 1'; $sqlParams = array(1 => array($params['messageTemplateID'], 'String')); $dao = CRM_Core_DAO::executeQuery($query, $sqlParams); $dao->fetch(); if (!$dao->N) { CRM_Core_Error::fatal(ts('No such message template: id=%1.', array(1 => $params['messageTemplateID']))); } $confirmation_block_html = ''; $confirmation_block_text = ''; $language = $params['language']; if ($params['confirmation_block']) { $cgid = $params['contact_id']; $aid = $params['activity_id']; $campaign_id = $params['campaign_id']; $hash = sha1(CIVICRM_SITE_KEY . $cgid); $url_confirm_and_keep = CRM_Utils_System::url('civicrm/speakcivi/confirm', "id={$cgid}&aid={$aid}&cid={$campaign_id}&hash={$hash}&utm_source=civicrm&utm_medium=email&utm_campaign=speakout_confirm", true); $url_confirm_and_not_receive = CRM_Utils_System::url('civicrm/speakcivi/optout', "id={$cgid}&aid={$aid}&cid={$campaign_id}&hash={$hash}&utm_source=civicrm&utm_medium=email&utm_campaign=speakout_optout", true); $template = CRM_Core_Smarty::singleton(); $template->assign('url_confirm_and_keep', $url_confirm_and_keep); $template->assign('url_confirm_and_not_receive', $url_confirm_and_not_receive); $confirmation_block_html = $template->fetch('../templates/CRM/Speakcivi/Page/ConfirmationBlock.' . $language . '.html.tpl'); $confirmation_block_text = $template->fetch('../templates/CRM/Speakcivi/Page/ConfirmationBlock.' . $language . '.text.tpl'); $params['subject'] = getSubjectConfirm($language); } else { $params['subject'] = getSubjectImpact($language); } $params['html'] = str_replace("#CONFIRMATION_BLOCK", $confirmation_block_html, $dao->html); $params['text'] = str_replace("#CONFIRMATION_BLOCK", $confirmation_block_text, $dao->text); $params['format'] = $dao->format; $dao->free(); $sent = CRM_Utils_Mail::send($params); return civicrm_api3_create_success($sent, $params); }
/** * Send an email from the specified template based on an array of params. * * @param array $params * A string-keyed array of function params, see function body for details. * * @return array * Array of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates */ public static function sendTemplate($params) { $defaults = array('groupName' => NULL, 'valueName' => NULL, 'messageTemplateID' => NULL, 'contactId' => NULL, 'tplParams' => array(), 'from' => NULL, 'toName' => NULL, 'toEmail' => NULL, 'cc' => NULL, 'bcc' => NULL, 'replyTo' => NULL, 'attachments' => NULL, 'isTest' => FALSE, 'PDFFilename' => NULL); $params = array_merge($defaults, $params); CRM_Utils_Hook::alterMailParams($params, 'messageTemplate'); if ((!$params['groupName'] || !$params['valueName']) && !$params['messageTemplateID']) { CRM_Core_Error::fatal(ts("Message template's option group and/or option value or ID missing.")); } if ($params['messageTemplateID']) { // fetch the three elements from the db based on id $query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format FROM civicrm_msg_template mt WHERE mt.id = %1 AND mt.is_default = 1'; $sqlParams = array(1 => array($params['messageTemplateID'], 'String')); } else { // fetch the three elements from the db based on option_group and option_value names $query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format FROM civicrm_msg_template mt JOIN civicrm_option_value ov ON workflow_id = ov.id JOIN civicrm_option_group og ON ov.option_group_id = og.id WHERE og.name = %1 AND ov.name = %2 AND mt.is_default = 1'; $sqlParams = array(1 => array($params['groupName'], 'String'), 2 => array($params['valueName'], 'String')); } $dao = CRM_Core_DAO::executeQuery($query, $sqlParams); $dao->fetch(); if (!$dao->N) { if ($params['messageTemplateID']) { CRM_Core_Error::fatal(ts('No such message template: id=%1.', array(1 => $params['messageTemplateID']))); } else { CRM_Core_Error::fatal(ts('No such message template: option group %1, option value %2.', array(1 => $params['groupName'], 2 => $params['valueName']))); } } $mailContent = array('subject' => $dao->subject, 'text' => $dao->text, 'html' => $dao->html, 'format' => $dao->format); $dao->free(); CRM_Utils_Hook::alterMailContent($mailContent); // add the test banner (if requested) if ($params['isTest']) { $query = "SELECT msg_subject subject, msg_text text, msg_html html\n FROM civicrm_msg_template mt\n JOIN civicrm_option_value ov ON workflow_id = ov.id\n JOIN civicrm_option_group og ON ov.option_group_id = og.id\n WHERE og.name = 'msg_tpl_workflow_meta' AND ov.name = 'test_preview' AND mt.is_default = 1"; $testDao = CRM_Core_DAO::executeQuery($query); $testDao->fetch(); $mailContent['subject'] = $testDao->subject . $mailContent['subject']; $mailContent['text'] = $testDao->text . $mailContent['text']; $mailContent['html'] = preg_replace('/<body(.*)$/im', "<body\\1\n{$testDao->html}", $mailContent['html']); $testDao->free(); } // replace tokens in the three elements (in subject as if it was the text body) $domain = CRM_Core_BAO_Domain::getDomain(); $hookTokens = array(); $mailing = new CRM_Mailing_BAO_Mailing(); $mailing->subject = $mailContent['subject']; $mailing->body_text = $mailContent['text']; $mailing->body_html = $mailContent['html']; $tokens = $mailing->getTokens(); CRM_Utils_Hook::tokens($hookTokens); $categories = array_keys($hookTokens); $contactID = CRM_Utils_Array::value('contactId', $params); if ($contactID) { $contactParams = array('contact_id' => $contactID); $returnProperties = array(); if (isset($tokens['subject']['contact'])) { foreach ($tokens['subject']['contact'] as $name) { $returnProperties[$name] = 1; } } if (isset($tokens['text']['contact'])) { foreach ($tokens['text']['contact'] as $name) { $returnProperties[$name] = 1; } } if (isset($tokens['html']['contact'])) { foreach ($tokens['html']['contact'] as $name) { $returnProperties[$name] = 1; } } // @todo CRM-17253 don't resolve contact details if there are no tokens // effectively comment out this next (performance-expensive) line // but unfortunately testing is a bit think on the ground to that needs to // be added. list($contact) = CRM_Utils_Token::getTokenDetails($contactParams, $returnProperties, FALSE, FALSE, NULL, CRM_Utils_Token::flattenTokens($tokens), 'CRM_Core_BAO_MessageTemplate'); $contact = $contact[$contactID]; } $mailContent['subject'] = CRM_Utils_Token::replaceDomainTokens($mailContent['subject'], $domain, FALSE, $tokens['text'], TRUE); $mailContent['text'] = CRM_Utils_Token::replaceDomainTokens($mailContent['text'], $domain, FALSE, $tokens['text'], TRUE); $mailContent['html'] = CRM_Utils_Token::replaceDomainTokens($mailContent['html'], $domain, TRUE, $tokens['html'], TRUE); if ($contactID) { $mailContent['subject'] = CRM_Utils_Token::replaceContactTokens($mailContent['subject'], $contact, FALSE, $tokens['text'], FALSE, TRUE); $mailContent['text'] = CRM_Utils_Token::replaceContactTokens($mailContent['text'], $contact, FALSE, $tokens['text'], FALSE, TRUE); $mailContent['html'] = CRM_Utils_Token::replaceContactTokens($mailContent['html'], $contact, FALSE, $tokens['html'], FALSE, TRUE); $contactArray = array($contactID => $contact); CRM_Utils_Hook::tokenValues($contactArray, array($contactID), NULL, CRM_Utils_Token::flattenTokens($tokens), 'CRM_Core_BAO_MessageTemplate'); $contact = $contactArray[$contactID]; $mailContent['subject'] = CRM_Utils_Token::replaceHookTokens($mailContent['subject'], $contact, $categories, TRUE); $mailContent['text'] = CRM_Utils_Token::replaceHookTokens($mailContent['text'], $contact, $categories, TRUE); $mailContent['html'] = CRM_Utils_Token::replaceHookTokens($mailContent['html'], $contact, $categories, TRUE); } // strip whitespace from ends and turn into a single line $mailContent['subject'] = "{strip}{$mailContent['subject']}{/strip}"; // parse the three elements with Smarty $smarty = CRM_Core_Smarty::singleton(); foreach ($params['tplParams'] as $name => $value) { $smarty->assign($name, $value); } foreach (array('subject', 'text', 'html') as $elem) { $mailContent[$elem] = $smarty->fetch("string:{$mailContent[$elem]}"); } // send the template, honouring the target user’s preferences (if any) $sent = FALSE; // create the params array $params['subject'] = $mailContent['subject']; $params['text'] = $mailContent['text']; $params['html'] = $mailContent['html']; if ($params['toEmail']) { $contactParams = array(array('email', 'LIKE', $params['toEmail'], 0, 1)); list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($contactParams); $prefs = array_pop($contact); if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'HTML') { $params['text'] = NULL; } if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'Text') { $params['html'] = NULL; } $config = CRM_Core_Config::singleton(); if (isset($params['isEmailPdf']) && $params['isEmailPdf'] == 1) { $pdfHtml = CRM_Contribute_BAO_ContributionPage::addInvoicePdfToEmail($params['contributionId'], $params['contactId']); if (empty($params['attachments'])) { $params['attachments'] = array(); } $params['attachments'][] = CRM_Utils_Mail::appendPDF('Invoice.pdf', $pdfHtml, $mailContent['format']); } $pdf_filename = ''; if ($config->doNotAttachPDFReceipt && $params['PDFFilename'] && $params['html']) { if (empty($params['attachments'])) { $params['attachments'] = array(); } $params['attachments'][] = CRM_Utils_Mail::appendPDF($params['PDFFilename'], $params['html'], $mailContent['format']); if (isset($params['tplParams']['email_comment'])) { $params['html'] = $params['tplParams']['email_comment']; $params['text'] = strip_tags($params['tplParams']['email_comment']); } } $sent = CRM_Utils_Mail::send($params); if ($pdf_filename) { unlink($pdf_filename); } } return array($sent, $mailContent['subject'], $mailContent['text'], $mailContent['html']); }
static function mailReport($fileContent, $instanceID = null, $outputMode = 'html') { if (!$instanceID) { return false; } $url = CRM_Utils_System::url("civicrm/report/instance/{$instanceID}", "reset=1", true); $url = "Report Url: {$url} "; $fileContent = $url . $fileContent; require_once 'CRM/Core/BAO/Domain.php'; list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail(); $params = array('id' => $instanceID); $instanceInfo = array(); CRM_Core_DAO::commonRetrieve('CRM_Report_DAO_Instance', $params, $instanceInfo); $from = '"' . $domainEmailName . '" <' . $domainEmailAddress . '>'; $toDisplayName = ""; //$domainEmailName; $toEmail = CRM_Utils_Array::value('email_to', $instanceInfo); $ccEmail = CRM_Utils_Array::value('email_cc', $instanceInfo); $subject = CRM_Utils_Array::value('email_subject', $instanceInfo); $attachments = CRM_Utils_Array::value('attachments', $instanceInfo); require_once 'Mail/mime.php'; require_once "CRM/Utils/Mail.php"; return CRM_Utils_Mail::send($from, $toDisplayName, $toEmail, $subject, '', $ccEmail, null, null, $fileContent, $attachments); }
function sendInvoiceMail($email, $displayName, $fromEmail, $fileName, $filePathName, $obj, $contactID, $contribution) { ## getting contact detail require_once 'api/v2/Contact.php'; $contactParams = array('id' => $contactID); $contact =& civicrm_contact_get($contactParams); ## Check the contribution type to work out which email template we should be using //print_r($contribution); exit; $contributionTypeId = $contribution->contribution_type_id; if ($contributionTypeId == '2') { ## Contribution Type - Membership $emailTemplateName = 'Membership Invoice'; $params['bcc'] = '*****@*****.**'; } if ($contributionTypeId == '4') { ## Contribution Type - Events $emailTemplateName = 'Participant Invoice'; $params['bcc'] = '*****@*****.**'; } ## getting invoice mail template $query = "SELECT * FROM civicrm_msg_template WHERE msg_title = '{$emailTemplateName}' AND is_active=1"; $dao = CRM_Core_DAO::executeQuery($query); if (!$dao->fetch()) { print "Not able to get Email Template"; exit; } $text = $dao->msg_text; $html = $dao->msg_html; $subject = $dao->msg_subject; ################################################### require_once "CRM/Mailing/BAO/Mailing.php"; $mailing = new CRM_Mailing_BAO_Mailing(); $mailing->body_text = $text; $mailing->body_html = $html; $tokens = $mailing->getTokens(); require_once "CRM/Utils/Token.php"; $subject = CRM_Utils_Token::replaceDomainTokens($subject, $domain, true, $tokens['text']); $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, true, $tokens['text']); $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, true, $tokens['html']); if ($contactID) { $subject = CRM_Utils_Token::replaceContactTokens($subject, $contact, false, $tokens['text']); $text = CRM_Utils_Token::replaceContactTokens($text, $contact, false, $tokens['text']); $html = CRM_Utils_Token::replaceContactTokens($html, $contact, false, $tokens['html']); } // parse the three elements with Smarty require_once 'CRM/Core/Smarty/resources/String.php'; civicrm_smarty_register_string_resource(); $smarty =& CRM_Core_Smarty::singleton(); foreach ($params['tplParams'] as $name => $value) { $smarty->assign($name, $value); } ################################################### $params['text'] = $text; $params['html'] = $html; $params['subject'] = $subject; // assigning from email $params['from'] = $fromEmail; #### live ###### uncomment it $params['toName'] = $displayName; $params['toEmail'] = $email; #### test ###### comment it #$params['toName'] = "Test"; #$params['toEmail'] = '*****@*****.**'; # Left this in as hard coded for now as the default from email address doesn't seem to work # We can probably do something with the contribution type for the from email addresses $params['from'] = '*****@*****.**'; $attach = array('fullPath' => $filePathName, 'mime_type' => 'pdf', 'cleanName' => $fileName); ## Commented out to test if attachments are causing the problem $params['attachments'] = array($fileName => $attach); require_once 'CRM/Utils/Mail.php'; // Comment to abort sending email $sent = CRM_Utils_Mail::send($params); if ($sent) { echo "<br />Invoice sent <b>successfully</b> - {$email}</b><br /><br />"; ## Insert a record into Log table - civicrm_mtl_invoice_log $contribution_id = $contribution->id; } else { echo "<br />Invoice sent <b>faliure</b> - <b>{$email}</b>{$sent->message}<br /><br />"; } //please comment this before setting up in LIVE //exit; }
/** * Send an email from the specified template based on an array of params * * @param array $params a string-keyed array of function params, see function body for details * * @return array of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates */ static function sendTemplate($params) { $defaults = array('groupName' => null, 'valueName' => null, 'contactId' => null, 'tplParams' => array(), 'from' => null, 'toName' => null, 'toEmail' => null, 'cc' => null, 'bcc' => null, 'replyTo' => null, 'attachments' => null, 'isTest' => false); $params = array_merge($defaults, $params); if (!$params['groupName'] or !$params['valueName']) { CRM_Core_Error::fatal(ts("Message template's option group and/or option value missing.")); } // fetch the three elements from the db based on option_group and option_value names $query = 'SELECT msg_subject subject, msg_text text, msg_html html FROM civicrm_msg_template mt JOIN civicrm_option_value ov ON workflow_id = ov.id JOIN civicrm_option_group og ON ov.option_group_id = og.id WHERE og.name = %1 AND ov.name = %2 AND mt.is_default = 1'; $sqlParams = array(1 => array($params['groupName'], 'String'), 2 => array($params['valueName'], 'String')); $dao = CRM_Core_DAO::executeQuery($query, $sqlParams); $dao->fetch(); if (!$dao->N) { CRM_Core_Error::fatal(ts('No such message template: option group %1, option value %2.', array(1 => $params['groupName'], 2 => $params['valueName']))); } $subject = $dao->subject; $text = $dao->text; $html = $dao->html; // add the test banner (if requested) if ($params['isTest']) { $query = "SELECT msg_subject subject, msg_text text, msg_html html\n FROM civicrm_msg_template mt\n JOIN civicrm_option_value ov ON workflow_id = ov.id\n JOIN civicrm_option_group og ON ov.option_group_id = og.id\n WHERE og.name = 'msg_tpl_workflow_meta' AND ov.name = 'test_preview' AND mt.is_default = 1"; $testDao = CRM_Core_DAO::executeQuery($query); $testDao->fetch(); $subject = $testDao->subject . $subject; $text = $testDao->text . $text; $html = preg_replace('/<body(.*)$/im', "<body\\1\n{$testDao->html}", $html); } // replace tokens in the three elements require_once 'CRM/Utils/Token.php'; require_once 'CRM/Core/BAO/Domain.php'; require_once 'api/v2/Contact.php'; require_once 'CRM/Mailing/BAO/Mailing.php'; $domain = CRM_Core_BAO_Domain::getDomain(); if ($params['contactId']) { $contactParams = array('contact_id' => $params['contactId']); $contact =& civicrm_contact_get($contactParams); } // replace tokens in subject as if it was the text body foreach (array('subject' => 'text', 'text' => 'text', 'html' => 'html') as $type => $tokenType) { if (!${$type}) { continue; } // skip all of the below if the given part is missing $bodyType = "body_{$tokenType}"; $mailing = new CRM_Mailing_BAO_Mailing(); $mailing->{$bodyType} = ${$type}; $tokens = $mailing->getTokens(); ${$type} = CRM_Utils_Token::replaceDomainTokens(${$type}, $domain, true, $tokens[$tokenType]); if ($params['contactId']) { ${$type} = CRM_Utils_Token::replaceContactTokens(${$type}, $contact, false, $tokens[$tokenType]); } } // strip whitespace from ends and turn into a single line $subject = "{strip}{$subject}{/strip}"; // parse the three elements with Smarty require_once 'CRM/Core/Smarty/resources/String.php'; civicrm_smarty_register_string_resource(); $smarty =& CRM_Core_Smarty::singleton(); foreach ($params['tplParams'] as $name => $value) { $smarty->assign($name, $value); } foreach (array('subject', 'text', 'html') as $elem) { ${$elem} = $smarty->fetch("string:{${$elem}}"); } // send the template, honouring the target user’s preferences (if any) $sent = false; if ($params['toEmail']) { $contactParams = array('email' => $params['toEmail']); $contact =& civicrm_contact_get($contactParams); $prefs = array_pop($contact); if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'HTML') { $text = null; } if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'Text') { $html = null; } require_once 'CRM/Utils/Mail.php'; $sent = CRM_Utils_Mail::send($params['from'], $params['toName'], $params['toEmail'], $subject, $text, $params['cc'], $params['bcc'], $params['replyTo'], $html, $params['attachments']); } return array($sent, $subject, $text, $html); }
/** * Send the message to a specific contact. * * @param string $from * The name and email of the sender. * @param int $fromID * @param int $toID * The contact id of the recipient. * @param string $subject * The subject of the message. * @param $text_message * @param $html_message * @param string $emailAddress * Use this 'to' email address instead of the default Primary address. * @param int $activityID * The activity ID that tracks the message. * @param null $attachments * @param null $cc * @param null $bcc * * @return bool * TRUE if successful else FALSE. */ public static function sendMessage($from, $fromID, $toID, &$subject, &$text_message, &$html_message, $emailAddress, $activityID, $attachments = NULL, $cc = NULL, $bcc = NULL) { list($toDisplayName, $toEmail, $toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($toID); if ($emailAddress) { $toEmail = trim($emailAddress); } // make sure both email addresses are valid // and that the recipient wants to receive email if (empty($toEmail) or $toDoNotEmail) { return FALSE; } if (!trim($toDisplayName)) { $toDisplayName = $toEmail; } $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts); // create the params array $mailParams = array('groupName' => 'Activity Email Sender', 'from' => $from, 'toName' => $toDisplayName, 'toEmail' => $toEmail, 'subject' => $subject, 'cc' => $cc, 'bcc' => $bcc, 'text' => $text_message, 'html' => $html_message, 'attachments' => $attachments); if (!CRM_Utils_Mail::send($mailParams)) { return FALSE; } // add activity target record for every mail that is send $activityTargetParams = array('activity_id' => $activityID, 'contact_id' => $toID, 'record_type_id' => $targetID); CRM_Activity_BAO_ActivityContact::create($activityTargetParams); return TRUE; }
/** * Send an email from the specified template based on an array of params * * @param array $params a string-keyed array of function params, see function body for details * * @return array of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates */ static function sendTemplate($params) { $defaults = array('groupName' => NULL, 'valueName' => NULL, 'messageTemplateID' => NULL, 'contactId' => NULL, 'tplParams' => array(), 'from' => NULL, 'toName' => NULL, 'toEmail' => NULL, 'cc' => NULL, 'bcc' => NULL, 'replyTo' => NULL, 'attachments' => NULL, 'isTest' => FALSE, 'PDFFilename' => NULL); $params = array_merge($defaults, $params); if ((!$params['groupName'] || !$params['valueName']) && !$params['messageTemplateID']) { CRM_Core_Error::fatal(ts("Message template's option group and/or option value or ID missing.")); } if ($params['messageTemplateID']) { // fetch the three elements from the db based on id $query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format FROM civicrm_msg_template mt WHERE mt.id = %1 AND mt.is_default = 1'; $sqlParams = array(1 => array($params['messageTemplateID'], 'String')); } else { // fetch the three elements from the db based on option_group and option_value names $query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format FROM civicrm_msg_template mt JOIN civicrm_option_value ov ON workflow_id = ov.id JOIN civicrm_option_group og ON ov.option_group_id = og.id WHERE og.name = %1 AND ov.name = %2 AND mt.is_default = 1'; $sqlParams = array(1 => array($params['groupName'], 'String'), 2 => array($params['valueName'], 'String')); } $dao = CRM_Core_DAO::executeQuery($query, $sqlParams); $dao->fetch(); if (!$dao->N) { if ($params['messageTemplateID']) { CRM_Core_Error::fatal(ts('No such message template: id=%1.', array(1 => $params['messageTemplateID']))); } else { CRM_Core_Error::fatal(ts('No such message template: option group %1, option value %2.', array(1 => $params['groupName'], 2 => $params['valueName']))); } } $subject = $dao->subject; $text = $dao->text; $html = $dao->html; $format = $dao->format; $dao->free(); // add the test banner (if requested) if ($params['isTest']) { $query = "SELECT msg_subject subject, msg_text text, msg_html html\n FROM civicrm_msg_template mt\n JOIN civicrm_option_value ov ON workflow_id = ov.id\n JOIN civicrm_option_group og ON ov.option_group_id = og.id\n WHERE og.name = 'msg_tpl_workflow_meta' AND ov.name = 'test_preview' AND mt.is_default = 1"; $testDao = CRM_Core_DAO::executeQuery($query); $testDao->fetch(); $subject = $testDao->subject . $subject; $text = $testDao->text . $text; $html = preg_replace('/<body(.*)$/im', "<body\\1\n{$testDao->html}", $html); $testDao->free(); } // replace tokens in the three elements (in subject as if it was the text body) $domain = CRM_Core_BAO_Domain::getDomain(); $hookTokens = array(); $mailing = new CRM_Mailing_BAO_Mailing(); $mailing->body_text = $text; $mailing->body_html = $html; $tokens = $mailing->getTokens(); CRM_Utils_Hook::tokens($hookTokens); $categories = array_keys($hookTokens); $contactID = CRM_Utils_Array::value('contactId', $params); if ($contactID) { $contactParams = array('contact_id' => $contactID); $returnProperties = array(); if (isset($tokens['text']['contact'])) { foreach ($tokens['text']['contact'] as $name) { $returnProperties[$name] = 1; } } if (isset($tokens['html']['contact'])) { foreach ($tokens['html']['contact'] as $name) { $returnProperties[$name] = 1; } } list($contact) = CRM_Utils_Token::getTokenDetails($contactParams, $returnProperties, FALSE, FALSE, NULL, CRM_Utils_Token::flattenTokens($tokens), 'CRM_Core_BAO_MessageTemplate'); $contact = $contact[$contactID]; } $subject = CRM_Utils_Token::replaceDomainTokens($subject, $domain, TRUE, $tokens['text'], TRUE); $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, TRUE, $tokens['text'], TRUE); $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, TRUE, $tokens['html'], TRUE); if ($contactID) { $subject = CRM_Utils_Token::replaceContactTokens($subject, $contact, FALSE, $tokens['text'], FALSE, TRUE); $text = CRM_Utils_Token::replaceContactTokens($text, $contact, FALSE, $tokens['text'], FALSE, TRUE); $html = CRM_Utils_Token::replaceContactTokens($html, $contact, FALSE, $tokens['html'], FALSE, TRUE); $contactArray = array($contactID => $contact); CRM_Utils_Hook::tokenValues($contactArray, array($contactID), NULL, CRM_Utils_Token::flattenTokens($tokens), 'CRM_Core_BAO_MessageTemplate'); $contact = $contactArray[$contactID]; $subject = CRM_Utils_Token::replaceHookTokens($subject, $contact, $categories, TRUE); $text = CRM_Utils_Token::replaceHookTokens($text, $contact, $categories, TRUE); $html = CRM_Utils_Token::replaceHookTokens($html, $contact, $categories, TRUE); } // strip whitespace from ends and turn into a single line $subject = "{strip}{$subject}{/strip}"; // parse the three elements with Smarty $smarty = CRM_Core_Smarty::singleton(); foreach ($params['tplParams'] as $name => $value) { $smarty->assign($name, $value); } foreach (array('subject', 'text', 'html') as $elem) { ${$elem} = $smarty->fetch("string:{${$elem}}"); } // send the template, honouring the target user’s preferences (if any) $sent = FALSE; // create the params array $params['subject'] = $subject; $params['text'] = $text; $params['html'] = $html; if ($params['toEmail']) { $contactParams = array(array('email', 'LIKE', $params['toEmail'], 0, 1)); list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($contactParams); $prefs = array_pop($contact); if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'HTML') { $params['text'] = NULL; } if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'Text') { $params['html'] = NULL; } $config = CRM_Core_Config::singleton(); $pdf_filename = ''; if ($config->doNotAttachPDFReceipt && $params['PDFFilename'] && $params['html']) { $pdf_filename = $config->templateCompileDir . CRM_Utils_File::makeFileName($params['PDFFilename']); //FIXME : CRM-7894 //xmlns attribute is required in XHTML but it is invalid in HTML, //Also the namespace "xmlns=http://www.w3.org/1999/xhtml" is default, //and will be added to the <html> tag even if you do not include it. $html = preg_replace('/(<html)(.+?xmlns=["\'].[^\\s]+["\'])(.+)?(>)/', '\\1\\3\\4', $params['html']); file_put_contents($pdf_filename, CRM_Utils_PDF_Utils::html2pdf($html, $params['PDFFilename'], TRUE, $format)); if (empty($params['attachments'])) { $params['attachments'] = array(); } $params['attachments'][] = array('fullPath' => $pdf_filename, 'mime_type' => 'application/pdf', 'cleanName' => $params['PDFFilename']); } $sent = CRM_Utils_Mail::send($params); if ($pdf_filename) { unlink($pdf_filename); } } return array($sent, $subject, $text, $html); }
function civicrm_api3_speakcivi_sendconfirm($params) { $confirmationBlock = $params['confirmation_block']; $contactId = $params['contact_id']; $campaignId = $params['campaign_id']; $activityId = $params['activity_id']; $campaignObj = new CRM_Speakcivi_Logic_Campaign($campaignId); $locale = $campaignObj->getLanguage(); $params['from'] = $campaignObj->getSenderMail(); $params['format'] = null; if ($confirmationBlock) { $params['subject'] = $campaignObj->getSubjectNew(); $message = $campaignObj->getMessageNew(); } else { $params['subject'] = $campaignObj->getSubjectCurrent(); $message = $campaignObj->getMessageCurrent(); } if (!$message) { if ($confirmationBlock) { $message = CRM_Speakcivi_Tools_Dictionary::getMessageNew($locale); $campaignObj->setCustomFieldBySQL($campaignId, $campaignObj->fieldMessageNew, $message); } else { $message = CRM_Speakcivi_Tools_Dictionary::getMessageCurrent($locale); $campaignObj->setCustomFieldBySQL($campaignId, $campaignObj->fieldMessageCurrent, $message); } } $contact = array(); $params_contact = array('id' => $contactId, 'sequential' => 1); $result = civicrm_api3('Contact', 'get', $params_contact); if ($result['count'] == 1) { $contact = $result['values'][0]; } /* CONFIRMATION_BLOCK */ $hash = sha1(CIVICRM_SITE_KEY . $contactId); $utm_content = 'version_' . $contactId % 2; $utm_campaign = $campaignObj->getUtmCampaign(); $url_confirm_and_keep = CRM_Utils_System::url('civicrm/speakcivi/confirm', "id={$contactId}&aid={$activityId}&cid={$campaignId}&hash={$hash}&utm_source=civicrm&utm_medium=email&utm_campaign={$utm_campaign}&utm_content={$utm_content}", true); $url_confirm_and_not_receive = CRM_Utils_System::url('civicrm/speakcivi/optout', "id={$contactId}&aid={$activityId}&cid={$campaignId}&hash={$hash}&utm_source=civicrm&utm_medium=email&utm_campaign={$utm_campaign}&utm_content={$utm_content}", true); $template = CRM_Core_Smarty::singleton(); $template->assign('url_confirm_and_keep', $url_confirm_and_keep); $template->assign('url_confirm_and_not_receive', $url_confirm_and_not_receive); $locales = getLocale($locale); $confirmation_block_html = $template->fetch('../templates/CRM/Speakcivi/Page/ConfirmationBlock.' . $locales['html'] . '.html.tpl'); $confirmation_block_text = $template->fetch('../templates/CRM/Speakcivi/Page/ConfirmationBlock.' . $locales['text'] . '.text.tpl'); /* SHARING_BLOCK */ $template->clearTemplateVars(); $template->assign('url_campaign', $campaignObj->getUrlCampaign()); $template->assign('url_campaign_fb', prepareCleanUrl($campaignObj->getUrlCampaign())); $template->assign('utm_campaign', $campaignObj->getUtmCampaign()); $template->assign('share_facebook', CRM_Speakcivi_Tools_Dictionary::getShareFacebook($locale)); $template->assign('share_twitter', CRM_Speakcivi_Tools_Dictionary::getShareTwitter($locale)); $template->assign('twitter_share_text', urlencode($campaignObj->getTwitterShareText())); $sharing_block_html = $template->fetch('../templates/CRM/Speakcivi/Page/SharingBlock.html.tpl'); $template->clearTemplateVars(); $template->assign('contact', $contact); $message = $template->fetch('string:' . $message); $message_html = str_replace("#CONFIRMATION_BLOCK", html_entity_decode($confirmation_block_html), $message); $message_text = str_replace("#CONFIRMATION_BLOCK", html_entity_decode($confirmation_block_text), $message); $message_html = str_replace("#SHARING_BLOCK", html_entity_decode($sharing_block_html), $message_html); $message_text = str_replace("#SHARING_BLOCK", html_entity_decode($sharing_block_html), $message_text); $params['html'] = $message_html; $params['text'] = convertHtmlToText($message_text); $sent = CRM_Utils_Mail::send($params); return civicrm_api3_create_success($sent, $params); }
function generatePDF($send = FALSE, $template_id) { require_once 'CRM/Utils/PDF/Utils.php'; $fileName = $this->mandate->reference . ".pdf"; if ($send) { $config = CRM_Core_Config::singleton(); $pdfFullFilename = $config->templateCompileDir . CRM_Utils_File::makeFileName($fileName); file_put_contents($pdfFullFilename, CRM_Utils_PDF_Utils::html2pdf($this->html, $fileName, true, null)); list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail(); $params = array(); $params['groupName'] = 'SEPA Email Sender'; $params['from'] = '"' . $domainEmailName . '" <' . $domainEmailAddress . '>'; $params['toEmail'] = $this->contact->email; $params['toName'] = $params['toEmail']; if (empty($params['toEmail'])) { CRM_Core_Session::setStatus(sprintf(ts("Error sending %s: Contact doesn't have an email."), $fileName)); return false; } $params['subject'] = "SEPA " . $fileName; if (!CRM_Utils_Array::value('attachments', $instanceInfo)) { $instanceInfo['attachments'] = array(); } $params['attachments'][] = array('fullPath' => $pdfFullFilename, 'mime_type' => 'application/pdf', 'cleanName' => $fileName); $mail = $this->getMessage($template_id); $params['text'] = "this is the mandate, please return signed"; $params['html'] = $this->getTemplate()->fetch("string:" . $mail["msg_html"]); CRM_Utils_Mail::send($params); // CRM_Core_Session::setStatus(ts("Mail sent")); } else { CRM_Utils_PDF_Utils::html2pdf($this->html, $fileName, false, null); } }
/** * Send a email to ?? with the mailing report of one mailing * * @param type $mailing_id */ function civicrm_api3_job_rapportagenamailings_mail($mailing_id) { global $base_root; // create a new Cor Page $page = new CRM_Core_Page(); $page->_mailing_id = $mailing_id; // create a new template $template = CRM_Core_Smarty::singleton(); // from CRM/Mailing/Page/Report.php // check that the user has permission to access mailing id CRM_Mailing_BAO_Mailing::checkPermission($mailing_id); $report = CRM_Mailing_BAO_Mailing::report($mailing_id); //get contents of mailing CRM_Mailing_BAO_Mailing::getMailingContent($report, $page); $subject = ts('Mailing Gereed: %1', array(1 => $report['mailing']['name'])); $template->assign('report', $report); // inlcude $base_root $template->assign('base_root', $base_root); $template->assign('subject', $subject); // from CRM/Core/page.php // only print $template->assign('tplFile', 'CRM/Rapportagenamailings/Page/RapportMailing.tpl'); $content = $template->fetch('CRM/common/print.tpl'); CRM_Utils_System::appendTPLFile('CRM/Rapportagenamailings/Page/RapportMailing.tpl', $content, $page->overrideExtraTemplateFileName()); //its time to call the hook. CRM_Utils_Hook::alterContent($content, 'page', 'CRM/Rapportagenamailings/Page/RapportMailing.tpl', $page); //echo $content; // send mail $params = array('from' => '*****@*****.**', 'toName' => 'Front Office VnV', 'toEmail' => '*****@*****.**', 'subject' => $subject, 'text' => $subject, 'html' => $content, 'replyTo' => '*****@*****.**'); CRM_Utils_Mail::send($params); }
public static function processMandrillCalls($reponse) { $events = array('open', 'click', 'hard_bounce', 'soft_bounce', 'spam', 'reject'); $bounceType = array(); //MTE-17 $config = CRM_Core_Config::singleton(); if (property_exists($config, 'civiVersion')) { $civiVersion = $config->civiVersion; } else { $civiVersion = CRM_Core_BAO_Domain::version(); } if (version_compare('4.4alpha1', $civiVersion) > 0) { $jobCLassName = 'CRM_Mailing_DAO_Job'; } else { $jobCLassName = 'CRM_Mailing_DAO_MailingJob'; } foreach ($reponse as $value) { //changes done to check if email exists in response array if (in_array($value['event'], $events) && CRM_Utils_Array::value('email', $value['msg'])) { $metaData = CRM_Utils_Array::value('metadata', $value['msg']) ? CRM_Utils_Array::value('CiviCRM_Mandrill_id', $value['msg']['metadata']) : NULL; $header = self::extractHeader($metaData); $mail = self::getMailing($header, $jobCLassName); $contacts = array(); if ($mail->find(TRUE)) { if ($value['event'] == 'click' && $mail->url_tracking === FALSE || $value['event'] == 'open' && $mail->open_tracking === FALSE) { continue; } $emails = self::retrieveEmailContactId($value['msg']['email']); if (!CRM_Utils_Array::value('contact_id', $emails['email'])) { continue; } $value['mailing_id'] = $mail->id; // IF no activity id in header then create new activity if (empty($header[0])) { self::createActivity($value, NULL, $header); } if (empty($header[2])) { $params = array('job_id' => CRM_Core_DAO::getFieldValue($jobCLassName, $mail->id, 'id', 'mailing_id'), 'contact_id' => $emails['email']['contact_id'], 'email_id' => $emails['email']['id']); $eventQueue = CRM_Mailing_Event_BAO_Queue::create($params); $eventQueueID = $eventQueue->id; $hash = $eventQueue->hash; $jobId = $params['job_id']; } else { $eventQueueID = $header[3]; $hash = explode('@', $header[4]); $hash = $hash[0]; $jobId = $header[2]; } if ($eventQueueID) { $mandrillActivtyParams = array('mailing_queue_id' => $eventQueueID, 'activity_id' => $header[0]); CRM_Mte_BAO_MandrillActivity::create($mandrillActivtyParams); } $msgBody = ''; if (!empty($header[0])) { $msgBody = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $header[0], 'details'); } $value['mail_body'] = $msgBody; $bType = ucfirst(preg_replace('/_\\w+/', '', $value['event'])); $assignedContacts = array(); switch ($value['event']) { case 'open': $oe = new CRM_Mailing_Event_BAO_Opened(); $oe->event_queue_id = $eventQueueID; $oe->time_stamp = date('YmdHis', $value['ts']); $oe->save(); break; case 'click': if (CRM_Utils_Array::value(1, $header) == 'b') { break; } $tracker = new CRM_Mailing_BAO_TrackableURL(); $tracker->url = $value['url']; $tracker->mailing_id = $mail->id; if (!$tracker->find(TRUE)) { $tracker->save(); } $open = new CRM_Mailing_Event_BAO_TrackableURLOpen(); $open->event_queue_id = $eventQueueID; $open->trackable_url_id = $tracker->id; $open->time_stamp = date('YmdHis', $value['ts']); $open->save(); break; case 'hard_bounce': case 'soft_bounce': case 'spam': case 'reject': if (empty($bounceType)) { CRM_Core_PseudoConstant::populate($bounceType, 'CRM_Mailing_DAO_BounceType', TRUE, 'id', NULL, NULL, NULL, 'name'); } //Delete queue in delivered since this email is not successfull $delivered = new CRM_Mailing_Event_BAO_Delivered(); $delivered->event_queue_id = $eventQueueID; if ($delivered->find(TRUE)) { $delivered->delete(); } $bounceParams = array('time_stamp' => date('YmdHis', $value['ts']), 'event_queue_id' => $eventQueueID, 'bounce_type_id' => $bounceType["Mandrill {$bType}"], 'job_id' => $jobId, 'hash' => $hash); $bounceParams['bounce_reason'] = CRM_Utils_Array::value('bounce_description', $value['msg']); if (empty($bounceParams['bounce_reason'])) { $bounceParams['bounce_reason'] = CRM_Core_DAO::getFieldValue('CRM_Mailing_DAO_BounceType', $bounceType["Mandrill {$bType}"], 'description'); } CRM_Mailing_Event_BAO_Bounce::create($bounceParams); if (substr($value['event'], -7) == '_bounce') { $mailingBackend = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME, 'mandrill_smtp_settings'); if (CRM_Utils_Array::value('group_id', $mailingBackend)) { list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail(); $mailBody = ts('The following email failed to be delivered due to a') . " {$bType} Bounce :</br>\nTo: {$value['msg']['email']} </br>\nFrom: {$value['msg']['sender']} </br>\nSubject: {$value['msg']['subject']}</br>\nMessage Body: {$msgBody}"; $mailParams = array('groupName' => 'Mandrill bounce notification', 'from' => '"' . $domainEmailName . '" <' . $domainEmailAddress . '>', 'subject' => ts('Mandrill Bounce Notification'), 'text' => $mailBody, 'html' => $mailBody); $query = "SELECT ce.email, cc.sort_name, cgc.contact_id FROM civicrm_contact cc\nINNER JOIN civicrm_group_contact cgc ON cgc.contact_id = cc.id\nINNER JOIN civicrm_email ce ON ce.contact_id = cc.id\nWHERE cc.is_deleted = 0 AND cc.is_deceased = 0 AND cgc.group_id = {$mailingBackend['group_id']} AND ce.is_primary = 1 AND ce.email <> %1"; $queryParam = array(1 => array($value['msg']['email'], 'String')); $dao = CRM_Core_DAO::executeQuery($query, $queryParam); while ($dao->fetch()) { $mailParams['toName'] = $dao->sort_name; $mailParams['toEmail'] = $dao->email; CRM_Utils_Mail::send($mailParams); $value['assignee_contact_id'][] = $dao->contact_id; } } } $bType = 'Bounce'; break; } // create activity for click and open event if ($value['event'] == 'open' || $value['event'] == 'click' || $bType == 'Bounce') { self::createActivity($value, $bType, $header); } } } } }
/** * send the message to a specific contact * * @param string $from the name and email of the sender * @param int $toID the contact id of the recipient * @param string $subject the subject of the message * @param string $message the message contents * @param string $emailAddress use this 'to' email address instead of the default Primary address * @param int $activityID the activity ID that tracks the message * * @return boolean true if successfull else false. * @access public * @static */ static function sendMessage($from, $fromID, $toID, &$subject, &$text_message, &$html_message, $emailAddress, $activityID, $attachments = null, $cc = null, $bcc = null) { list($toDisplayName, $toEmail, $toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($toID); if ($emailAddress) { $toEmail = trim($emailAddress); } // make sure both email addresses are valid // and that the recipient wants to receive email if (empty($toEmail) or $toDoNotEmail) { return false; } if (!trim($toDisplayName)) { $toDisplayName = $toEmail; } // create the params array $params = array(); $params['groupName'] = 'Activity Email Sender'; $params['from'] = $from; $params['toName'] = $toDisplayName; $params['toEmail'] = $toEmail; $params['subject'] = $subject; $params['cc'] = $cc; $params['bcc'] = $bcc; $params['text'] = $text_message; $params['html'] = $html_message; $params['attachments'] = $attachments; if (!CRM_Utils_Mail::send($params)) { return false; } // add activity target record for every mail that is send $activityTargetParams = array('activity_id' => $activityID, 'target_contact_id' => $toID); self::createActivityTarget($activityTargetParams); return true; }
/** * @todo per totten's suggestion, wrap all these writes in a transaction; * see http://wiki.civicrm.org/confluence/display/CRMDOC43/Transaction+Reference */ function postProcess() { $cid = CRM_Utils_Array::value('userID', $_SESSION['CiviCRM'], NULL); $values = $this->controller->exportValues(); $isFlexible = FALSE; // Role id is not present in form $values when the only public need is the flexible need. // So if role id is not set OR if it matches flexible role id constant then use the flexible need id if (!isset($values['volunteer_role_id']) || (int) CRM_Utils_Array::value('volunteer_role_id', $values) === CRM_Volunteer_BAO_Need::FLEXIBLE_ROLE_ID) { $isFlexible = TRUE; foreach ($this->_project->needs as $n) { if ($n['is_flexible'] === '1') { $values['volunteer_need_id'] = $n['id']; break; } } } unset($values['volunteer_role_id']); // we don't need this anymore $params = array('id' => CRM_Utils_Array::value('volunteer_need_id', $values), 'version' => 3); $need = civicrm_api('VolunteerNeed', 'getsingle', $params); $profile_fields = CRM_Core_BAO_UFGroup::getFields($this->_ufgroup_id); $profile_values = array_intersect_key($values, $profile_fields); $builtin_values = array_diff_key($values, $profile_values); // Search for duplicate if (!$cid) { $dedupeParams = CRM_Dedupe_Finder::formatParams($profile_values, 'Individual'); $dedupeParams['check_permission'] = FALSE; $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual'); if ($ids) { $cid = $ids[0]; } } $cid = CRM_Contact_BAO_Contact::createProfileContact($profile_values, $profile_fields, $cid, NULL, $this->_ufgroup_id); $activity_statuses = CRM_Activity_BAO_Activity::buildOptions('status_id', 'create'); $builtin_values['activity_date_time'] = CRM_Utils_Array::value('start_time', $need); $builtin_values['assignee_contact_id'] = $cid; $builtin_values['is_test'] = $this->_mode === 'test' ? 1 : 0; // below we assume that volunteers are always signing up only themselves; // for now this is a safe assumption, but we may need to revisit this. $builtin_values['source_contact_id'] = $cid; // Set status to Available if user selected Flexible Need, else set to Scheduled. if ($isFlexible) { $builtin_values['status_id'] = CRM_Utils_Array::key('Available', $activity_statuses); } else { $builtin_values['status_id'] = CRM_Utils_Array::key('Scheduled', $activity_statuses); } $builtin_values['subject'] = $this->_project->title; $builtin_values['time_scheduled_minutes'] = CRM_Utils_Array::value('duration', $need); CRM_Volunteer_BAO_Assignment::createVolunteerActivity($builtin_values); // Send confirmation email to volunteer list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($cid); list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail(); if ($email) { $date = CRM_Utils_Date::customFormat($builtin_values['activity_date_time'], "%m/%E/%Y at %l:%M %P"); $html = "You are scheduled to volunteer at the " . $builtin_values["subject"] . " on " . $date . ". Thank You!"; $mailParams["from"] = "{$domainEmailName} <" . $domainEmailAddress . ">"; $mailParams["toName"] = $displayName; $mailParams["toEmail"] = $email; $mailParams["subject"] = "Volunteer Confirmation for {$builtin_values['subject']}"; $mailParams["text"] = $html; $mailParams["html"] = $html; $mailParams["replyTo"] = $domainEmailAddress; CRM_Utils_Mail::send($mailParams); } $statusMsg = ts('You are scheduled to volunteer. Thank you!', array('domain' => 'org.civicrm.volunteer')); CRM_Core_Session::setStatus($statusMsg, '', 'success'); CRM_Utils_System::redirect($this->_destination); }
function send_alert_email($p_eWAY_tran_num, $p_trxn_out, $p_trxn_back, $p_request, $p_response) { // Initialization call is required to use CiviCRM APIs. civicrm_initialize(true); require_once 'CRM/Utils/Mail.php'; require_once 'CRM/Core/BAO/Domain.php'; list($fromName, $fromEmail) = CRM_Core_BAO_Domain::getNameAndEmail(); $from = "{$fromName} <{$fromEmail}>"; $toName = 'Support at eWAY'; $toEmail = '*****@*****.**'; $subject = "ALERT: Unique Trxn Number Failure : eWAY Transaction # = [" . $p_eWAY_tran_num . "]"; $message = "\r\nTRXN sent out with request = '{$p_trxn_out}'.\r\nTRXN sent back with response = '{$p_trxn_back}'.\r\n\r\nThis is a ['{$this->_mode}'] transaction.\r\n\r\n\r\nRequest XML = \r\n---------------------------------------------------------------------------\r\n{$p_request}\r\n---------------------------------------------------------------------------\r\n\r\n\r\nResponse XML = \r\n---------------------------------------------------------------------------\r\n{$p_response}\r\n---------------------------------------------------------------------------\r\n\r\n\r\nRegards\r\n\r\nThe CiviCRM eWAY Payment Processor Module\r\n"; //$cc = 'Name@Domain'; CRM_Utils_Mail::send($from, $toName, $toEmail, $subject, $message, $cc); }
static function sendReminder($contactId, $email, $scheduleID, $from, $tokenParams) { $schedule = new CRM_Core_DAO_ActionSchedule(); $schedule->id = $scheduleID; $domain = CRM_Core_BAO_Domain::getDomain(); $result = NULL; $hookTokens = array(); if ($schedule->find(TRUE)) { $body_text = $schedule->body_text; $body_html = $schedule->body_html; $body_subject = $schedule->subject; if (!$body_text) { $body_text = CRM_Utils_String::htmlToText($body_html); } $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')) { return NULL; } // merge activity tokens with contact array $contact = array_merge($contact, $tokenParams); //CRM-5734 CRM_Utils_Hook::tokenValues($contact, $contactId); CRM_Utils_Hook::tokens($hookTokens); $categories = array_keys($hookTokens); $type = array('html', 'text'); foreach ($type as $key => $value) { $dummy_mail = new CRM_Mailing_BAO_Mailing(); $bodyType = "body_{$value}"; $dummy_mail->{$bodyType} = ${$bodyType}; $tokens = $dummy_mail->getTokens(); if (${$bodyType}) { CRM_Utils_Token::replaceGreetingTokens(${$bodyType}, NULL, $contact['contact_id']); ${$bodyType} = CRM_Utils_Token::replaceDomainTokens(${$bodyType}, $domain, TRUE, $tokens[$value], TRUE); ${$bodyType} = CRM_Utils_Token::replaceContactTokens(${$bodyType}, $contact, FALSE, $tokens[$value], FALSE, TRUE); ${$bodyType} = CRM_Utils_Token::replaceComponentTokens(${$bodyType}, $contact, $tokens[$value], TRUE, FALSE); ${$bodyType} = CRM_Utils_Token::replaceHookTokens(${$bodyType}, $contact, $categories, TRUE); } } $html = $body_html; $text = $body_text; $smarty = CRM_Core_Smarty::singleton(); foreach (array('text', 'html') as $elem) { ${$elem} = $smarty->fetch("string:{${$elem}}"); } $matches = array(); preg_match_all('/(?<!\\{|\\\\)\\{(\\w+\\.\\w+)\\}(?!\\})/', $body_subject, $matches, PREG_PATTERN_ORDER); $subjectToken = NULL; if ($matches[1]) { foreach ($matches[1] as $token) { list($type, $name) = preg_split('/\\./', $token, 2); if ($name) { if (!isset($subjectToken['contact'])) { $subjectToken['contact'] = array(); } $subjectToken['contact'][] = $name; } } } $messageSubject = CRM_Utils_Token::replaceContactTokens($body_subject, $contact, FALSE, $subjectToken); $messageSubject = CRM_Utils_Token::replaceDomainTokens($messageSubject, $domain, TRUE, $tokens[$value]); $messageSubject = CRM_Utils_Token::replaceComponentTokens($messageSubject, $contact, $tokens[$value], TRUE); $messageSubject = CRM_Utils_Token::replaceHookTokens($messageSubject, $contact, $categories, TRUE); $messageSubject = $smarty->fetch("string:{$messageSubject}"); // set up the parameters for CRM_Utils_Mail::send $mailParams = array('groupName' => 'Scheduled Reminder Sender', 'from' => $from, 'toName' => $contact['display_name'], 'toEmail' => $email, 'subject' => $messageSubject); if (!$html || $contact['preferred_mail_format'] == 'Text' || $contact['preferred_mail_format'] == 'Both') { // render the & entities in text mode, so that the links work $mailParams['text'] = str_replace('&', '&', $text); } if ($html && ($contact['preferred_mail_format'] == 'HTML' || $contact['preferred_mail_format'] == 'Both')) { $mailParams['html'] = $html; } $result = CRM_Utils_Mail::send($mailParams); } $schedule->free(); return $result; }
/** * @param $contactId * @param $to * @param $scheduleID * @param $from * @param $tokenParams * * @return bool|null * @throws CRM_Core_Exception */ static function sendReminder($contactId, $to, $scheduleID, $from, $tokenParams) { $email = $to['email']; $phoneNumber = $to['phone']; $schedule = new CRM_Core_DAO_ActionSchedule(); $schedule->id = $scheduleID; $domain = CRM_Core_BAO_Domain::getDomain(); $result = NULL; $hookTokens = array(); if ($schedule->find(TRUE)) { $body_text = $schedule->body_text; $body_html = $schedule->body_html; $sms_body_text = $schedule->sms_body_text; $body_subject = $schedule->subject; if (!$body_text) { $body_text = CRM_Utils_String::htmlToText($body_html); } $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')) { return NULL; } // merge activity tokens with contact array $contact = array_merge($contact, $tokenParams); //CRM-5734 CRM_Utils_Hook::tokenValues($contact, $contactId); CRM_Utils_Hook::tokens($hookTokens); $categories = array_keys($hookTokens); $type = array('body_html' => 'html', 'body_text' => 'text', 'sms_body_text' => 'text'); foreach ($type as $bodyType => $value) { $dummy_mail = new CRM_Mailing_BAO_Mailing(); if ($bodyType == 'sms_body_text') { $dummy_mail->body_text = ${$bodyType}; } else { $dummy_mail->{${$bodyType}} = ${$bodyType}; } $tokens = $dummy_mail->getTokens(); if (${$bodyType}) { CRM_Utils_Token::replaceGreetingTokens(${$bodyType}, NULL, $contact['contact_id']); ${$bodyType} = CRM_Utils_Token::replaceDomainTokens(${$bodyType}, $domain, TRUE, $tokens[$value], TRUE); ${$bodyType} = CRM_Utils_Token::replaceContactTokens(${$bodyType}, $contact, FALSE, $tokens[$value], FALSE, TRUE); ${$bodyType} = CRM_Utils_Token::replaceComponentTokens(${$bodyType}, $contact, $tokens[$value], TRUE, FALSE); ${$bodyType} = CRM_Utils_Token::replaceHookTokens(${$bodyType}, $contact, $categories, TRUE); } } $html = $body_html; $text = $body_text; $sms_text = $sms_body_text; $smarty = CRM_Core_Smarty::singleton(); foreach (array('text', 'html', 'sms_text') as $elem) { ${$elem} = $smarty->fetch("string:{${$elem}}"); } $matches = array(); preg_match_all('/(?<!\\{|\\\\)\\{(\\w+\\.\\w+)\\}(?!\\})/', $body_subject, $matches, PREG_PATTERN_ORDER); $subjectToken = NULL; if ($matches[1]) { foreach ($matches[1] as $token) { list($type, $name) = preg_split('/\\./', $token, 2); if ($name) { if (!isset($subjectToken[$type])) { $subjectToken[$type] = array(); } $subjectToken[$type][] = $name; } } } $messageSubject = CRM_Utils_Token::replaceContactTokens($body_subject, $contact, FALSE, $subjectToken); $messageSubject = CRM_Utils_Token::replaceDomainTokens($messageSubject, $domain, TRUE, $subjectToken); $messageSubject = CRM_Utils_Token::replaceComponentTokens($messageSubject, $contact, $subjectToken, TRUE); $messageSubject = CRM_Utils_Token::replaceHookTokens($messageSubject, $contact, $categories, TRUE); $messageSubject = $smarty->fetch("string:{$messageSubject}"); if ($schedule->mode == 'SMS' or $schedule->mode == 'User_Preference') { $session = CRM_Core_Session::singleton(); $userID = $session->get('userID') ? $session->get('userID') : $contactId; $smsParams = array('To' => $phoneNumber, 'provider_id' => $schedule->sms_provider_id, 'activity_subject' => $messageSubject); $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'SMS', 'name'); $activityParams = array('source_contact_id' => $userID, 'activity_type_id' => $activityTypeID, 'activity_date_time' => date('YmdHis'), 'subject' => $messageSubject, 'details' => $sms_text, 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name')); $activity = CRM_Activity_BAO_Activity::create($activityParams); CRM_Activity_BAO_Activity::sendSMSMessage($contactId, $sms_text, $html, $smsParams, $activity->id, $userID); } if ($schedule->mode == 'Email' or $schedule->mode == 'User_Preference') { // set up the parameters for CRM_Utils_Mail::send $mailParams = array('groupName' => 'Scheduled Reminder Sender', 'from' => $from, 'toName' => $contact['display_name'], 'toEmail' => $email, 'subject' => $messageSubject, 'entity' => 'action_schedule', 'entity_id' => $scheduleID); if (!$html || $contact['preferred_mail_format'] == 'Text' || $contact['preferred_mail_format'] == 'Both') { // render the & entities in text mode, so that the links work $mailParams['text'] = str_replace('&', '&', $text); } if ($html && ($contact['preferred_mail_format'] == 'HTML' || $contact['preferred_mail_format'] == 'Both')) { $mailParams['html'] = $html; } $result = CRM_Utils_Mail::send($mailParams); } } $schedule->free(); return $result; }
function civicrm_api3_job_exportleaveregistration_months_email($params, $content) { // create a temp file, with the csv content $filename = tempnam($conf['file_temporary_path'], 'verlof.bosgoed.com-maand.csv'); $fp = fopen($filename, 'w'); fwrite($fp, $content); fclose($fp); if (isset($params['email']) and !empty($params['email'])) { $email = $params['email']; } else { $email = '*****@*****.**'; } global $conf; // set the paramters of the email $parameters = array('from' => '"' . $conf['site_name'] . '" <' . $conf['site_mail'] . '>', 'toName' => 'Isolde Dordievski', 'toEmail' => $email, 'subject' => 'Overzicht verlof bosgoed Maand(en)', 'text' => 'Overzicht verlof bosgoed maand(en)', 'attachments' => array('ExportLeaveregistration' => array('fullPath' => $filename, 'mime_type' => 'text/csv', 'cleanName' => 'Verlof Bosgoed Com - Maand(en).csv'))); // send the email if (!CRM_Utils_Mail::send($parameters)) { echo ts('Failt to send mail !'); } // remove the temp csv file unlink($filename); }
function giftmemberships_civicrm_postProcess($formName, &$form) { if ($formName == "CRM_Price_Form_Field" && ($form->_submitValues['gift-check'] == 1 || $form->_submitValues['redeem-check'] == 1)) { $priceSetId = $form->get('sid'); $label = $form->_submitValues['label']; /* Get price fields belonging to price set */ try { $result = civicrm_api3('PriceField', 'get', array('sequential' => 1, 'price_set_id' => $priceSetId)); foreach ($result['values'] as $value) { if ($value['label'] == $label) { /*** Update Name in Pricefield table ***/ $priceFieldId = $value['id']; if ($form->_submitValues['gift-check'] == 1) { $name = '_gift_membership'; } elseif ($form->_submitValues['redeem-check'] == 1) { $name = '_redeem_membership'; } $update = civicrm_api3('PriceField', 'create', array('sequential' => 1, 'price_set_id' => $priceSetId, 'id' => $priceFieldId, 'name' => $name)); /*** Save membership_type in gift_membership_price_fields table ***/ if ($update['is_error'] != 1 && $form->_submitValues['gift-check'] == 1) { $memType = $form->_submitValues['membershipselect']; $sql = "SELECT pfid FROM civicrm_gift_membership_price_fields WHERE pfid = {$priceFieldId};"; $dao = CRM_Core_DAO::executeQuery($sql); if ($dao->fetch()) { $giftPFID = $dao->pfid; } if ($giftPFID) { $sql = "UPDATE civicrm_gift_membership_price_fields SET membership_type_id={$memType} WHERE pfid={$giftPFID};"; } else { $sql = "INSERT INTO civicrm_gift_membership_price_fields (pfid, membership_type_id) VALUES ({$priceFieldId}, {$memType});"; } $dao = CRM_Core_DAO::executeQuery($sql); } } } } catch (CiviCRM_API3_Exeception $e) { $error = $e->getMessage(); } } if ($formName == "CRM_Contribute_Form_Contribution_Confirm") { $submitValues = $form->_params; $contributionId = $form->_contributionID; $giverId = $form->_contactID; foreach ($submitValues as $key => $value) { if (strpos($key, '_gift-codes') !== false) { $giftcodes = true; $price = explode("_", $key); $pfid = $price[0]; $sql = "SELECT membership_type_id FROM civicrm_gift_membership_price_fields WHERE pfid = {$pfid};"; $dao = CRM_Core_DAO::executeQuery($sql); if ($dao->fetch()) { $membershipType = $dao->membership_type_id; } if (strpos($value, '::')) { $codes = explode('::', $value); foreach ($codes as $code) { $sql = "INSERT INTO civicrm_gift_membership_codes (membership_id, code, membership_type, contribution_id, giver_id) VALUES (NULL, '{$code}', '{$membershipType}', '{$contributionId}','{$giverId}' );"; $dao = CRM_Core_DAO::executeQuery($sql); } } else { if ($value != "") { $sql = "INSERT INTO civicrm_gift_membership_codes (membership_id, code, membership_type, contribution_id, giver_id) VALUES (NULL, '{$value}', '{$membershipType}', '{$contributionId}', '{$giverId}');"; $dao = CRM_Core_DAO::executeQuery($sql); } } } if (strpos($key, '_redeem-code') !== false) { //Create Membership using api $contact_id = $form->_contactID; $price = explode("_", $key); $pfid = $price[0]; $priceName = "price_" . $pfid; $code = $submitValues[$priceName]; $sql = "SELECT * FROM civicrm_gift_membership_codes WHERE code = '{$code}'"; $dao = CRM_Core_DAO::executeQuery($sql); if ($dao->fetch()) { $memType = $dao->membership_type; $giver = $dao->giver_id; $displayName = CRM_Contact_BAO_Contact::displayName($giver); $source = "Gift Membership from " . $displayName; $result = civicrm_api3('Membership', 'create', array('sequential' => 1, 'membership_type_id' => $memType, 'contact_id' => $contact_id, 'source' => $source)); if ($result['is_error'] != 1) { $memId = $result['id']; $sql = "UPDATE civicrm_gift_membership_codes SET membership_id='{$memId}' WHERE code='{$code}';"; $dao = CRM_Core_DAO::executeQuery($sql); } } } } //end foreach /**** Send Email With Codes ****/ if (isset($giftcodes) && $giftcodes == true) { /*** Make beginning of Code Table ***/ $codeTable = "<h3>Gift Membership Codes</h3><table width='500px' style='border:1px solid #999;margin:1em 0em 1em;border-collapse:collapse'><thead><tr><th style='text-align:left;padding:4px;border-bottom:1px solid #999;background-color:#eee'>Membership</th><th style='text-align:left;padding:4px;border-bottom:1px solid #999;background-color:#eee'>Code</th></tr></thead><tbody>"; $sql = "SELECT * FROM civicrm_gift_membership_codes WHERE contribution_id = '{$contributionId}'"; $dao = CRM_Core_DAO::executeQuery($sql); /*** Add row for each code with corresponding membership purchased ***/ while ($dao->fetch()) { $code = $dao->code; $memType = $dao->membership_type; $result = civicrm_api3('MembershipType', 'getsingle', array('sequential' => 1, 'id' => $memType)); $memName = $result['name'] . " Membership"; $codeTable .= "<tr><td>{$memName}</td><td>{$code}</td></tr>"; } $codeTable .= "</tbody></table>"; /*** get organization id of site ***/ $sql = "SELECT contact_id FROM civicrm_domain WHERE id = 1"; $dao = CRM_Core_DAO::executeQuery($sql); if ($dao->fetch()) { $orgEmail = CRM_Contact_BAO_Contact::getPrimaryEmail($dao->contact_id); } /*** Prepare Params and Send Email ***/ $email = CRM_Contact_BAO_Contact::getPrimaryEmail($giverId); $contactName = CRM_Contact_BAO_Contact::displayName($giverId); $mailParams = array(); $mailParams['from'] = $orgEmail; $mailParams['toName'] = $contactName; $mailParams['subject'] = 'Gift Membership codes'; $mailParams['toEmail'] = $email; $mailParams['html'] = $codeTable; $mailed = CRM_Utils_Mail::send($mailParams); } } }
/** * Send pdf by email. * * @param array $contact * @param string $html * * @param $is_pdf * @param array $format * @param array $params * * @return bool */ public static function emailLetter($contact, $html, $is_pdf, $format = array(), $params = array()) { try { if (empty($contact['email'])) { return FALSE; } $mustBeEmpty = array('do_not_email', 'is_deceased', 'on_hold'); foreach ($mustBeEmpty as $emptyField) { if (!empty($contact[$emptyField])) { return FALSE; } } $defaults = array('toName' => $contact['display_name'], 'toEmail' => $contact['email'], 'text' => '', 'html' => $html); if (empty($params['from'])) { $emails = CRM_Core_BAO_Email::getFromEmail(); $emails = array_keys($emails); $defaults['from'] = array_pop($emails); } if (!empty($params['subject'])) { $defaults['subject'] = $params['subject']; } else { $defaults['subject'] = ts('Thank you for your contribution/s'); } if ($is_pdf) { $defaults['html'] = ts('Please see attached'); $defaults['attachments'] = array(CRM_Utils_Mail::appendPDF('ThankYou.pdf', $html, $format)); } $params = array_merge($defaults); return CRM_Utils_Mail::send($params); } catch (CRM_Core_Exception $e) { return FALSE; } }
static function mailReport($fileContent, $instanceID = null, $outputMode = 'html') { if (!$instanceID) { return false; } $url = CRM_Utils_System::url("civicrm/report/instance/{$instanceID}", "reset=1", true); $url = "Report Url: {$url} "; $fileContent = $url . $fileContent; require_once 'CRM/Core/BAO/Domain.php'; list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail(); $params = array('id' => $instanceID); $instanceInfo = array(); CRM_Core_DAO::commonRetrieve('CRM_Report_DAO_Instance', $params, $instanceInfo); $params = array(); $params['groupName'] = 'Report Email Sender'; $params['from'] = '"' . $domainEmailName . '" <' . $domainEmailAddress . '>'; $params['toName'] = ""; //$domainEmailName; $params['toEmail'] = CRM_Utils_Array::value('email_to', $instanceInfo); $params['cc'] = CRM_Utils_Array::value('email_cc', $instanceInfo); $params['subject'] = CRM_Utils_Array::value('email_subject', $instanceInfo); $params['attachments'] = CRM_Utils_Array::value('attachments', $instanceInfo); $params['text'] = ''; $params['html'] = $fileContent; require_once "CRM/Utils/Mail.php"; return CRM_Utils_Mail::send($params); }
static function mailReport($fileContent, $instanceID = NULL, $outputMode = 'html', $attachments = array()) { if (!$instanceID) { return FALSE; } list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail(); $params = array('id' => $instanceID); $instanceInfo = array(); CRM_Core_DAO::commonRetrieve('CRM_Report_DAO_ReportInstance', $params, $instanceInfo); $params = array(); $params['groupName'] = 'Report Email Sender'; $params['from'] = '"' . $domainEmailName . '" <' . $domainEmailAddress . '>'; //$domainEmailName; $params['toName'] = ""; $params['toEmail'] = CRM_Utils_Array::value('email_to', $instanceInfo); $params['cc'] = CRM_Utils_Array::value('email_cc', $instanceInfo); $params['subject'] = CRM_Utils_Array::value('email_subject', $instanceInfo); if (empty($instanceInfo['attachments'])) { $instanceInfo['attachments'] = array(); } $params['attachments'] = array_merge(CRM_Utils_Array::value('attachments', $instanceInfo), $attachments); $params['text'] = ''; $params['html'] = $fileContent; return CRM_Utils_Mail::send($params); }
/** * send the message to a specific contact * * @param string $from the name and email of the sender * @param int $toID the contact id of the recipient * @param string $subject the subject of the message * @param string $message the message contents * @param string $emailAddress use this 'to' email address instead of the default Primary address * @param int $activityID the activity ID that tracks the message * * @return boolean true if successfull else false. * @access public * @static */ function sendMessage($from, $toID, &$subject, &$message, $emailAddress, $activityID) { list($toDisplayName, $toEmail, $toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($toID); if ($emailAddress) { $toEmail = trim($emailAddress); } // make sure both email addresses are valid // and that the recipient wants to receive email if (empty($toEmail) or $toDoNotEmail) { return false; } if (!trim($toDisplayName)) { $toDisplayName = $toEmail; } if (!CRM_Utils_Mail::send($from, $toDisplayName, $toEmail, $subject, $message)) { return false; } // we need to insert an activity history record here $params = array('entity_table' => 'civicrm_contact', 'entity_id' => $toID, 'activity_type' => ts('Email Sent'), 'module' => 'CiviCRM', 'callback' => 'CRM_Core_BAO_EmailHistory::showEmailDetails', 'activity_id' => $activityID, 'activity_summary' => ts('To: %1; Subject: %2', array(1 => "{$toDisplayName} <{$toEmail}>", 2 => $subject)), 'activity_date' => date('YmdHis')); if (is_a(crm_create_activity_history($params), CRM_Core_Error)) { return false; } return true; }
/** * Send an alert email. * * @param $p_eWAY_tran_num * @param $p_trxn_out * @param $p_trxn_back * @param $p_request * @param $p_response */ public function send_alert_email($p_eWAY_tran_num, $p_trxn_out, $p_trxn_back, $p_request, $p_response) { // Initialization call is required to use CiviCRM APIs. civicrm_initialize(TRUE); list($fromName, $fromEmail) = CRM_Core_BAO_Domain::getNameAndEmail(); $from = "{$fromName} <{$fromEmail}>"; $toName = 'Support at eWAY'; $toEmail = '*****@*****.**'; $subject = "ALERT: Unique Trxn Number Failure : eWAY Transaction # = [" . $p_eWAY_tran_num . "]"; $message = "\nTRXN sent out with request = '{$p_trxn_out}'.\nTRXN sent back with response = '{$p_trxn_back}'.\n\nThis is a ['{$this->_mode}'] transaction.\n\n\nRequest XML =\n---------------------------------------------------------------------------\n{$p_request}\n---------------------------------------------------------------------------\n\n\nResponse XML =\n---------------------------------------------------------------------------\n{$p_response}\n---------------------------------------------------------------------------\n\n\nRegards\n\nThe CiviCRM eWAY Payment Processor Module\n"; $params = array(); $params['groupName'] = 'eWay Email Sender'; $params['from'] = $from; $params['toName'] = $toName; $params['toEmail'] = $toEmail; $params['subject'] = $subject; $params['text'] = $message; CRM_Utils_Mail::send($params); }
/** * @param \Civi\Token\TokenRow $tokenRow * @param CRM_Core_DAO_ActionSchedule $schedule * @param int $toContactID * @return array * List of error messages. */ protected static function sendReminderEmail($tokenRow, $schedule, $toContactID) { $toEmail = CRM_Contact_BAO_Contact::getPrimaryEmail($toContactID); if (!$toEmail) { return array("email_missing" => "Couldn't find recipient's email address."); } $body_text = $tokenRow->render('body_text'); $body_html = $tokenRow->render('body_html'); if (!$schedule->body_text) { $body_text = CRM_Utils_String::htmlToText($body_html); } // set up the parameters for CRM_Utils_Mail::send $mailParams = array('groupName' => 'Scheduled Reminder Sender', 'from' => self::pickFromEmail($schedule), 'toName' => $tokenRow->context['contact']['display_name'], 'toEmail' => $toEmail, 'subject' => $tokenRow->render('subject'), 'entity' => 'action_schedule', 'entity_id' => $schedule->id); if (!$body_html || $tokenRow->context['contact']['preferred_mail_format'] == 'Text' || $tokenRow->context['contact']['preferred_mail_format'] == 'Both') { // render the & entities in text mode, so that the links work $mailParams['text'] = str_replace('&', '&', $body_text); } if ($body_html && ($tokenRow->context['contact']['preferred_mail_format'] == 'HTML' || $tokenRow->context['contact']['preferred_mail_format'] == 'Both')) { $mailParams['html'] = $body_html; } $result = CRM_Utils_Mail::send($mailParams); if (!$result || is_a($result, 'PEAR_Error')) { return array('email_fail' => 'Failed to send message'); } return array(); }
/** * 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) { $se =& CRM_Mailing_Event_BAO_Subscribe::verify($contact_id, $subscribe_id, $hash); if (!$se) { return FALSE; } // before we proceed lets just check if this contact is already 'Added' // if so, we should ignore this request and hence avoid sending multiple // emails - CRM-11157 $details = CRM_Contact_BAO_GroupContact::getMembershipDetail($contact_id, $se->group_id); if ($details && $details->status == 'Added') { // This contact is already subscribed // lets return the group title return CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $se->group_id, 'title'); } $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(); CRM_Contact_BAO_GroupContact::addContactsToGroup(array($contact_id), $se->group_id, 'Email', 'Added', $ce->id); $transaction->commit(); $config = CRM_Core_Config::singleton(); $domain = CRM_Core_BAO_Domain::getDomain(); list($domainEmailName, $_) = CRM_Core_BAO_Domain::getNameAndEmail(); list($display_name, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($se->contact_id); $group = new CRM_Contact_DAO_Group(); $group->id = $se->group_id; $group->find(TRUE); $component = new CRM_Mailing_BAO_Component(); $component->is_default = 1; $component->is_active = 1; $component->component_type = 'Welcome'; $component->find(TRUE); $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain(); $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::replaceWelcomeTokens($html, $group->title, TRUE); $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, FALSE, $tokens['text']); $text = CRM_Utils_Token::replaceWelcomeTokens($text, $group->title, FALSE); $mailParams = array('groupName' => 'Mailing Event ' . $component->component_type, 'subject' => $component->subject, 'from' => "\"{$domainEmailName}\" <do-not-reply@{$emailDomain}>", 'toEmail' => $email, 'toName' => $display_name, 'replyTo' => "do-not-reply@{$emailDomain}", 'returnPath' => "do-not-reply@{$emailDomain}", 'html' => $html, 'text' => $text); // send - ignore errors because the desired status change has already been successful $unused_result = CRM_Utils_Mail::send($mailParams); return $group->title; }
/** * Process the form * * @return void * @access public */ function postProcess() { $contactID = $this->get('contactID'); if (!$contactID) { // make a copy of params so we dont destroy our params // (since we pass this by reference) $premiumParams = $params = $this->_params; // so now we have a confirmed financial transaction // lets create or update a contact first require_once 'api/crm.php'; $ids = CRM_Core_BAO_UFGroup::findContact($params); $contactsIDs = explode(',', $ids); // if we find more than one contact, use the first one $contact_id = $contactsIDs[0]; $contact = null; if ($contact_id) { $contact =& crm_get_contact(array('contact_id' => $contact_id)); } $ids = array(); if (!$contact || !is_a($contact, 'CRM_Contact_BAO_Contact')) { $contact =& CRM_Contact_BAO_Contact::createFlat($params, $ids); } else { // need to fix and unify all contact creation $idParams = array('id' => $contact_id, 'contact_id' => $contact_id); $defaults = array(); CRM_Contact_BAO_Contact::retrieve($idParams, $defaults, $ids); $contact =& CRM_Contact_BAO_Contact::createFlat($params, $ids); } if (is_a($contact, 'CRM_Core_Error')) { CRM_Core_Error::fatal("Failed creating contact for contributor"); } $contactID = $contact->id; $this->set('contactID', $contactID); } $contributionType =& new CRM_Contribute_DAO_ContributionType(); $contributionType->id = $this->_values['contribution_type_id']; if (!$contributionType->find(true)) { CRM_Core_Error::fatal("Could not find a system table"); } // add some contribution type details to the params list // if folks need to use it $this->_params['contributionType_name'] = $contributionType->name; $this->_params['contributionType_accounting_code'] = $contributionType->accounting_code; $this->_params['contributionForm_id'] = $this->_values['id']; require_once 'CRM/Contribute/Payment.php'; $payment =& CRM_Contribute_Payment::singleton($this->_mode); if ($this->_contributeMode == 'express') { $result =& $payment->doExpressCheckout($this->_params); } else { $result =& $payment->doDirectPayment($this->_params); } if (is_a($result, 'CRM_Core_Error')) { CRM_Core_Error::displaySessionError($result); CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact', '_qf_Main_display=true')); } $now = date('YmdHis'); $this->_params = array_merge($this->_params, $result); $this->_params['receive_date'] = $now; $this->set('params', $this->_params); $this->assign('trxn_id', $result['trxn_id']); $this->assign('receive_date', CRM_Utils_Date::mysqlToIso($this->_params['receive_date'])); // result has all the stuff we need // lets archive it to a financial transaction $config =& CRM_Core_Config::singleton(); $receiptDate = null; if ($this->_values['is_email_receipt']) { $receiptDate = $now; } if ($contributionType->is_deductible) { $this->assign('is_deductible', true); $this->set('is_deductible', true); } // assigning Premium information to receipt tpl if ($premiumParams['selectProduct'] && $premiumParams['selectProduct'] != 'no_thanks') { $startDate = $endDate = ""; $this->assign('selectPremium', true); require_once 'CRM/Contribute/DAO/Product.php'; $productDAO =& new CRM_Contribute_DAO_Product(); $productDAO->id = $premiumParams['selectProduct']; $productDAO->find(true); $this->assign('product_name', $productDAO->name); $this->assign('price', $productDAO->price); $this->assign('sku', $productDAO->sku); $this->assign('option', $premiumParams['options_' . $premiumParams['selectProduct']]); $periodType = $productDAO->period_type; if ($periodType) { $fixed_period_start_day = $productDAO->fixed_period_start_day; $duration_unit = $productDAO->duration_unit; $duration_interval = $productDAO->duration_interval; if ($periodType == 'rolling') { $startDate = date('Y-m-d'); } else { if ($periodType == 'fixed') { if ($fixed_period_start_day) { $date = explode('-', date('Y-m-d')); $month = substr($fixed_period_start_day, 0, strlen($fixed_period_start_day) - 2); $day = substr($fixed_period_start_day, -2) . "<br>"; $year = $date[0]; $startDate = $year . '-' . $month . '-' . $day; } else { $startDate = date('Y-m-d'); } } } $date = explode('-', $startDate); $year = $date[0]; $month = $date[1]; $day = $date[2]; switch ($duration_unit) { case 'year': $year = $year + $duration_interval; break; case 'month': $month = $month + $duration_interval; break; case 'day': $day = $day + $duration_interval; break; case 'week': $day = $day + $duration_interval * 7; } $endDate = date('Y-m-d H:i:s', mktime($hour, $minute, $second, $month, $day, $year)); $this->assign('start_date', $startDate); $this->assign('end_date', $endDate); } require_once 'CRM/Contribute/DAO/Premium.php'; $dao =& new CRM_Contribute_DAO_Premium(); $dao->entity_table = 'civicrm_contribution_page'; $dao->entity_id = $this->_id; $dao->find(true); $this->assign('contact_phone', $dao->premiums_contact_phone); $this->assign('contact_email', $dao->premiums_contact_email); } CRM_Core_DAO::transaction('BEGIN'); $nonDeductibleAmount = $result['gross_amount']; if ($contributionType->is_deductible) { if ($premiumParams['selectProduct'] != 'no_thanks') { require_once 'CRM/Contribute/DAO/Product.php'; $productDAO =& new CRM_Contribute_DAO_Product(); $productDAO->id = $premiumParams['selectProduct']; $productDAO->find(true); if ($result['gross_amount'] < $productDAO->price) { $nonDeductibleAmount = $result['gross_amount']; } else { $nonDeductibleAmount = $productDAO->price; } } else { $nonDeductibleAmount = '0.00'; } } // check contribution Type // first create the contribution record $params = array('contact_id' => $contactID, 'contribution_type_id' => $contributionType->id, 'payment_instrument_id' => 1, 'receive_date' => $now, 'non_deductible_amount' => $nonDeductibleAmount, 'total_amount' => $result['gross_amount'], 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $result['gross_amount']), 'trxn_id' => $result['trxn_id'], 'invoice_id' => $this->_params['invoiceID'], 'currency' => $this->_params['currencyID'], 'receipt_date' => $receiptDate, 'source' => ts('Online Contribution:') . ' ' . $this->_values['title']); $ids = array(); $contribution =& CRM_Contribute_BAO_Contribution::add($params, $ids); //create Premium record if ($premiumParams['selectProduct'] && $premiumParams['selectProduct'] != 'no_thanks') { require_once 'CRM/Contribute/DAO/Product.php'; $productDAO =& new CRM_Contribute_DAO_Product(); $productDAO->id = $premiumParams['selectProduct']; $productDAO->find(true); $periodType = $productDAO->period_type; require_once 'CRM/Utils/Date.php'; $params = array('product_id' => $premiumParams['selectProduct'], 'contribution_id' => $contribution->id, 'product_option' => $premiumParams['options_' . $premiumParams['selectProduct']], 'quantity' => 1, 'start_date' => CRM_Utils_Date::customFormat($startDate, '%Y%m%d'), 'end_date' => CRM_Utils_Date::customFormat($endDate, '%Y%m%d')); CRM_Contribute_BAO_Contribution::addPremium($params); } // process the custom data that is submitted or that came via the url $groupTree = $this->get('groupTree'); $customValues = $this->get('customGetValues'); $customValues = array_merge($this->_params, $customValues); require_once 'CRM/Core/BAO/CustomGroup.php'; CRM_Core_BAO_CustomGroup::postProcess($groupTree, $customValues); CRM_Core_BAO_CustomGroup::updateCustomData($groupTree, 'Contribution', $contribution->id); // next create the transaction record $params = array('entity_table' => 'civicrm_contribution', 'entity_id' => $contribution->id, 'trxn_date' => $now, 'trxn_type' => 'Debit', 'total_amount' => $result['gross_amount'], 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $result['gross_amount']), 'currency' => $this->_params['currencyID'], 'payment_processor' => $config->paymentProcessor, 'trxn_id' => $result['trxn_id']); require_once 'CRM/Contribute/BAO/FinancialTrxn.php'; $trxn =& CRM_Contribute_BAO_FinancialTrxn::create($params); // also create an activity history record require_once 'CRM/Utils/Money.php'; $params = array('entity_table' => 'civicrm_contact', 'entity_id' => $contactID, 'activity_type' => $contributionType->name, 'module' => 'CiviContribute', 'callback' => 'CRM_Contribute_Page_Contribution::details', 'activity_id' => $contribution->id, 'activity_summary' => 'Online - ' . CRM_Utils_Money::format($this->_params['amount']), 'activity_date' => $now); if (is_a(crm_create_activity_history($params), 'CRM_Core_Error')) { CRM_Core_Error::fatal("Could not create a system record"); } CRM_Core_DAO::transaction('COMMIT'); // finally send an email receipt if ($this->_values['is_email_receipt']) { list($displayName, $email) = CRM_Contact_BAO_Contact::getEmailDetails($contactID); $template =& CRM_Core_Smarty::singleton(); $subject = trim($template->fetch('CRM/Contribute/Form/Contribution/ReceiptSubject.tpl')); $message = $template->fetch('CRM/Contribute/Form/Contribution/ReceiptMessage.tpl'); $receiptFrom = '"' . $this->_values['receipt_from_name'] . '" <' . $this->_values['receipt_from_email'] . '>'; require_once 'CRM/Utils/Mail.php'; CRM_Utils_Mail::send($receiptFrom, $displayName, $email, $subject, $message, $this->_values['cc_receipt'], $this->_values['bcc_receipt']); } }