/** * Save email to a folder (via IMAP) * * This function will open an IMAP stream using the email * credentials previously specified, and will save the email * to a specified folder. Parameter is the folder name (ie, Sent) * if nothing was specified it will be saved in the inbox. * * @author David Tkachuk <http://davidrockin.com/> */ public function copyToFolder($folderPath = "SendByWebsite") { $message = $this->MIMEHeader . $this->MIMEBody; //$path = "";//"INBOX" . (isset($folderPath) && !is_null($folderPath) ? ".".$folderPath : ""); // Location to save the email $imapStream = imap_open("{imap.mail.hostpoint.ch:143/notls}SendByWebsite", $this->Username, $this->Password); /* $arr = imap_getmailboxes($imapStream, "{imap.mail.hostpoint.ch:143}", "*"); Use this to find the Folder to save the sent email to if (is_array($arr)) { foreach ($arr as $key => $val) { echo "($key) "; echo imap_utf7_decode($val->name) . ","; echo "'" . $val->delimiter . "',"; echo $val->attributes . "<br />\n"; } } else { echo "imap_getmailboxes failed: " . imap_last_error() . "\n"; } */ if ($imapStream != false) { imap_append($imapStream, "{imap.mail.hostpoint.ch:143/notls" . $folderPath . "}", $message); imap_close($imapStream); } }
/** * Create a multipart message with subparts * * @param resource $imap_stream * @param string $mailbox */ function create_multipart_message($imap_stream, $mailbox) { global $users, $domain; $envelope["from"] = "*****@*****.**"; $envelope["to"] = "{$users['0']}@{$domain}"; $envelope["subject"] = "Test msg 1"; $part1["type"] = TYPEMULTIPART; $part1["subtype"] = "mixed"; $part2["type"] = TYPETEXT; $part2["subtype"] = "plain"; $part2["description"] = "imap_mail_compose() function"; $part2["contents.data"] = "message 1:xxxxxxxxxxxxxxxxxxxxxxxxxx"; $part3["type"] = TYPETEXT; $part3["subtype"] = "plain"; $part3["description"] = "Example"; $part3["contents.data"] = "message 2:yyyyyyyyyyyyyyyyyyyyyyyyyy"; $file_handle = fopen(__FILE__, 'r+'); $file_size = 1; $part4["type"] = TYPEAPPLICATION; $part4["encoding"] = ENCBASE64; $part4["subtype"] = "octet-stream"; $part4["description"] = 'Test'; $part4['disposition.type'] = 'attachment'; $part4['disposition'] = array('filename' => 'Test'); $part4['type.parameters'] = array('name' => 'Test'); $part4["contents.data"] = base64_encode(fread($file_handle, 1)); $body[1] = $part1; $body[2] = $part2; $body[3] = $part3; $body[4] = $part4; $msg = imap_mail_compose($envelope, $body); if (imap_append($imap_stream, $mailbox, $msg) === false) { echo imap_last_error() . "\n"; echo "TEST FAILED : could not append new message to mailbox '{$mailbox}'\n"; exit; } }
function store_email_into_folder($msg, $folder = 'SentFromDolibarr') { global $user, $db; $mailboxconfig = new Usermailboxconfig($db); $mailboxconfig->fetch_from_user($user->id); $user->mailbox_imap_login = $mailboxconfig->mailbox_imap_login; $user->mailbox_imap_password = $mailboxconfig->mailbox_imap_password; $user->mailbox_imap_host = $mailboxconfig->mailbox_imap_host; $user->mailbox_imap_port = $mailboxconfig->mailbox_imap_port; $user->mailbox_imap_ssl = $mailboxconfig->mailbox_imap_ssl; $user->mailbox_imap_ssl_novalidate_cert = $mailboxconfig->mailbox_imap_ssl_novalidate_cert; $user->mailbox_imap_ref = $mailboxconfig->get_ref(); $user->mailbox_imap_connector_url = $mailboxconfig->get_connector_url(); $mbox = imap_open($user->mailbox_imap_connector_url . $folder, $user->mailbox_imap_login, $user->mailbox_imap_password); $check = imap_check($mbox); $before = $check->Nmsgs; $result = imap_append($mbox, $user->mailbox_imap_connector_url . $folder, $msg); $check = imap_check($mbox); $after = $check->Nmsgs; if ($result == FALSE) { if (imap_createmailbox($mbox, imap_utf7_encode($user->mailbox_imap_ref . $folder))) { $mbox = imap_open($user->mailbox_imap_connector_url . $folder, $user->mailbox_imap_login, $user->mailbox_imap_password); $check = imap_check($mbox); $before = $check->Nmsgs; $result = imap_append($mbox, $user->mailbox_imap_connector_url . $folder, $msg); $check = imap_check($mbox); $after = $check->Nmsgs; } } imap_close($mbox); }
/** * Appends a message to a mailbox * @param string $mailbox The mailbox to append the message to * @param zibo\library\mail\Message $message The message to append * @return null * @throws zibo\library\mail\exception\MailException when th message could not be appended to the mailbox */ public function appendMessage($mailbox, Message $message) { $parser = new MessageParser($message); $message = 'Subject: ' . $parser->getSubject() . "\r\n"; $message .= implode("\r\n", $parser->getHeaders()); $message .= "\r\n\r\n" . $parser->getBody(); $connection = $this->getConnection($mailbox); $stream = $connection->getStream(); $reference = $connection->getReference(); if (!imap_append($stream, $reference, $message)) { throw new MailException('Could not append the message to ' . $mailbox . ': ' . imap_last_error()); } }
/** * @name: addmail * Wenn die Mails nicht per imap geholt werden, fuege die Mail mit allen header-Daten aus $xarf als Mail ein. * * @param $xarf-report * @return Boolean */ public function addmail($xarf) { $config = $this->config; preg_match('/subject: (.*)/im', $xarf, $subject); $this->subject = $subject[1]; $xarf = str_replace("\n", "\r\n", $xarf); $check = imap_check($this->connection); $add = imap_append($this->connection, '{' . $config['server'] . ':' . $config['port'] . '/' . $config['conntyp'] . '/' . $config['extras'] . '}' . $config['ordner'], stripslashes($xarf)); $check1 = imap_check($this->connection); if ($check < $check1 && $add == 1) { $return = 0; } else { $return = 1; } return $return; }
public function appendMessage($message, $box = 'IMAP.Sent', $flags = null, $messageId = null) { $mailbox = $this->imap->reopen($box); $date = null; if ($messageId) { //var_dump($messageId); $messageId = imap_uid($this->connection, $messageId); //var_dump($messageId); $headerinfo = imap_headerinfo($this->connection, $messageId); $date = date('d-M-Y H:i:s O', $headerinfo->udate); } $result = imap_append($this->connection, $mailbox, $message, $flags); $this->fullName = $this->imap->reopen($this->name); return $result; }
public function saveMailToImap($content, $folder = 'INBOX') { imap_append($this->imapStream, $this->getMailbox() . $folder, $content); }
/** * Function sends mail */ public function send() { $currentUserModel = Users_Record_Model::getCurrentUserModel(); $rootDirectory = vglobal('root_directory'); $mailer = Emails_Mailer_Model::getInstance(); $mailer->IsHTML(true); $fromEmail = $this->getFromEmailAddress(); $replyTo = $currentUserModel->get('email1'); $userName = $currentUserModel->getName(); // To eliminate the empty value of an array $toEmailInfo = array_filter($this->get('toemailinfo')); $toMailNamesList = array_filter($this->get('toMailNamesList')); foreach ($toMailNamesList as $id => $emailData) { foreach ($emailData as $key => $email) { if ($toEmailInfo[$id]) { array_push($toEmailInfo[$id], $email['value']); } } } $emailsInfo = array(); foreach ($toEmailInfo as $id => $emails) { foreach ($emails as $key => $value) { array_push($emailsInfo, $value); } } $toFieldData = array_diff(explode(',', $this->get('saved_toid')), $emailsInfo); $toEmailsData = array(); $i = 1; foreach ($toFieldData as $value) { $toEmailInfo['to' . $i++] = array($value); } $attachments = $this->getAttachmentDetails(); $status = false; // Merge Users module merge tags based on current user. $mergedDescription = getMergedDescription($this->get('description'), $currentUserModel->getId(), 'Users'); $mergedSubject = getMergedDescription($this->get('subject'), $currentUserModel->getId(), 'Users'); foreach ($toEmailInfo as $id => $emails) { $mailer->reinitialize(); $mailer->ConfigSenderInfo($fromEmail, $userName, $replyTo); $old_mod_strings = vglobal('mod_strings'); $description = $this->get('description'); $subject = $this->get('subject'); $parentModule = $this->getEntityType($id); if ($parentModule) { $currentLanguage = Vtiger_Language_Handler::getLanguage(); $moduleLanguageStrings = Vtiger_Language_Handler::getModuleStringsFromFile($currentLanguage, $parentModule); vglobal('mod_strings', $moduleLanguageStrings['languageStrings']); if ($parentModule != 'Users') { // Apply merge for non-Users module merge tags. $description = getMergedDescription($mergedDescription, $id, $parentModule); $subject = getMergedDescription($mergedSubject, $id, $parentModule); } else { // Re-merge the description for user tags based on actual user. $description = getMergedDescription($description, $id, 'Users'); $subject = getMergedDescription($mergedSubject, $id, 'Users'); vglobal('mod_strings', $old_mod_strings); } } if (strpos($description, '$logo$')) { $description = str_replace('$logo$', "<img src='cid:logo' />", $description); $logo = true; } foreach ($emails as $email) { $mailer->Body = ''; if ($parentModule) { $mailer->Body = $this->getTrackImageDetails($id, $this->isEmailTrackEnabled()); } $mailer->Body .= $description; $mailer->Signature = str_replace(array('\\r\\n', '\\n'), '<br>', $currentUserModel->get('signature')); if ($mailer->Signature != '') { $mailer->Body .= '<br><br>' . decode_html($mailer->Signature); } $mailer->Subject = $subject; $mailer->AddAddress($email); //Adding attachments to mail if (is_array($attachments)) { foreach ($attachments as $attachment) { $fileNameWithPath = $rootDirectory . $attachment['path'] . $attachment['fileid'] . "_" . $attachment['attachment']; if (is_file($fileNameWithPath)) { $mailer->AddAttachment($fileNameWithPath, $attachment['attachment']); } } } if ($logo) { //While sending email template and which has '$logo$' then it should replace with company logo $mailer->AddEmbeddedImage(dirname(__FILE__) . '/../../../layouts/vlayout/skins/images/logo_mail.jpg', 'logo', 'logo.jpg', 'base64', 'image/jpg'); } $ccs = array_filter(explode(',', $this->get('ccmail'))); $bccs = array_filter(explode(',', $this->get('bccmail'))); if (!empty($ccs)) { // SalesPlatform.ru begin foreach ($ccs as $cc) { $mailer->AddCC($idn->encode($cc)); } //$mailer->AddCC($cc); // SalesPlatform.ru end } if (!empty($bccs)) { // SalesPlatform.ru begin foreach ($bccs as $bcc) { $mailer->AddBCC($idn->encode($bcc)); } //$mailer->AddBCC($bcc); // SalesPlatform.ru end } } // SalesPlatform.ru begin $idn = new idna_convert(); $query = "select * from vtiger_systems where server_type=?"; $params = array('email'); //SalesPlatform begin fix bug $adb = PearDatabase::getInstance(); //SalesPaltform.ru end $result = $adb->pquery($query, $params); $server_username = $adb->query_result($result, 0, 'server_username'); $from_name_db = $adb->query_result($result, 0, 'from_name'); $server_port = $adb->query_result($result, 0, 'server_port'); $server_tls = $adb->query_result($result, 0, 'server_tls'); if ($server_username != '') { $server_username = $idn->encode($server_username); $mailer->Username = $server_username; } if (isset($from_name_db) && $from_name_db != '') { $mailer->FromName = decode_html($from_name_db); } $from_email = $adb->query_result($result, 0, 'from_email_field'); if ($from_email != '') { $mailer->From = $idn->encode($from_email); } if (!empty($server_port) && $server_port != 0) { $mailer->Port = $server_port; } if (!empty($server_tls) && $server_tls != 'no') { $mailer->SMTPSecure = $server_tls; } $use_sendmail = $adb->query_result($result, 0, 'use_sendmail'); if ($use_sendmail == "on") { $mailer->IsSendmail(); } else { $mailer->IsSMTP(); } // SalesPlatform.ru end $status = $mailer->Send(true); if (!$status) { $status = $mailer->getError(); } else { $mailString = $mailer->getMailString(); $mailBoxModel = MailManager_Mailbox_Model::activeInstance(); $folderName = $mailBoxModel->folder(); if (!empty($folderName) && !empty($mailString)) { $connector = MailManager_Connector_Connector::connectorWithModel($mailBoxModel, ''); imap_append($connector->mBox, $connector->mBoxUrl . $folderName, $mailString, "\\Seen"); } } } return $status; }
/** * This method provides the functionality to import MIME messages into the server * using the {@link imap_append} method. * * @param string $dest_mb * The destination mailbox where the messages will be imported to. * @param array $messages * An array of MIME messages to import. * * @return BOOL * @access public * @see imap_append * @tutorial http://www.smilingsouls.net/Mail_IMAP?content=Mail_IMAP_ManageMB/importMail */ function importMail($dest_mb, $messages) { if (is_array($messages)) { $opt = isset($this->option['append']) ? $this->option['append'] : NULL; foreach ($messages as $msg) { if (!@imap_append($this->mailbox, $this->mailboxInfo['host'] . $dest_mb, $msg, $opt)) { $this->error->push(Mail_IMAPv2_ERROR, 'error', NULL, 'Unable to import message, imap_append failed!'); $ret = FALSE; } } if (!isset($ret)) { $ret = TRUE; } } else { $this->error->push(Mail_IMAPv2_ERROR_ARGUMENT_REQUIRES_ARRAY, 'error', array('arg' => '$messages')); $ret = FALSE; } return $ret; }
function sendToServerThroughIMAP($server, $with_ssl, $transport, $ssl_port, $box, $from, $password, $content) { $password = self::ENCRYPT_DECRYPT($password); $ssl = $with_ssl == '1' || $transport == 'ssl' ? '/ssl' : ''; $tls = $transport == 'tls' ? '/tls' : ''; $no_valid_cert = $ssl == '' && $tls == '' ? '/novalidate-cert' : ''; $port = $with_ssl == '1' ? ':' . $ssl_port : ''; $mail_box = isset($box) ? $box : 'INBOX.Sent'; $connection = '{' . $server . $port . '/imap' . $no_valid_cert . $ssl . $tls . '}' . $mail_box; $stream = imap_open($connection, $from, $password); if ($stream !== FALSE) { imap_append($stream, $connection, $content); imap_close($stream); } }
public function create($URI, &$data) { switch ($URI['concept']) { case 'labeled': if (isset($data['folderName']) && isset($data['messageNumber']) && isset($data['labelId'])) { $this->mbox = $this->open_mbox($data['folderName']); imap_setflag_full($this->mbox, $data['messageNumber'], '$Label' . $data['labelId'], ST_UID); return array('id' => $data['folderName'] . '/' . $data['messageNumber'] . '#' . $data['labelId']); } return array(); case 'followupflagged': //deve ser gravado primeiro no imap, obtido o message-id e, depois gravado no banco if (isset($data['folderName']) && isset($data['messageNumber'])) { $this->mbox = $this->open_mbox($data['folderName']); $s = imap_setflag_full($this->mbox, $data['messageNumber'], '$Followupflagged', ST_UID); $headers = imap_fetch_overview($this->mbox, $data['messageNumber'], FT_UID); $data['messageId'] = $headers[0]->message_id; /* * TODO * Verificar erro ao tentar setar uma flag com o limite de flags atingido * onde o status retornado pelo imap_setflag_full é true mesmo não sendo possível * a inserção da flag. */ return $s && imap_last_error() != 'Too many user flags in mailbox' ? $data : array(); } else { if (isset($data['messageId'])) { /** * Busca pela mensagem com o messageId dado. Se uma pasta foi passada, busca nela, * senão busca em todas. */ $folders = array(); if (isset($data['folderName'])) { $folders = array($data['folderName']); } else { $folder_list = $this->get_folders_list(); foreach ($folder_list as $folder) { if (isset($folder['folder_id'])) { $folders[] = $folder['folder_id']; } } } foreach ($folders as $folder) { $this->mbox = $this->open_mbox($folder); if ($messages = imap_search($this->mbox, 'ALL TEXT "Message-Id: ' . $data['messageId'] . '"', SE_UID)) { $s = imap_setflag_full($this->mbox, $messages[0], '$Followupflagged', ST_UID); /** * Stop searching in all folders */ return $data; } } } } return array(); case 'message': require_once ROOTPATH . '/library/uuid/class.uuid.php'; $GLOBALS['phpgw_info']['flags'] = array('noheader' => true, 'nonavbar' => true, 'currentapp' => 'expressoMail', 'enable_nextmatchs_class' => True); $return = array(); require_once dirname(__FILE__) . '/../../services/class.servicelocator.php'; $mailService = ServiceLocator::getService('mail'); $msg_uid = $data['msg_id']; $body = $data['body']; $body = str_replace("<", "&yzwkx;", $body); //Alterar as Entities padrão das tags < > para compatibilizar com o Expresso $body = str_replace(">", "&xzwky;", $body); $body = str_replace("%nbsp;", " ", $body); $body = html_entity_decode($body, ENT_QUOTES, 'ISO-8859-1'); $body = str_replace("&yzwkx;", "<", $body); $body = str_replace("&xzwky;", ">", $body); $folder = mb_convert_encoding($data['folder'], "UTF7-IMAP", "ISO-8859-1, UTF-8"); $folder = @preg_replace('/INBOX[\\/.]/i', "INBOX" . $this->imap_delimiter, $folder); /** * Gera e preenche o field Message-Id do header */ $mailService->addHeaderField('Message-Id', UUID::generate(UUID::UUID_RANDOM, UUID::FMT_STRING) . '@Draft'); $mailService->addHeaderField('Reply-To', mb_convert_encoding($data['input_reply_to'], 'ISO-8859-1', 'UTF-8,ISO-8859-1')); $mailService->addHeaderField('Date', date("d-M-Y H:i:s")); $mailService->addTo(mb_convert_encoding($data['input_to'], 'ISO-8859-1', 'UTF-8,ISO-8859-1')); $mailService->addCc(mb_convert_encoding($data['input_cc'], 'ISO-8859-1', 'UTF-8,ISO-8859-1')); $mailService->addBcc(mb_convert_encoding($data['input_cco'], 'ISO-8859-1', 'UTF-8,ISO-8859-1')); $mailService->setSubject(mb_convert_encoding($data['input_subject'], 'ISO-8859-1', 'UTF-8,ISO-8859-1')); if (isset($data['input_important_message'])) { $mailService->addHeaderField('Importance', 'High'); } if (isset($data['input_return_receipt'])) { $mailService->addHeaderField('Disposition-Notification-To', Config::me('mail')); } $this->rfc2397ToEmbeddedAttachment($mailService, $body); $isHTML = isset($data['type']) && $data['type'] == 'html' ? true : false; if (!$body) { $body = ' '; } $mbox_stream = $this->open_mbox($folder); $attachment = json_decode($data['attachments'], TRUE); if (!empty($attachment)) { foreach ($attachment as &$value) { if ((int) $value > 0) { $att = Controller::read(array('id' => $value, 'concept' => 'mailAttachment')); if ($att['disposition'] == 'embedded' && $isHTML) { $body = str_replace('"../prototype/getArchive.php?mailAttachment=' . $att['id'] . '"', '"' . mb_convert_encoding($att['name'], 'ISO-8859-1', 'UTF-8,ISO-8859-1') . '"', $body); $mailService->addStringImage(base64_decode($att['source']), $att['type'], mb_convert_encoding($att['name'], 'ISO-8859-1', 'UTF-8,ISO-8859-1')); } else { $mailService->addStringAttachment(base64_decode($att['source']), mb_convert_encoding($att['name'], 'ISO-8859-1', 'UTF-8,ISO-8859-1'), $att['type'], 'base64', isset($att['disposition']) ? $att['disposition'] : 'attachment'); } unset($att); } else { $value = json_decode($value, true); switch ($value['type']) { case 'imapPart': $att = $this->getForwardingAttachment($value['folder'], $value['uid'], $value['part']); if (strstr($body, 'src="./inc/get_archive.php?msgFolder=' . $value['folder'] . '&msgNumber=' . $value['uid'] . '&indexPart=' . $value['part'] . '"') !== false) { $body = str_ireplace('src="./inc/get_archive.php?msgFolder=' . $value['folder'] . '&msgNumber=' . $value['uid'] . '&indexPart=' . $value['part'] . '"', 'src="' . $att['name'] . '"', $body); $mailService->addStringImage($att['source'], $att['type'], mb_convert_encoding($att['name'], 'ISO-8859-1', 'UTF-8,ISO-8859-1')); } else { $mailService->addStringAttachment($att['source'], mb_convert_encoding($att['name'], 'ISO-8859-1', 'UTF-8,ISO-8859-1'), $att['type'], 'base64', isset($att['disposition']) ? $att['disposition'] : 'attachment'); } unset($att); break; case 'imapMSG': $mbox_stream = $this->open_mbox($value['folder']); $rawmsg = $this->getRawHeader($value['uid']) . "\r\n\r\n" . $this->getRawBody($value['uid']); $mailService->addStringAttachment($rawmsg, mb_convert_encoding(base64_decode($value['name']), 'ISO-8859-1', 'UTF-8,ISO-8859-1'), 'message/rfc822', '7bit', 'attachment'); unset($rawmsg); break; default: break; } } } } if ($isHTML) { $mailService->setBodyHtml($body); } else { $mailService->setBodyText(mb_convert_encoding($body, 'ISO-8859-1', 'UTF-8,ISO-8859-1')); } if (imap_append($mbox_stream, "{" . $this->imap_server . ":" . $this->imap_port . "}" . $folder, $mailService->getMessage(), "\\Seen \\Draft")) { $status = imap_status($mbox_stream, "{" . $this->imap_server . ":" . $this->imap_port . "}" . $folder, SA_UIDNEXT); $return['id'] = $status->uidnext - 1; if ($data['uidsSave']) { $this->delete_msgs(array('folder' => $folder, 'msgs_number' => $data['uidsSave'])); } Logger::info('expressomail', 'SAVEMSG', 'ID: ' . $return['id'] . ' # ' . 'Subject:' . $data['input_subject']); } return $return; } }
/** * Create a new note with a given subject and body text. * * @param string $Note_Subject The note subject. * @param string $Note_Text The note body text. * * @return boolean <u>Description:</u><br>Returns TRUE if the note was created successfully and FALSE if the creation failed */ function Create_New_Note($Note_Subject, $Note_Text) { $currenttime = strftime('%a, %d %b %Y %H:%M:%S %z'); $note = "Date: {$currenttime}\nFrom: {$this->email}\nX-Uniform-Type-Identifier: com.apple.mail-note\nContent-Type: text/html;\nSubject: {$Note_Subject}\n\n{$Note_Text}"; return imap_append($this->imap, "{imap.mail.me.com:993/imap/ssl}Notes", $note); }
public function save_to_outbox() { $mbox = @imap_open("{" . $this->imap_config['host'] . ":" . $this->imap_config['port'] . "/imap/ssl}", $this->config['mail_from_mailbox'], $this->config['smtp_password']); if (!$mbox) { return 'Невозможно сохранить письмо в исходящих, проверьте настройки imap или соединение с интернетом'; die; } $check = imap_check($mbox); imap_append($mbox, "{" . $this->imap_config['host'] . ":" . $this->imap_config['port'] . "}&BB4EQgQ,BEAEMAQyBDsENQQ9BD0ESwQ1-", $this->letter, "\\Seen"); $check = imap_check($mbox); imap_close($mbox); return true; }
/** * Sends mail via SMTP using PhpSMTP (Author: * Chris Ryan). Returns bool. Returns false if there is a * bad MAIL FROM, RCPT, or DATA input. * @access private * @return bool */ function SmtpSend($header, $body) { include_once $this->PluginDir . "class.smtp.php"; $error = ""; $bad_rcpt = array(); $errorx = ''; if (!$this->SmtpConnect()) { return false; } if ($this->SMIME) { $header = ''; $body = $this->Body; } $smtp_from = $this->Sender == "" ? $this->From : $this->Sender; if (!$this->smtp->Mail($smtp_from)) { $error = $this->Lang("from_failed") . $smtp_from; $this->SetError($error); $this->smtp->Reset(); return false; } // Attempt to send attach all recipients $to_count = count($this->to); for ($i = 0; $i < $to_count; ++$i) { if (!$this->smtp->Recipient($this->to[$i][0])) { $bad_rcpt[] = $this->to[$i][0]; } } $cc_count = count($this->cc); for ($i = 0; $i < $cc_count; ++$i) { if (!$this->smtp->Recipient($this->cc[$i][0])) { $bad_rcpt[] = $this->cc[$i][0]; } } $bcc_count = count($this->bcc); for ($i = 0; $i < $bcc_count; ++$i) { if (!$this->smtp->Recipient($this->bcc[$i][0])) { $bad_rcpt[] = $this->bcc[$i][0]; } } if ($errorx != '') { $error = $errorx; $error = $this->Lang("recipients_failed") . ' ' . $errorx; $this->SetError($error); $this->smtp->Reset(); return false; } if (count($bad_rcpt) > 0) { //Postfix version 2.3.8-2 $smtp_code_error = substr($this->smtp->error['smtp_msg'], 0, 5); //Postfix version 2.1.5-9 $array_error = explode(":", $this->smtp->error['smtp_msg']); $bad_rcpt_count = count($bad_rcpt); for ($i = 0; $i < $bad_rcpt_count; ++$i) { if ($i != 0) { $error .= ", "; } $error .= $bad_rcpt[$i]; } if ($smtp_code_error == '5.7.1' || trim($array_error[2]) == 'Access denied') { $error = $this->Lang("not_allowed") . $error; } else { $error = $this->Lang("recipients_failed") . $error; } $this->SetError($error); $this->smtp->Reset(); return false; } // Vai verificar se deve cifrar a msg ...... if (count($this->Certs_crypt) > 0) { // Vai cifrar a msg antes de enviar ...... include_once "../security/classes/CertificadoB.php"; $teste1 = array(); $aux_cifra1 = $header . $body; // Início relocação dos headers // Esta relocação dos headers podem causar problemas. $match = 0; $pattern = '/^Disposition\\-Notification\\-To:.*\\n/m'; $match = preg_match($pattern, $aux_cifra1, $teste1); if (!empty($match)) { $aux_cifra1 = preg_replace($pattern, '', $aux_cifra1, 1); // retira o Disposition-Notification-To $match = 0; $teste2 = array(); $pattern = '/^MIME\\-Version:.*\\n/m'; $match = preg_match($pattern, $aux_cifra1, $teste2); $aux_cifra1 = preg_replace($pattern, $teste1[0] . $teste2[0], $aux_cifra1, 1); // Adiciona Disposition-Notification-To logo acima de MIME-Version } // Fim relocação dos headers // Vai partir em duas partes a msg. A primeira parte he a dos headers, e a segunda vai ser criptografada ... $pos_content_type = strpos($aux_cifra1, 'Content-Type:'); $pos_MIME_Version = strpos($aux_cifra1, 'MIME-Version: 1.0' . chr(0xd) . chr(0xa)); $valx_len = 19; if ($pos_MIME_Version === False) { $pos_MIME_Version = strpos($aux_cifra1, 'MIME-Version: 1.0' . chr(0xa)); $valx_len = 18; } if ($pos_MIME_Version >= $pos_content_type) { // nao deve enviar a msg..... O header MIME-Version com posicao invalida ...... $this->SetError('Formato dos headers da msg estao invalidos.(CD-17) - A'); $this->smtp->Reset(); return false; } $aux_cifra2 = array(); $aux_cifra2[] = substr($aux_cifra1, 0, $pos_MIME_Version - 1); $aux_cifra2[] = substr($aux_cifra1, $pos_MIME_Version + $valx_len); /* // este explode pode ser fonte de problemas ....... $aux_cifra2 = explode('MIME-Version: 1.0' . chr(0x0A), $aux_cifra1); // Pode ocorrer um erro se nao tiver o header MIME-Version ..... if(count($aux_cifra2) != 2 ) { $aux_cifra2 = explode('MIME-Version: 1.0' . chr(0x0D) . chr(0x0A), $aux_cifra1); if(count($aux_cifra2) != 2 ) { // nao deve enviar a msg..... nao tem o header MIME-Version ...... $this->SetError('Formato dos headers da msg estao invalidos.(CD-17) - ' . count($aux_cifra2)); $this->smtp->Reset(); return false; } } */ $certificado = new certificadoB(); $h = array(); $aux_body = $certificado->encriptar($aux_cifra2[1], $this->Certs_crypt, $h); if (!$aux_body) { $this->SetError('Ocorreu um erro. A msg nao foi enviada. (CD-18)'); $this->smtp->Reset(); return false; } // salvar sem cifra...... //$smtpSent = $this->smtp->Data($aux_cifra2[0] . $aux_body); // salva a msg sifrada. neste caso deve ter sido adicionado o certificado do autor da msg...... $header = $aux_cifra2[0]; $body = $aux_body; $smtpSent = $this->smtp->Data($header . $body); } else { $smtpSent = $this->smtp->Data($header . $body); } if (!$smtpSent) { $this->SetError($this->Lang("data_not_accepted") . ' ' . $this->smtp->error['error'] . ',' . $this->smtp->error['smtp_code'] . ',' . $this->smtp->error['smtp_msg']); $this->smtp->Reset(); return false; } if ($this->SMTPKeepAlive == true) { $this->smtp->Reset(); } else { $this->SmtpClose(); } if ($this->SaveMessageInFolder) { $username = $_SESSION['phpgw_info']['expressomail']['user']['userid']; $password = $_SESSION['phpgw_info']['expressomail']['user']['passwd']; $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer']; $imap_port = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort']; if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes') { $imap_options = '/tls/novalidate-cert'; } else { $imap_options = '/notls/novalidate-cert'; } $mbox_stream = imap_open("{" . $imap_server . ":" . $imap_port . $imap_options . "}" . $this->SaveMessageInFolder, $username, $password); ## # @AUTHOR Rodrigo Souza dos Santos # @DATE 2008/09/11 # @BRIEF Adding arbitrarily the BCC field. You may need to # check if this field already exists in the header. ## if (count($this->bcc) > 0) { $target = stripos($header, 'subject'); $header = substr($header, 0, $target) . $this->AddrAppend("Bcc", $this->bcc) . substr($header, $target); } $new_headerx = str_replace(chr(0xa), chr(0xd) . chr(0xa), $header); $new_bodyx = str_replace(chr(0xa), chr(0xd) . chr(0xa), $body); $new_header = str_replace(chr(0xd) . chr(0xd) . chr(0xa), chr(0xd) . chr(0xa), $new_headerx); $new_body = str_replace(chr(0xd) . chr(0xd) . chr(0xa), chr(0xd) . chr(0xa), $new_bodyx); if ($this->SaveMessageAsDraft) { imap_append($mbox_stream, "{" . $imap_server . ":" . $imap_port . "}" . $this->SaveMessageInFolder, $new_header . $new_body, "\\Seen \\Draft"); return true; } else { imap_append($mbox_stream, "{" . $imap_server . ":" . $imap_port . "}" . $this->SaveMessageInFolder, $new_header . $new_body, "\\Seen"); } } return $smtpSent; }
for ($i = 1; $i <= $da_no_msgs; $i++) { $obj = imap_header($src_mbox, $i); $msg_date = $obj->udate; $msg_date = getSentDate($src_mbox, $i); if (false) { print "msg_date = {$msg_date}\n"; $con = date("D, d M Y H:i:s", $msg_date); print "convert date back = {$con}\n"; exit; } if ($archive_date == -1 || $msg_date < $archive_date) { $contents = imap_fetchheader($src_mbox, $i) . "\r\n" . imap_body($src_mbox, $i, FT_PEEK); if ($debug) { print "\nappending msg {$i}: {$dest_server} {$dest_mbox} : {$msg_date} < {$archive_date}\n"; } if (imap_append($dest_mbox, $dst_imap_string . $dest_mailbox, $contents)) { setDestFlagsToSrcFlags($dest_mbox, $src_mbox, $i); if ($delete_src_msg == "true") { if ($debug) { print "delete_src_msg = {$delete_src_msg} - Deleting source message\n"; } if (!deletemsg($src_mbox, $i)) { print " WARNING message {$i} for {$src_username} on {$src_server} not deleted!!\n"; } } else { if ($debug) { print "delete_src_msg = {$delete_src_msg} - NOT deleting source message\n"; } } } else { print " WARNING message {$i} for {$src_username} on {$src_server} not appended to {$dest_server}\n";
function insert_email($source, $folder, $timestamp, $flags) { $username = $_SESSION['phpgw_info']['expressomail']['user']['userid']; $password = $_SESSION['phpgw_info']['expressomail']['user']['passwd']; $imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer']; $imap_port = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort']; $imap_options = '/notls/novalidate-cert'; $folder = mb_convert_encoding($folder, "UTF7-IMAP", "ISO-8859-1"); $mbox_stream = imap_open("{" . $imap_server . ":" . $imap_port . $imap_options . "}" . $folder, $username, $password); if (imap_last_error() === 'Mailbox already exists') { imap_createmailbox($mbox_stream, imap_utf7_encode("{" . $imap_server . "}" . $folder)); } if ($timestamp) { if (version_compare(PHP_VERSION, '5.3.2', '>=')) { $return['append'] = imap_append($mbox_stream, "{" . $imap_server . ":" . $imap_port . "}" . mb_convert_encoding($folder, "UTF7-IMAP", "ISO_8859-1"), $source, '', date('d-M-Y H:i:s O', $timestamp)); } else { $pdate = date_parse(date('r')); // pega a data atual do servidor (TODO: pegar a data da mensagem local) $timestamp += $pdate['zone'] * 60; //converte a data da mensagem para o fuso horário GMT 0. Isto é feito devido ao Expresso Mail armazenar a data no fuso horário GMT 0 e para exibi-la converte ela para o fuso horário local. /* TODO: o diretorio /tmp deve ser substituido pelo diretorio temporario configurado no setup */ $file = "/tmp/sess_" . $_SESSION['phpgw_session']['session_id']; $f = fopen($file, "w"); fputs($f, base64_encode($source)); fclose($f); $command = "python " . dirname(__FILE__) . "/../imap.py \"{$imap_server}\" \"{$imap_port}\" \"{$username}\" \"{$password}\" \"{$timestamp}\" \"{$folder}\" \"{$file}\""; $return['command'] = exec($command); } } else { $return['append'] = imap_append($mbox_stream, "{" . $imap_server . ":" . $imap_port . "}" . $folder, $source, "\\Seen"); } if (!empty($return['command'])) { list($result, $msg) = explode(':', $return['command']); if (strtoupper($result) === 'NO') { $return['error'] = $msg; return $return; } } $status = imap_status($mbox_stream, "{" . $this->imap_server . ":" . $this->imap_port . "}" . $folder, SA_UIDNEXT); $return['msg_no'] = $status->uidnext - 1; $return['error'] = ''; if (imap_last_error() && imap_last_error() != "SECURITY PROBLEM: insecure server advertised AUTH=PLAIN") { $return['error'] = imap_last_error(); } if (!$return['error'] && $flags != '') { $flags_array = explode(':', $flags); //"Answered","Draft","Flagged","Unseen" $flags_fixed = ""; if ($flags_array[0] == 'A') { $flags_fixed .= "\\Answered "; } if ($flags_array[1] == 'X') { $flags_fixed .= "\\Draft "; } if ($flags_array[2] == 'F') { $flags_fixed .= "\\Flagged "; } if ($flags_array[3] != 'U') { $flags_fixed .= "\\Seen "; } if ($flags_array[4] == 'F') { $flags_fixed .= "\\Answered \\Draft "; } imap_setflag_full($mbox_stream, $return['msg_no'], $flags_fixed, ST_UID); } //Ignorando erro de AUTH=Plain if ($return['error'] === 'SECURITY PROBLEM: insecure server advertised AUTH=PLAIN') { $return['error'] = false; } if ($mbox_stream) { imap_close($mbox_stream); } return $return; }
public function addMail($msg, $seen = true) { return imap_append($this->getImapStream(), $this->imapPath, $msg . "\r\n", $seen ? "\\Seen" : null); }
/** * Add a message to the mailbox * * @param string $message * * @return boolean */ public function addMessage($message) { return \imap_append($this->connection->getResource(), $this->mailbox, $message); }
/** * Save email to a folder (via IMAP) * * This function will open an IMAP stream using the email * credentials previously specified, and will save the email * to a specified folder. Parameter is the folder name (ie, Sent) * if nothing was specified it will be saved in the inbox. * * @author David Tkachuk <http://davidrockin.com/> */ public function copyToFolder($folderPath = null) { $message = $this->MIMEHeader . $this->MIMEBody; $path = "INBOX" . (isset($folderPath) && !is_null($folderPath) ? "." . $folderPath : ""); // Location to save the email $imapStream = imap_open("{" . $this->Host . "}" . $path, $this->Username, $this->Password); imap_append($imapStream, "{" . $this->Host . "}" . $path, $message); imap_close($imapStream); }
//send the message, check for errors $result = $mail->send(); if (!$result) { echo "Mailer Error: " . $mail->ErrorInfo; } else { $host = '{imap.gmail.com:993/imap/ssl}[Gmail]/Sent Mail'; $user = '******'; $password = '******'; $mbox = imap_open($host, $user, $password); $count = 0; if (!$mbox) { echo "IMAP Error"; } else { $dmy = date("d-M-Y H:i:s"); $msg = "From: {$event_mail}\r\n" . "To: {$to}\r\n" . "Date: {$dmy}\r\n" . "Subject: {$subject}\r\n" . "Message: {$message}\r\n"; if (imap_append($mbox, $host, $msg)) { echo "<h3><center>Message sent!</h3></center>"; } else { echo "<h3><center>Message not sent!</h3></center>"; } imap_close($mbox); } } } else { echo "Connection Failed"; } mysqli_close($mysqli); } else { if (isset($_SESSION["ec_name"]) && !isset($_REQUEST["id"])) { header("Location:ec_home.php"); } else {
/** * Adds a message with seen flag to a specified folder (used for saving sent items) * * @param string $folderid id of the folder * @param string $header header of the message * @param long $body body of the message * * @access protected * @return boolean status */ protected function addSentMessage($folderid, $header, $body) { $header_body = str_replace("\n", "\r\n", str_replace("\r", "", $header . "\n\n" . $body)); return @imap_append($this->mbox, $this->server . $folderid, $header_body, "\\Seen"); }
function appendMessage($_folderName, $_header, $_body, $_flags) { #print "<pre>$_header.$_body</pre>"; $mailboxString = ExecMethod('emailadmin.bo.getMailboxString', $_folderName, 3, $this->profileID); $header = str_replace("\n", "\r\n", $_header); $body = str_replace("\n", "\r\n", $_body); $result = @imap_append($this->mbox, $mailboxString, "{$header}" . "{$body}", $_flags); #print imap_last_error(); return $result; }
function mailcwp_send_callback() { //echo print_r($_POST, true); $result = array(); $to = str_replace(";", ",", $_POST["to"]); $cc = str_replace(";", ",", $_POST["cc"]); $bcc = str_replace(";", ",", $_POST["bcc"]); $subject = $_POST["subject"]; $draft_id = $_POST["draft_id"]; if (empty($to) && empty($cc) && empty($bcc)) { $result["result"] = "Failed"; $result["message"] = "Please enter an address to send the mail to."; } else { if (empty($subject)) { $result["result"] = "Failed"; $result["message"] = "Please enter a subject before sending the mail."; } else { $mailcwp_session = mailcwp_get_session(); $account = $mailcwp_session["account"]; if (array_key_exists("smtp_host", $account)) { $smtp_host = $account["smtp_host"]; } else { $smtp_host = ''; } create_message($headers, $message, $attachments, false, !empty($smtp_host)); if (empty($message)) { $result["result"] = "Failed"; $result["message"] = "Please enter a message before sending the mail."; } else { //write_log($message); //write_log($headers); $to = stripslashes($to); $subject = stripslashes($subject); //check for smtp settings //$mailcwp_session = mailcwp_get_session(); $account = $mailcwp_session["account"]; if (array_key_exists("smtp_host", $account)) { $smtp_host = $account["smtp_host"]; $smtp_port = $account["smtp_port"]; $smtp_auth = $account["smtp_auth"]; $smtp_username = $account["smtp_username"]; $smtp_password = $account["smtp_password"]; } //if smtp host is set use PHPMailer to sent mail via SMTP if (!empty($smtp_host)) { require_once "lib/class.phpmailer.php"; require_once "lib/class.smtp.php"; $options = get_option("mailcwp_settings", array()); $mailer = new PHPMailer(); if (isset($options["smtp_connect_timeout"])) { $mailer->Timeout = intval($options["smtp_connect_timeout"]); } else { $mailer->Timeout = 10; } $mailer->IsSMTP(); $mailer->SMTPAuth = $smtp_auth; $mailer->Host = $smtp_host; if (!empty($smtp_port)) { $mailer->Port = $smtp_port; } if ($smtp_auth) { $mailer->Username = $smtp_username; $mailer->Password = $smtp_password; } $mailer->SetFrom($account['email'], $account['name']); $mailer->AddReplyTo($account['email'], $account['name']); $mailer->Subject = $subject; $mailer->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test $mailer->MsgHTML(stripslashes($message)); $to_items = explode(",", $to); foreach ($to_items as $to_item) { if (($start_address = strpos($to_item, '<')) !== FALSE) { $end_address = strpos($to_item, '>'); $name = substr($to_item, 0, $start_address - 1); $to_item = substr($to_item, $start_address + 1, $end_address - $start_address - 1); $mailer->AddAddress($to_item, $name); } else { $mailer->AddAddress($to_item); } } $cc_items = explode(",", $cc); foreach ($cc_items as $cc_item) { if (($start_address = strpos($cc_item, '<')) !== FALSE) { $end_address = strpos($cc_item, '>'); $name = substr($cc_item, 0, $start_address - 1); $cc_item = substr($cc_item, $start_address + 1, $end_address - $start_address - 1); $mailer->AddCC($cc_item, $name); } else { $mailer->AddCC($cc_item); } } $bcc_items = explode(",", $bcc); foreach ($bcc_items as $bcc_item) { if (($start_address = strpos($bcc_item, '<')) !== FALSE) { $end_address = strpos($bcc_item, '>'); $name = substr($bcc_item, 0, $start_address - 1); $bcc_item = substr($bcc_item, $start_address + 1, $end_address - $start_address - 1); $mailer->AddBCC($bcc_item, $name); } else { $mailer->AddBCC($bcc_item); } } foreach ($attachments as $attachment) { $mailer->AddAttachment($attachment); } $mail_sent = $mailer->Send(); } else { $mail_sent = mail($to, $subject, $message, $headers); } if ($mail_sent) { $headers .= "To: {$to}\r\n" . "Subject: {$subject}\r\n"; $mailcwp_session = mailcwp_get_session(); $account = $mailcwp_session["account"]; //$account = $mailcwp_session["account"]; $from = "{$account['name']} <{$account['email']}>"; $mbox_name = "{$account['host']}:{$account['port']}"; $use_ssl = $account["use_ssl"]; $validate_cert = $account["validate_cert"]; $username = $account["username"]; $password = $account["password"]; $use_tls = $account["use_tls"]; $folder = $mailcwp_session["folder"]; $unique_id = $_POST["unique_id"]; $original = isset($_POST["original"]) ? $_POST["original"] : -1; $use_ssl_flag = $use_ssl === "true" ? "/ssl" : ""; $validate_cert_flag = $validate_cert === "true" ? "" : "/novalidate-cert"; $use_tls_flag = $use_tls === "true" ? "/tls" : ""; $sent_folder = ""; if (is_array($account)) { //keep copy in sent folder $sent_folder = null; if (array_key_exists("sent_folder", $account)) { $sent_folder = $account["sent_folder"]; } $mbox = mailcwp_imap_connect($account, OP_HALFOPEN, ""); if (empty($sent_folder)) { $sent_folder = mailcwp_find_folder($mbox, $account, "Sent"); } imap_close($mbox); if (!empty($sent_folder)) { $mbox = mailcwp_imap_connect($account, 0, $sent_folder); //write_log(print_r(imap_check($mbox))); //write_log("APPENDING TO FOLDER [$sent_folder] with HEADERS [$headers] and MESSAGE [$message]"); if (!imap_append($mbox, "{" . $mbox_name . $use_ssl_flag . "}" . $sent_folder, $headers . "\r\n" . $message . "\r\n", "\\Seen")) { $result["result"] = "OK"; $result["message"] = "Message could not be copied to sent folder ({$sent_folder})"; $result["imap_errors"] = imap_errors(); } imap_close($mbox); } if ($original != -1) { $mbox = mailcwp_imap_connect($account, 0, $folder); //write_log(print_r(imap_check($mbox))); //write_log("MARKING MESSAGE [$original] in [$folder] ANSWERED"); if (!imap_setflag_full($mbox, $original, "\\Answered")) { $result["result"] = "OK"; $result["message"] = "Unable to flag message as answered."; $result["imap_errors"] = imap_errors(); } imap_close($mbox); } } if (empty($result)) { $result["result"] = "OK"; } $current_user_id = get_current_user_id(); if ($current_user_id != 0) { //delete_user_meta($current_user_id, "mailcwp_contacts"); $options = get_option("mailcwp_settings", array()); $max_contacts = isset($options["max_contacts"]) ? $options["max_contacts"] : 100; $user_contacts = get_user_meta($current_user_id, "mailcwp_contacts", true); if ($user_contacts == null) { $user_contacts = array(); } else { if (count($user_contacts) > $max_contacts) { $count = count($user_contacts); $unset_index = 0; while ($count > $max_contacts) { unset($user_contacts[$unset_index++]); $count -= 1; } } } if (!empty($to)) { $to_items = explode(",", $to); foreach ($to_items as $to_item) { if (!in_array($to_item, $user_contacts)) { $user_contacts[] = $to_item; } } } if (!empty($cc)) { $cc_items = explode(",", $cc); foreach ($cc_items as $cc_item) { if (!in_array($cc_item, $user_contacts)) { $user_contacts[] = $cc_item; } } } if (!empty($bcc)) { $bcc_items = explode(",", $bcc); foreach ($bcc_items as $bcc_item) { if (!in_array($bcc_item, $user_contacts)) { $user_contacts[] = $bcc_item; } } } update_user_meta($current_user_id, "mailcwp_contacts", $user_contacts); } } else { $result["result"] = "Failed"; $result["message"] = "Message could not be sent."; $result["imap_errors"] = imap_errors(); } } } } echo json_encode($result); die; }
/** * Add a message to the mailbox * * @param string $message * * @return boolean */ public function addMessage($message) { $this->init(); return imap_append($this->connection->getResource(), $this->mailbox->name, $message); }
function addSentMessage($folderid, $header, $body) { return @imap_append($this->_mbox, $this->_server . $folderid, $header . "\n\n" . $body, "\\Seen"); }
/** * Adds the given message to the current folder. see: imap_append() (http://php.net/manual/en/function.imap-append.php) * @param string $message * @param int $options * @param string $internalDate * @return bool */ public function addMessage($message, $options = null, $internalDate = null) { return imap_append($this->connection->getConnection(), $this->connection->getMailbox()->getMailboxName(), $message, $options, $internalDate); }
/** Put a Message to the Server */ function mailPut($mail, $flag = null, $date = null) { // Parse date from message? if (empty($date) && preg_match('/^Date: (.+)$/m', $mail, $x)) { $date = strftime('%d-%b-%Y %H:%M:%S %z', strtotime($x[1])); } // $stat = $this->pathStat(); // $ret = imap_append($this->_c,$stat['check_path'], $mail, $flag, $date); $ret = imap_append($this->_c, $this->_folder_name, $mail, $flag, $date); $x = $this->stat(); if (!empty($x)) { print_r($x); return false; } return true; }
/** * save email in sent * * @return void * @param $header * @param $body */ public function saveMessageInSent($header, $body) { return imap_append($this->imap, $this->mailbox . $this->getSent(), $header . "\r\n" . $body . "\r\n", "\\Seen"); }
/** * Sends Email for Email 2.0 */ function email2Send($request) { global $mod_strings; global $app_strings; global $current_user; global $sugar_config; global $locale; global $timedate; global $beanList; global $beanFiles; $OBCharset = $locale->getPrecedentPreference('default_email_charset'); /********************************************************************** * Sugar Email PREP */ /* preset GUID */ $orignialId = ""; if (!empty($this->id)) { $orignialId = $this->id; } // if if (empty($this->id)) { $this->id = create_guid(); $this->new_with_id = true; } /* satisfy basic HTML email requirements */ $this->name = $request['sendSubject']; $this->description_html = '<html><body>' . $request['sendDescription'] . '</body></html>'; /********************************************************************** * PHPMAILER PREP */ $mail = new SugarPHPMailer(); $mail = $this->setMailer($mail, '', $_REQUEST['fromAccount']); if (empty($mail->Host) && !$this->isDraftEmail($request)) { $this->status = 'send_error'; if ($mail->oe->type == 'system') { echo $app_strings['LBL_EMAIL_ERROR_PREPEND'] . $app_strings['LBL_EMAIL_INVALID_SYSTEM_OUTBOUND']; } else { echo $app_strings['LBL_EMAIL_ERROR_PREPEND'] . $app_strings['LBL_EMAIL_INVALID_PERSONAL_OUTBOUND']; } return false; } $subject = $this->name; $mail->Subject = from_html($this->name); // work-around legacy code in SugarPHPMailer if ($_REQUEST['setEditor'] == 1) { $_REQUEST['description_html'] = $_REQUEST['sendDescription']; $this->description_html = $_REQUEST['description_html']; } else { $this->description_html = ''; $this->description = $_REQUEST['sendDescription']; } // end work-around if ($this->isDraftEmail($request)) { if ($this->type != 'draft' && $this->status != 'draft') { $this->id = create_guid(); $this->new_with_id = true; $this->date_entered = ""; } // if $q1 = "update emails_email_addr_rel set deleted = 1 WHERE email_id = '{$this->id}'"; $r1 = $this->db->query($q1); } // if if (isset($request['saveDraft'])) { $this->type = 'draft'; $this->status = 'draft'; $forceSave = true; } else { /* Apply Email Templates */ // do not parse email templates if the email is being saved as draft.... $toAddresses = $this->email2ParseAddresses($_REQUEST['sendTo']); $sea = new SugarEmailAddress(); $object_arr = array(); if (isset($_REQUEST['parent_type']) && !empty($_REQUEST['parent_type']) && isset($_REQUEST['parent_id']) && !empty($_REQUEST['parent_id']) && ($_REQUEST['parent_type'] == 'Accounts' || $_REQUEST['parent_type'] == 'Contacts' || $_REQUEST['parent_type'] == 'Leads' || $_REQUEST['parent_type'] == 'Users' || $_REQUEST['parent_type'] == 'Prospects')) { if (isset($beanList[$_REQUEST['parent_type']]) && !empty($beanList[$_REQUEST['parent_type']])) { $className = $beanList[$_REQUEST['parent_type']]; if (isset($beanFiles[$className]) && !empty($beanFiles[$className])) { if (!class_exists($className)) { require_once $beanFiles[$className]; } $bean = new $className(); $bean->retrieve($_REQUEST['parent_id']); $object_arr[$bean->module_dir] = $bean->id; } // if } // if } foreach ($toAddresses as $addrMeta) { $addr = $addrMeta['email']; $beans = $sea->getBeansByEmailAddress($addr); foreach ($beans as $bean) { if (!isset($object_arr[$bean->module_dir])) { $object_arr[$bean->module_dir] = $bean->id; } } } /* template parsing */ if (empty($object_arr)) { $object_arr = array('Contacts' => '123'); } $object_arr['Users'] = $current_user->id; $this->description_html = EmailTemplate::parse_template($this->description_html, $object_arr); $this->name = EmailTemplate::parse_template($this->name, $object_arr); $this->description = EmailTemplate::parse_template($this->description, $object_arr); $this->description = html_entity_decode($this->description, ENT_COMPAT, 'UTF-8'); if ($this->type != 'draft' && $this->status != 'draft') { $this->id = create_guid(); $this->date_entered = ""; $this->new_with_id = true; $this->type = 'out'; $this->status = 'sent'; } } if (isset($_REQUEST['parent_type']) && empty($_REQUEST['parent_type']) && isset($_REQUEST['parent_id']) && empty($_REQUEST['parent_id'])) { $this->parent_id = ""; $this->parent_type = ""; } // if $mail->Subject = $this->name; $mail = $this->handleBody($mail); $mail->Subject = $this->name; $this->description_html = from_html($this->description_html); $this->description_html = $this->decodeDuringSend($this->description_html); $this->description = $this->decodeDuringSend($this->description); /* from account */ $replyToAddress = $current_user->emailAddress->getReplyToAddress($current_user); $replyToName = ""; if (empty($request['fromAccount'])) { $defaults = $current_user->getPreferredEmail(); $mail->From = $defaults['email']; $mail->FromName = $defaults['name']; $replyToName = $mail->FromName; //$replyToAddress = $current_user->emailAddress->getReplyToAddress($current_user); } else { // passed -> user -> system default $ie = new InboundEmail(); $ie->retrieve($request['fromAccount']); $storedOptions = unserialize(base64_decode($ie->stored_options)); $fromName = ""; $fromAddress = ""; $replyToName = ""; //$replyToAddress = ""; if (!empty($storedOptions)) { $fromAddress = $storedOptions['from_addr']; $fromName = from_html($storedOptions['from_name']); $replyToAddress = isset($storedOptions['reply_to_addr']) ? $storedOptions['reply_to_addr'] : ""; $replyToName = isset($storedOptions['reply_to_name']) ? from_html($storedOptions['reply_to_name']) : ""; } // if $defaults = $current_user->getPreferredEmail(); // Personal Account doesn't have reply To Name and Reply To Address. So add those columns on UI // After adding remove below code // code to remove if ($ie->is_personal) { if (empty($replyToAddress)) { $replyToAddress = $current_user->emailAddress->getReplyToAddress($current_user); } // if if (empty($replyToName)) { $replyToName = $defaults['name']; } // if //Personal accounts can have a reply_address, which should //overwrite the users set default. if (!empty($storedOptions['reply_to_addr'])) { $replyToAddress = $storedOptions['reply_to_addr']; } } // end of code to remove $mail->From = !empty($fromAddress) ? $fromAddress : $defaults['email']; $mail->FromName = !empty($fromName) ? $fromName : $defaults['name']; $replyToName = !empty($replyToName) ? $replyToName : $mail->FromName; } $mail->Sender = $mail->From; /* set Return-Path field in header to reduce spam score in emails sent via Sugar's Email module */ if (!empty($replyToAddress)) { $mail->AddReplyTo($replyToAddress, $locale->translateCharsetMIME(trim($replyToName), 'UTF-8', $OBCharset)); } else { $mail->AddReplyTo($mail->From, $locale->translateCharsetMIME(trim($mail->FromName), 'UTF-8', $OBCharset)); } // else $emailAddressCollection = array(); // used in linking to beans below // handle to/cc/bcc foreach ($this->email2ParseAddresses($request['sendTo']) as $addr_arr) { if (empty($addr_arr['email'])) { continue; } if (empty($addr_arr['display'])) { $mail->AddAddress($addr_arr['email'], ""); } else { $mail->AddAddress($addr_arr['email'], $locale->translateCharsetMIME(trim($addr_arr['display']), 'UTF-8', $OBCharset)); } $emailAddressCollection[] = $addr_arr['email']; } foreach ($this->email2ParseAddresses($request['sendCc']) as $addr_arr) { if (empty($addr_arr['email'])) { continue; } if (empty($addr_arr['display'])) { $mail->AddCC($addr_arr['email'], ""); } else { $mail->AddCC($addr_arr['email'], $locale->translateCharsetMIME(trim($addr_arr['display']), 'UTF-8', $OBCharset)); } $emailAddressCollection[] = $addr_arr['email']; } foreach ($this->email2ParseAddresses($request['sendBcc']) as $addr_arr) { if (empty($addr_arr['email'])) { continue; } if (empty($addr_arr['display'])) { $mail->AddBCC($addr_arr['email'], ""); } else { $mail->AddBCC($addr_arr['email'], $locale->translateCharsetMIME(trim($addr_arr['display']), 'UTF-8', $OBCharset)); } $emailAddressCollection[] = $addr_arr['email']; } /* parse remove attachments array */ $removeAttachments = array(); if (!empty($request['templateAttachmentsRemove'])) { $exRemove = explode("::", $request['templateAttachmentsRemove']); foreach ($exRemove as $file) { $removeAttachments = substr($file, 0, 36); } } /* handle attachments */ if (!empty($request['attachments'])) { $exAttachments = explode("::", $request['attachments']); foreach ($exAttachments as $file) { $file = trim(from_html($file)); $file = str_replace("\\", "", $file); if (!empty($file)) { //$fileLocation = $this->et->userCacheDir."/{$file}"; $fileGUID = substr($file, 0, 36); $fileLocation = $this->et->userCacheDir . "/{$fileGUID}"; $filename = substr($file, 36, strlen($file)); // strip GUID for PHPMailer class to name outbound file $mail->AddAttachment($fileLocation, $filename, 'base64', $this->email2GetMime($fileLocation)); //$mail->AddAttachment($fileLocation, $filename, 'base64'); // only save attachments if we're archiving or drafting if ($this->type == 'draft' && !empty($this->id) || isset($request['saveToSugar']) && $request['saveToSugar'] == 1) { $note = new Note(); $note->id = create_guid(); $note->new_with_id = true; // duplicating the note with files $note->parent_id = $this->id; $note->parent_type = $this->module_dir; $note->name = $filename; $note->filename = $filename; $noteFile = "{$sugar_config['upload_dir']}{$note->id}"; $note->file_mime_type = $this->email2GetMime($fileLocation); if (!copy($fileLocation, $noteFile)) { $GLOBALS['log']->debug("EMAIL 2.0: could not copy attachment file to cache/upload [ {$fileLocation} ]"); } $note->save(); } } } } /* handle sugar documents */ if (!empty($request['documents'])) { $exDocs = explode("::", $request['documents']); foreach ($exDocs as $docId) { $docId = trim($docId); if (!empty($docId)) { $doc = new Document(); $docRev = new DocumentRevision(); $doc->retrieve($docId); $docRev->retrieve($doc->document_revision_id); $filename = $docRev->filename; $fileLocation = "{$sugar_config['upload_dir']}{$docRev->id}"; $mime_type = $docRev->file_mime_type; $mail->AddAttachment($fileLocation, $locale->translateCharsetMIME(trim($filename), 'UTF-8', $OBCharset), 'base64', $mime_type); // only save attachments if we're archiving or drafting if ($this->type == 'draft' && !empty($this->id) || isset($request['saveToSugar']) && $request['saveToSugar'] == 1) { $note = new Note(); $note->id = create_guid(); $note->new_with_id = true; // duplicating the note with files $note->parent_id = $this->id; $note->parent_type = $this->module_dir; $note->name = $filename; $note->filename = $filename; $note->file_mime_type = $mime_type; $noteFile = "{$sugar_config['upload_dir']}{$note->id}"; if (!copy($fileLocation, $noteFile)) { $GLOBALS['log']->debug("EMAIL 2.0: could not copy SugarDocument revision file to {$sugar_config['upload_dir']} [ {$fileLocation} ]"); } $note->save(); } } } } /* handle template attachments */ if (!empty($request['templateAttachments'])) { $exNotes = explode("::", $request['templateAttachments']); foreach ($exNotes as $noteId) { $noteId = trim($noteId); if (!empty($noteId)) { $note = new Note(); $note->retrieve($noteId); if (!empty($note->id)) { $filename = $note->filename; $fileLocation = "{$sugar_config['upload_dir']}{$note->id}"; $mime_type = $note->file_mime_type; if (!$note->embed_flag) { $mail->AddAttachment($fileLocation, $filename, 'base64', $mime_type); // only save attachments if we're archiving or drafting if ($this->type == 'draft' && !empty($this->id) || isset($request['saveToSugar']) && $request['saveToSugar'] == 1) { if ($note->parent_id != $this->id) { $this->saveTempNoteAttachments($filename, $fileLocation, $mime_type); } } // if } // if } else { //$fileLocation = $this->et->userCacheDir."/{$file}"; $fileGUID = substr($noteId, 0, 36); $fileLocation = $this->et->userCacheDir . "/{$fileGUID}"; //$fileLocation = $this->et->userCacheDir."/{$noteId}"; $filename = substr($noteId, 36, strlen($noteId)); // strip GUID for PHPMailer class to name outbound file $mail->AddAttachment($fileLocation, $locale->translateCharsetMIME(trim($filename), 'UTF-8', $OBCharset), 'base64', $this->email2GetMime($fileLocation)); //If we are saving an email we were going to forward we need to save the attachments as well. if ($this->type == 'draft' && !empty($this->id) || isset($request['saveToSugar']) && $request['saveToSugar'] == 1) { $mimeType = $this->email2GetMime($fileLocation); $this->saveTempNoteAttachments($filename, $fileLocation, $mimeType); } // if } } } } /********************************************************************** * Final Touches */ /* save email to sugar? */ $forceSave = false; if ($this->type == 'draft' && !isset($request['saveDraft'])) { // sending a draft email $this->type = 'out'; $this->status = 'sent'; $forceSave = true; } elseif (isset($request['saveDraft'])) { $this->type = 'draft'; $this->status = 'draft'; $forceSave = true; } /********************************************************************** * SEND EMAIL (finally!) */ $mailSent = false; if ($this->type != 'draft') { $mail->prepForOutbound(); $mail->Body = $this->decodeDuringSend($mail->Body); $mail->AltBody = $this->decodeDuringSend($mail->AltBody); if (!$mail->Send()) { $this->status = 'send_error'; ob_clean(); echo $app_strings['LBL_EMAIL_ERROR_PREPEND'] . $mail->ErrorInfo; return false; } } if (!(empty($orignialId) || isset($request['saveDraft']) || $this->type == 'draft' && $this->status == 'draft') && ($_REQUEST['composeType'] == 'reply' || $_REQUEST['composeType'] == 'replyAll' || $_REQUEST['composeType'] == 'replyCase') && $orignialId != $this->id) { $originalEmail = new Email(); $originalEmail->retrieve($orignialId); $originalEmail->reply_to_status = 1; $originalEmail->save(); $this->reply_to_status = 0; } // if if ($_REQUEST['composeType'] == 'reply' || $_REQUEST['composeType'] == 'replyCase') { if (isset($_REQUEST['ieId']) && isset($_REQUEST['mbox'])) { $emailFromIe = new InboundEmail(); $emailFromIe->retrieve($_REQUEST['ieId']); $emailFromIe->mailbox = $_REQUEST['mbox']; if (isset($emailFromIe->id) && $emailFromIe->is_personal) { if ($emailFromIe->isPop3Protocol()) { $emailFromIe->mark_answered($this->uid, 'pop3'); } elseif ($emailFromIe->connectMailserver() == 'true') { $emailFromIe->markEmails($this->uid, 'answered'); $emailFromIe->mark_answered($this->uid); } } } } if ($forceSave || $this->type == 'draft' || isset($request['saveToSugar']) && $request['saveToSugar'] == 1) { // saving a draft OR saving a sent email $decodedFromName = mb_decode_mimeheader($mail->FromName); $this->from_addr = "{$decodedFromName} <{$mail->From}>"; $this->from_addr_name = $this->from_addr; $this->to_addrs = $_REQUEST['sendTo']; $this->to_addrs_names = $_REQUEST['sendTo']; $this->cc_addrs = $_REQUEST['sendCc']; $this->cc_addrs_names = $_REQUEST['sendCc']; $this->bcc_addrs = $_REQUEST['sendBcc']; $this->bcc_addrs_names = $_REQUEST['sendBcc']; $this->assigned_user_id = $current_user->id; $this->date_sent = $timedate->now(); /////////////////////////////////////////////////////////////////// //// LINK EMAIL TO SUGARBEANS BASED ON EMAIL ADDY if (isset($_REQUEST['parent_type']) && !empty($_REQUEST['parent_type']) && isset($_REQUEST['parent_id']) && !empty($_REQUEST['parent_id'])) { $this->parent_id = $_REQUEST['parent_id']; $this->parent_type = $_REQUEST['parent_type']; $q = "SELECT count(*) c FROM emails_beans WHERE email_id = '{$this->id}' AND bean_id = '{$_REQUEST['parent_id']}' AND bean_module = '{$_REQUEST['parent_type']}'"; $r = $this->db->query($q); $a = $this->db->fetchByAssoc($r); if ($a['c'] <= 0) { if (isset($beanList[$_REQUEST['parent_type']]) && !empty($beanList[$_REQUEST['parent_type']])) { $className = $beanList[$_REQUEST['parent_type']]; if (isset($beanFiles[$className]) && !empty($beanFiles[$className])) { if (!class_exists($className)) { require_once $beanFiles[$className]; } $bean = new $className(); $bean->retrieve($_REQUEST['parent_id']); if ($bean->load_relationship('emails')) { $bean->emails->add($this->id); } // if } // if } // if } // if } else { if (!class_exists('aCase')) { } else { $c = new aCase(); if ($caseId = InboundEmail::getCaseIdFromCaseNumber($mail->Subject, $c)) { $c->retrieve($caseId); $c->load_relationship('emails'); $c->emails->add($this->id); $this->parent_type = "Cases"; $this->parent_id = $caseId; } // if } } // else //// LINK EMAIL TO SUGARBEANS BASED ON EMAIL ADDY /////////////////////////////////////////////////////////////////// $this->save(); } if (!empty($request['fromAccount'])) { if (isset($ie->id) && !$ie->isPop3Protocol()) { $sentFolder = $ie->get_stored_options("sentFolder"); if (!empty($sentFolder)) { $data = $mail->CreateHeader() . "\r\n" . $mail->CreateBody() . "\r\n"; $ie->mailbox = $sentFolder; if ($ie->connectMailserver() == 'true') { $connectString = $ie->getConnectString($ie->getServiceString(), $ie->mailbox); $returnData = imap_append($ie->conn, $connectString, $data, "\\Seen"); if (!$returnData) { $GLOBALS['log']->debug("could not copy email to {$ie->mailbox} for {$ie->name}"); } // if } else { $GLOBALS['log']->debug("could not connect to mail serve for folder {$ie->mailbox} for {$ie->name}"); } // else } else { $GLOBALS['log']->debug("could not copy email to {$ie->mailbox} sent folder as its empty"); } // else } // if } // if return true; }
/** Store a Message with proper date */ function mailPut($mail, $opts, $date) { $stat = $this->pathStat(); if (empty($mail)) { $mail = 'This message has no content'; } $ret = imap_append($this->_c, $stat['check_path'], $mail, $opts, $date); if ($buf = imap_errors()) { die(print_r($buf, true)); } return $ret; }