/** * Notifies the given user of a report problem * * @param User $recipient Message recipient * @param string $subject Message subject * @param string $body Message body */ protected function sendNotificationOfReport(User $recipient, $subject, $body) { $mailer = MailerFactory::getSystemDefaultMailer(); // set the subject of the email $mailer->setSubject($subject); // set the body of the email... $textOnly = EmailFormatter::isTextOnly($body); if ($textOnly) { $mailer->setTextBody($body); } else { $textBody = strip_tags(br2nl($body)); // need to create the plain-text part $mailer->setTextBody($textBody); $mailer->setHtmlBody($body); } // add the recipient... // first get all email addresses known for this recipient $recipientEmailAddresses = array($recipient->email1, $recipient->email2); $recipientEmailAddresses = array_filter($recipientEmailAddresses); // then retrieve first non-empty email address $recipientEmailAddress = array_shift($recipientEmailAddresses); // a MailerException is raised if $email is invalid, which prevents the call to send below $mailer->addRecipientsTo(new EmailIdentity($recipientEmailAddress)); // send the email $mailer->send(); }
/** * Send new password or link to user * * @param string $templateId Id of email template * @param array $additionalData additional params: link, url, password * @return array status: true|false, message: error message, if status = false and message = '' it means that send method has returned false */ public function sendEmailForPassword($templateId, array $additionalData = array()) { global $current_user, $app_strings; $mod_strings = return_module_language('', 'Users'); $result = array('status' => false, 'message' => ''); $emailTemplate = BeanFactory::getBean('EmailTemplates'); $emailTemplate->disable_row_level_security = true; if ($emailTemplate->retrieve($templateId) == '') { $result['message'] = $mod_strings['LBL_EMAIL_TEMPLATE_MISSING']; return $result; } $emailTemplate->body = $this->replaceInstanceVariablesInEmailTemplates($emailTemplate->body, $additionalData); // in case the email is text-only and $emailTemplate->body_html is not empty, use a local variable for the HTML // part to ignore the body_html property and prevent changing it on the EmailTemplate object $htmlBody = null; if ($emailTemplate->text_only != 1) { $emailTemplate->body_html = $this->replaceInstanceVariablesInEmailTemplates($emailTemplate->body_html, $additionalData); $htmlBody = $emailTemplate->body_html; } try { $mailer = MailerFactory::getSystemDefaultMailer(); // set the subject $mailer->setSubject($emailTemplate->subject); // set the plain-text body $mailer->setTextBody($emailTemplate->body); // set the HTML body... it will be null in the text-only case, but that's okay $mailer->setHtmlBody($htmlBody); // make sure there is at least one message part (but only if the current user is an admin)... // even though $htmlBody is already set, resetting it verifies that $mailer actually got it $textBody = $mailer->getTextBody(); $htmlBody = $mailer->getHtmlBody(); if ($current_user->is_admin && !$mailer->hasMessagePart($textBody) && !$mailer->hasMessagePart($htmlBody)) { throw new MailerException("No email body was provided", MailerException::InvalidMessageBody); } // get the recipient's email address $itemail = $this->emailAddress->getPrimaryAddress($this); if (!empty($itemail)) { // add the recipient $mailer->addRecipientsTo(new EmailIdentity($itemail)); // if send doesn't raise an exception then set the result status to true $mailer->send(); $result["status"] = true; // save the email record $email = new Email(); $email->team_id = 1; $email->to_addrs = ''; $email->type = 'archived'; $email->deleted = '0'; $email->name = $emailTemplate->subject; $email->description = $textBody; $email->description_html = $htmlBody; $email->from_addr = $mailer->getHeader(EmailHeaders::From)->getEmail(); $email->parent_type = 'User'; $email->date_sent = TimeDate::getInstance()->nowDb(); $email->modified_user_id = '1'; $email->created_by = '1'; $email->status = 'sent'; $email->save(); if (!isset($additionalData['link']) || $additionalData['link'] == false) { $this->setNewPassword($additionalData['password'], '1'); } } else { // this exception is ignored as part of the default case in the switch statement in the catch block // but it adds documentation as to what is happening throw new MailerException("There are no recipients", MailerException::FailedToSend); } } catch (MailerException $me) { switch ($me->getCode()) { case MailerException::FailedToConnectToRemoteServer: if ($current_user->is_admin) { // the smtp host may not be empty, but this is the best error message for now $result['message'] = $mod_strings['ERR_SERVER_SMTP_EMPTY']; } else { // status=failed to send, but no message is returned to non-admin users } break; case MailerException::InvalidMessageBody: // this exception will only be raised if the current user is an admin, so there is no need to // worry about catching it in a non-admin case and handling the error message accordingly // both the plain-text and HTML parts are empty, but this is the best error message for now $result['message'] = $app_strings['LBL_EMAIL_TEMPLATE_EDIT_PLAIN_TEXT']; break; default: // status=failed to send, but no message is returned break; } } return $result; }
protected function create_notification_email($notify_user) { return MailerFactory::getSystemDefaultMailer(); }
/** * Send an email to the assigned user of the job * * @param String $subject The Subject * @param String $body The Body of the email */ protected function sendEmail($subject, $body) { $mailTransmissionProtocol = "unknown"; /* @var $user User */ $user = BeanFactory::getBean('Users', $this->job->assigned_user_id); try { /* @var $mailer SmtpMailer */ $mailer = MailerFactory::getSystemDefaultMailer(); $mailTransmissionProtocol = $mailer->getMailTransmissionProtocol(); // add the recipient... $mailer->addRecipientsTo(new EmailIdentity($user->email1, $user->full_name)); // set the subject $mailer->setSubject($subject); $mailer->setHtmlBody($body); $mailer->send(); } catch (MailerException $me) { $message = $me->getMessage(); $GLOBALS["log"]->warn("Notifications: error sending e-mail (method: {$mailTransmissionProtocol}), (error: {$message})"); } }
/** * @param $data * @return bool */ public function run($data) { global $current_user; global $current_language; global $locale; $this->job->runnable_ran = true; $this->job->runnable_data = $data; $report_schedule_id = $data; require_once 'modules/Reports/schedule/ReportSchedule.php'; $reportSchedule = new ReportSchedule(); $scheduleInfo = $reportSchedule->getInfo($report_schedule_id); $GLOBALS["log"]->debug("-----> in Reports foreach() loop"); $savedReport = BeanFactory::getBean('Reports', $scheduleInfo['report_id']); $GLOBALS["log"]->debug("-----> Generating Reporter"); require_once 'modules/Reports/Report.php'; $reporter = new Report(from_html($savedReport->content)); $reporter->is_saved_report = true; $reporter->saved_report = $savedReport; $reporter->saved_report_id = $savedReport->id; $mod_strings = return_module_language($current_language, 'Reports'); // prevent invalid report from being processed if (!$reporter->is_definition_valid()) { $invalidFields = $reporter->get_invalid_fields(); $args = array($scheduleInfo['report_id'], implode(', ', $invalidFields)); $message = string_format($mod_strings['ERR_REPORT_INVALID'], $args); $GLOBALS["log"]->fatal("-----> {$message}"); $reportOwner = BeanFactory::retrieveBean('Users', $savedReport->assigned_user_id); if ($reportOwner) { require_once 'modules/Reports/utils.php'; $reportsUtils = new ReportsUtilities(); try { $reportsUtils->sendNotificationOfInvalidReport($reportOwner, $message); } catch (MailerException $me) { //@todo consider logging the error at the very least } } $this->job->failJob('Report field definition is invalid'); return false; } else { $GLOBALS["log"]->debug("-----> Reporter settings attributes"); $reporter->layout_manager->setAttribute("no_sort", 1); $GLOBALS["log"]->debug("-----> Reporter Handling PDF output"); require_once 'modules/Reports/templates/templates_tcpdf.php'; $reportFilename = template_handle_pdf($reporter, false); // get the recipient's data... // first get all email addresses known for this recipient $recipientEmailAddresses = array($current_user->email1, $current_user->email2); $recipientEmailAddresses = array_filter($recipientEmailAddresses); // then retrieve first non-empty email address $recipientEmailAddress = array_shift($recipientEmailAddresses); // get the recipient name that accompanies the email address $recipientName = $locale->formatName($current_user); $result = false; try { $GLOBALS["log"]->debug("-----> Generating Mailer"); $mailer = MailerFactory::getSystemDefaultMailer(); // set the subject of the email $subject = empty($savedReport->name) ? "Report" : $savedReport->name; $mailer->setSubject($subject); // add the recipient $mailer->addRecipientsTo(new EmailIdentity($recipientEmailAddress, $recipientName)); // attach the report, using the subject as the name of the attachment $charsToRemove = array("\r", "\n"); // remove these characters from the attachment name $attachmentName = str_replace($charsToRemove, "", $subject); // replace spaces with the underscores $attachmentName = str_replace(" ", "_", "{$attachmentName}.pdf"); $attachment = new Attachment($reportFilename, $attachmentName, Encoding::Base64, "application/pdf"); $mailer->addAttachment($attachment); // set the body of the email $body = $mod_strings["LBL_HELLO"]; if ($recipientName != "") { $body .= " {$recipientName}"; } $body .= ",\n\n" . $mod_strings["LBL_SCHEDULED_REPORT_MSG_INTRO"] . $savedReport->date_entered . $mod_strings["LBL_SCHEDULED_REPORT_MSG_BODY1"] . $savedReport->name . $mod_strings["LBL_SCHEDULED_REPORT_MSG_BODY2"]; $textOnly = EmailFormatter::isTextOnly($body); if ($textOnly) { $mailer->setTextBody($body); } else { $textBody = strip_tags(br2nl($body)); // need to create the plain-text part $mailer->setTextBody($textBody); $mailer->setHtmlBody($body); } $GLOBALS["log"]->debug("-----> Sending PDF via Email to [ {$recipientEmailAddress} ]"); $mailer->send(); $result = true; $GLOBALS["log"]->debug("-----> Send successful"); $reportSchedule->update_next_run_time($report_schedule_id, $scheduleInfo["next_run"], $scheduleInfo["time_interval"]); } catch (MailerException $me) { switch ($me->getCode()) { case MailerException::InvalidEmailAddress: $GLOBALS["log"]->info("No email address for {$recipientName}"); break; default: $GLOBALS["log"]->fatal("Mail error: " . $me->getMessage()); break; } } $GLOBALS["log"]->debug("-----> Removing temporary PDF file"); unlink($reportFilename); if ($result) { $this->job->succeedJob(); } return $result; } }
// imports all of the Mailer classes that are needed global $current_user; $test = false; if (isset($_REQUEST['mode']) && $_REQUEST['mode'] == 'test') { $test = true; } if (isset($_REQUEST['send_all']) && $_REQUEST['send_all'] == true) { $send_all = true; } else { $send_all = false; //if set to true email delivery will continue..to run until all email have been delivered. } $GLOBALS['log'] = LoggerManager::getLogger('SugarCRM'); $mailer = null; try { $mailer = MailerFactory::getSystemDefaultMailer(); } catch (MailerException $me) { $GLOBALS['log']->fatal("Email delivery error:" . $me->getMessage()); return; } $admin = Administration::getSettings(); if (isset($admin->settings['massemailer_campaign_emails_per_run'])) { $max_emails_per_run = $admin->settings['massemailer_campaign_emails_per_run']; } if (empty($max_emails_per_run)) { $max_emails_per_run = 500; //default } //save email copies? $massemailer_email_copy = 0; //default: save copies of the email.
/** * Sends the users password to the email address. * * @param string $user_id * @param string $password */ public function sendEmailPassword($user_id, $password) { $result = $GLOBALS['db']->query("SELECT email1, email2, first_name, last_name FROM users WHERE id='{$user_id}'"); $row = $GLOBALS['db']->fetchByAssoc($result); if (empty($row['email1']) && empty($row['email2'])) { $_SESSION['login_error'] = 'Please contact an administrator to setup up your email address associated to this account'; } else { $mailTransmissionProtocol = "unknown"; try { $mailer = MailerFactory::getSystemDefaultMailer(); $mailTransmissionProtocol = $mailer->getMailTransmissionProtocol(); // add the recipient... // first get all email addresses known for this recipient $recipientEmailAddresses = array($row["email1"], $row["email2"]); $recipientEmailAddresses = array_filter($recipientEmailAddresses); // then retrieve first non-empty email address $recipientEmailAddress = array_shift($recipientEmailAddresses); // get the recipient name that accompanies the email address $recipientName = "{$row["first_name"]} {$row["last_name"]}"; $mailer->addRecipientsTo(new EmailIdentity($recipientEmailAddress, $recipientName)); // override the From header $from = new EmailIdentity("*****@*****.**", "Sugar Authentication"); $mailer->setHeader(EmailHeaders::From, $from); // set the subject $mailer->setSubject("Sugar Token"); // set the body of the email... looks to be plain-text only $mailer->setTextBody("Your sugar session authentication token is: {$password}"); $mailer->send(); $GLOBALS["log"]->info("Notifications: e-mail successfully sent"); } catch (MailerException $me) { $message = $me->getMessage(); $GLOBALS["log"]->warn("Notifications: error sending e-mail (method: {$mailTransmissionProtocol}), (error: {$message})"); } } }
function send_workflow_alert(&$focus, $address_array, $alert_msg, &$admin, $alert_shell_array, $check_for_bridge = false, $alert_user_array = array()) { $invitePerson = false; $users = array(); $contacts = array(); // Handle inviting users/contacts to meetings/calls if ($focus->module_dir == "Calls" || $focus->module_dir == "Meetings") { if ($check_for_bridge == true && !empty($focus->bridge_object)) { // we are inviting people $invitePerson = true; } } if ($alert_shell_array['source_type'] == "System Default") { get_invite_email($focus, $admin, $address_array, $invitePerson, $alert_msg, $alert_shell_array); } elseif ($alert_shell_array['source_type'] == "Custom Template" && $invitePerson == true) { // you are using a custom template and this is a meeting/call child invite get_invite_email($focus, $admin, $address_array, $invitePerson, $alert_msg, $alert_shell_array); } else { $mailTransmissionProtocol = "unknown"; try { $mailer = MailerFactory::getSystemDefaultMailer(); $mailer->getConfig()->setEncoding(Encoding::Base64); $mailTransmissionProtocol = $mailer->getMailTransmissionProtocol(); foreach ($address_array['to'] as $userInfo) { $mailer->addRecipientsTo(new EmailIdentity($userInfo['address'], $userInfo['name'])); if ($invitePerson == true) { populate_usr_con_arrays($userInfo, $users, $contacts); } } foreach ($address_array['cc'] as $userInfo) { $mailer->addRecipientsCc(new EmailIdentity($userInfo['address'], $userInfo['name'])); if ($invitePerson == true) { populate_usr_con_arrays($userInfo, $users, $contacts); } } foreach ($address_array['bcc'] as $userInfo) { $mailer->addRecipientsBcc(new EmailIdentity($userInfo['address'], $userInfo['name'])); if ($invitePerson == true) { populate_usr_con_arrays($userInfo, $users, $contacts); } } if ($invitePerson == true) { // Handle inviting users/contacts to meetings/calls if (!empty($address_array['invite_only'])) { foreach ($address_array['invite_only'] as $userInfo) { populate_usr_con_arrays($userInfo, $users, $contacts); } } // use the user_arr & contact_arr to add these people to the meeting $focus->users_arr = $users; $focus->contacts_arr = $contacts; invite_people($focus); } // add the message content to the mailer // return: true=encountered an error; false=no errors $error = create_email_body($focus, $mailer, $admin, $alert_msg, $alert_shell_array, "", $alert_user_array); if ($error) { throw new MailerException("Failed to add message content", MailerException::InvalidMessageBody); } $mailer->send(); } catch (MailerException $me) { $message = $me->getMessage(); $GLOBALS["log"]->warn("Notifications: error sending e-mail (method: {$mailTransmissionProtocol}), (error: {$message})"); } } }
/** * send reminders * @param SugarBean $bean * @param Administration $admin *use is deprecated* * @param array $recipients * @return boolean */ protected function sendReminders(SugarBean $bean, Administration $admin, $recipients) { if (!empty($_SESSION["authenticated_user_language"])) { $currentLanguage = $_SESSION["authenticated_user_language"]; } else { $currentLanguage = $GLOBALS["sugar_config"]["default_language"]; } $user = BeanFactory::getBean('Users', $bean->created_by); $xtpl = new XTemplate(get_notify_template_file($currentLanguage)); $xtpl = $this->setReminderBody($xtpl, $bean, $user); $templateName = "{$GLOBALS["beanList"][$bean->module_dir]}Reminder"; $xtpl->parse($templateName); $xtpl->parse("{$templateName}_Subject"); $mailTransmissionProtocol = "unknown"; try { $mailer = MailerFactory::getSystemDefaultMailer(); $mailTransmissionProtocol = $mailer->getMailTransmissionProtocol(); // set the subject of the email $subject = $xtpl->text("{$templateName}_Subject"); $mailer->setSubject($subject); // set the body of the email $body = trim($xtpl->text($templateName)); $textOnly = EmailFormatter::isTextOnly($body); if ($textOnly) { $mailer->setTextBody($body); } else { $textBody = strip_tags(br2nl($body)); // need to create the plain-text part $mailer->setTextBody($textBody); $mailer->setHtmlBody($body); } foreach ($recipients as $recipient) { // reuse the mailer, but process one send per recipient $mailer->clearRecipients(); $mailer->addRecipientsTo(new EmailIdentity($recipient["email"], $recipient["name"])); $mailer->send(); } } catch (MailerException $me) { $message = $me->getMessage(); switch ($me->getCode()) { case MailerException::FailedToConnectToRemoteServer: $GLOBALS["log"]->fatal("Email Reminder: error sending email, system smtp server is not set"); break; default: $GLOBALS["log"]->fatal("Email Reminder: error sending e-mail (method: {$mailTransmissionProtocol}), (error: {$message})"); break; } return false; } return true; }