4 +-----------------------------------------------------------------------+
5 | program/steps/mail/sendmail.inc |
7 | This file is part of the Roundcube Webmail client |
8 | Copyright (C) 2005-2011, The Roundcube Dev Team |
9 | Licensed under the GNU GPL |
12 | Compose a new mail message with all headers and attachments |
13 | and send it using the PEAR::Net_SMTP class or with PHP mail() |
15 +-----------------------------------------------------------------------+
16 | Author: Thomas Bruederli <roundcube@gmail.com> |
17 +-----------------------------------------------------------------------+
19 $Id: sendmail.inc 5952 2012-03-03 13:20:14Z alec $
23 // remove all scripts and act as called in frame
25 $OUTPUT->framed = TRUE;
27 $savedraft = !empty($_POST['_draft']) ? true : false;
29 $COMPOSE_ID = get_input_value('_id', RCUBE_INPUT_GPC);
30 $COMPOSE =& $_SESSION['compose_data_'.$COMPOSE_ID];
32 /****** checks ********/
34 if (!isset($COMPOSE['id'])) {
35 raise_error(array('code' => 500, 'type' => 'php',
36 'file' => __FILE__, 'line' => __LINE__,
37 'message' => "Invalid compose ID"), true, false);
39 $OUTPUT->show_message('internalerror', 'error');
40 $OUTPUT->send('iframe');
44 if (empty($_POST['_to']) && empty($_POST['_cc']) && empty($_POST['_bcc'])
45 && empty($_POST['_subject']) && $_POST['_message']) {
46 $OUTPUT->show_message('sendingfailed', 'error');
47 $OUTPUT->send('iframe');
50 if(!empty($CONFIG['sendmail_delay'])) {
51 $wait_sec = time() - intval($CONFIG['sendmail_delay']) - intval($CONFIG['last_message_time']);
53 $OUTPUT->show_message('senttooquickly', 'error', array('sec' => $wait_sec * -1));
54 $OUTPUT->send('iframe');
60 /****** message sending functions ********/
62 // encrypt parts of the header
63 function rcmail_encrypt_header($what)
65 global $CONFIG, $RCMAIL;
66 if (!$CONFIG['http_received_header_encrypt']) {
69 return $RCMAIL->encrypt($what);
72 // get identity record
73 function rcmail_get_identity($id)
75 global $USER, $OUTPUT;
77 if ($sql_arr = $USER->get_identity($id)) {
79 $out['mailto'] = $sql_arr['email'];
80 $out['string'] = format_email_recipient($sql_arr['email'],
81 rcube_charset_convert($sql_arr['name'], RCMAIL_CHARSET, $OUTPUT->get_charset()));
91 * <img src="http[s]://.../tiny_mce/plugins/emotions/images/smiley-cool.gif" border="0" alt="Cool" title="Cool" />
95 * <img src="/path/on/server/.../tiny_mce/plugins/emotions/images/smiley-cool.gif" border="0" alt="Cool" title="Cool" />
98 function rcmail_fix_emoticon_paths(&$mime_message)
102 $body = $mime_message->getHTMLBody();
104 // remove any null-byte characters before parsing
105 $body = preg_replace('/\x00/', '', $body);
107 $searchstr = 'program/js/tiny_mce/plugins/emotions/img/';
110 // keep track of added images, so they're only added once
111 $included_images = array();
113 if (preg_match_all('# src=[\'"]([^\'"]+)#', $body, $matches, PREG_OFFSET_CAPTURE)) {
114 foreach ($matches[1] as $m) {
115 // find emoticon image tags
116 if (preg_match('#'.$searchstr.'(.*)$#', $m[0], $imatches)) {
117 $image_name = $imatches[1];
119 // sanitize image name so resulting attachment doesn't leave images dir
120 $image_name = preg_replace('/[^a-zA-Z0-9_\.\-]/i', '', $image_name);
121 $img_file = INSTALL_PATH . '/' . $searchstr . $image_name;
123 if (! in_array($image_name, $included_images)) {
124 // add the image to the MIME message
125 if (! $mime_message->addHTMLImage($img_file, 'image/gif', '', true, $image_name))
126 $OUTPUT->show_message("emoticonerror", 'error');
127 array_push($included_images, $image_name);
130 $body = substr_replace($body, $img_file, $m[1] + $offset, strlen($m[0]));
131 $offset += strlen($img_file) - strlen($m[0]);
136 $mime_message->setHTMLBody($body);
142 * Parse and cleanup email address input (and count addresses)
144 * @param string Address input
145 * @param boolean Do count recipients (saved in global $RECIPIENT_COUNT)
146 * @param boolean Validate addresses (errors saved in global $EMAIL_FORMAT_ERROR)
147 * @return string Canonical recipients string separated by comma
149 function rcmail_email_input_format($mailto, $count=false, $check=true)
151 global $RCMAIL, $EMAIL_FORMAT_ERROR, $RECIPIENT_COUNT;
153 // simplified email regexp, supporting quoted local part
154 $email_regexp = '(\S+|("[^"]+"))@\S+';
156 $delim = trim($RCMAIL->config->get('recipients_separator', ','));
157 $regexp = array("/[,;$delim]\s*[\r\n]+/", '/[\r\n]+/', "/[,;$delim]\s*\$/m", '/;/', '/(\S{1})(<'.$email_regexp.'>)/U');
158 $replace = array($delim.' ', ', ', '', $delim, '\\1 \\2');
160 // replace new lines and strip ending ', ', make address input more valid
161 $mailto = trim(preg_replace($regexp, $replace, $mailto));
164 $items = rcube_explode_quoted_string($delim, $mailto);
166 foreach($items as $item) {
168 // address in brackets without name (do nothing)
169 if (preg_match('/^<'.$email_regexp.'>$/', $item)) {
170 $item = rcube_idn_to_ascii(trim($item, '<>'));
171 $result[] = '<' . $item . '>';
172 // address without brackets and without name (add brackets)
173 } else if (preg_match('/^'.$email_regexp.'$/', $item)) {
174 $item = rcube_idn_to_ascii($item);
175 $result[] = '<' . $item . '>';
176 // address with name (handle name)
177 } else if (preg_match('/<*'.$email_regexp.'>*$/', $item, $matches)) {
178 $address = $matches[0];
179 $name = trim(str_replace($address, '', $item));
180 if ($name[0] == '"' && $name[count($name)-1] == '"') {
181 $name = substr($name, 1, -1);
183 $name = stripcslashes($name);
184 $address = rcube_idn_to_ascii(trim($address, '<>'));
185 $result[] = format_email_recipient($address, $name);
187 } else if (trim($item)) {
191 // check address format
192 $item = trim($item, '<>');
193 if ($item && $check && !check_email($item)) {
194 $EMAIL_FORMAT_ERROR = $item;
200 $RECIPIENT_COUNT += count($result);
203 return implode(', ', $result);
207 /****** compose message ********/
209 if (strlen($_POST['_draft_saveid']) > 3)
210 $olddraftmessageid = get_input_value('_draft_saveid', RCUBE_INPUT_POST);
212 $message_id = rcmail_gen_message_id();
214 // set default charset
215 $input_charset = $OUTPUT->get_charset();
216 $message_charset = isset($_POST['_charset']) ? $_POST['_charset'] : $input_charset;
218 $EMAIL_FORMAT_ERROR = NULL;
219 $RECIPIENT_COUNT = 0;
221 $mailto = rcmail_email_input_format(get_input_value('_to', RCUBE_INPUT_POST, TRUE, $message_charset), true);
222 $mailcc = rcmail_email_input_format(get_input_value('_cc', RCUBE_INPUT_POST, TRUE, $message_charset), true);
223 $mailbcc = rcmail_email_input_format(get_input_value('_bcc', RCUBE_INPUT_POST, TRUE, $message_charset), true);
225 if ($EMAIL_FORMAT_ERROR) {
226 $OUTPUT->show_message('emailformaterror', 'error', array('email' => $EMAIL_FORMAT_ERROR));
227 $OUTPUT->send('iframe');
230 if (empty($mailto) && !empty($mailcc)) {
234 else if (empty($mailto))
235 $mailto = 'undisclosed-recipients:;';
237 // Get sender name and address...
238 $from = get_input_value('_from', RCUBE_INPUT_POST, true, $message_charset);
239 // ... from identity...
240 if (is_numeric($from)) {
241 if (is_array($identity_arr = rcmail_get_identity($from))) {
242 if ($identity_arr['mailto'])
243 $from = $identity_arr['mailto'];
244 if ($identity_arr['string'])
245 $from_string = $identity_arr['string'];
251 // ... if there is no identity record, this might be a custom from
252 else if ($from_string = rcmail_email_input_format($from)) {
253 if (preg_match('/(\S+@\S+)/', $from_string, $m))
254 $from = trim($m[1], '<>');
259 if (!$from_string && $from)
260 $from_string = $from;
262 // compose headers array
265 // if configured, the Received headers goes to top, for good measure
266 if ($CONFIG['http_received_header'])
270 $http_header = 'from ';
271 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
272 $host = $_SERVER['HTTP_X_FORWARDED_FOR'];
273 $hostname = gethostbyaddr($host);
274 if ($CONFIG['http_received_header_encrypt']) {
275 $http_header .= rcmail_encrypt_header($hostname);
276 if ($host != $hostname)
277 $http_header .= ' ('. rcmail_encrypt_header($host) . ')';
279 $http_header .= (($host != $hostname) ? $hostname : '[' . $host . ']');
280 if ($host != $hostname)
281 $http_header .= ' (['. $host .'])';
283 $http_header .= $nldlm . ' via ';
285 $host = $_SERVER['REMOTE_ADDR'];
286 $hostname = gethostbyaddr($host);
287 if ($CONFIG['http_received_header_encrypt']) {
288 $http_header .= rcmail_encrypt_header($hostname);
289 if ($host != $hostname)
290 $http_header .= ' ('. rcmail_encrypt_header($host) . ')';
292 $http_header .= (($host != $hostname) ? $hostname : '[' . $host . ']');
293 if ($host != $hostname)
294 $http_header .= ' (['. $host .'])';
297 $http_header .= $nldlm . 'by ' . $_SERVER['HTTP_HOST'];
299 $http_header .= $nldlm . 'with HTTP (' . $_SERVER['SERVER_PROTOCOL'] .
300 ' '.$_SERVER['REQUEST_METHOD'] . '); ' . date('r');
301 $http_header = wordwrap($http_header, 69, $nldlm);
303 $headers['Received'] = $http_header;
306 $headers['Date'] = rcmail_user_date();
307 $headers['From'] = rcube_charset_convert($from_string, RCMAIL_CHARSET, $message_charset);
308 $headers['To'] = $mailto;
310 // additional recipients
311 if (!empty($mailcc)) {
312 $headers['Cc'] = $mailcc;
314 if (!empty($mailbcc)) {
315 $headers['Bcc'] = $mailbcc;
317 if (!empty($identity_arr['bcc'])) {
318 $headers['Bcc'] = ($headers['Bcc'] ? $headers['Bcc'].', ' : '') . $identity_arr['bcc'];
322 if (($max_recipients = (int) $RCMAIL->config->get('max_recipients')) > 0) {
323 if ($RECIPIENT_COUNT > $max_recipients) {
324 $OUTPUT->show_message('toomanyrecipients', 'error', array('max' => $max_recipients));
325 $OUTPUT->send('iframe');
330 $headers['Subject'] = trim(get_input_value('_subject', RCUBE_INPUT_POST, TRUE, $message_charset));
332 if (!empty($identity_arr['organization'])) {
333 $headers['Organization'] = $identity_arr['organization'];
335 if (!empty($_POST['_replyto'])) {
336 $headers['Reply-To'] = rcmail_email_input_format(get_input_value('_replyto', RCUBE_INPUT_POST, TRUE, $message_charset));
338 else if (!empty($identity_arr['reply-to'])) {
339 $headers['Reply-To'] = rcmail_email_input_format($identity_arr['reply-to'], false, true);
341 if (!empty($headers['Reply-To'])) {
342 $headers['Mail-Reply-To'] = $headers['Reply-To'];
344 if (!empty($_POST['_followupto'])) {
345 $headers['Mail-Followup-To'] = rcmail_email_input_format(get_input_value('_followupto', RCUBE_INPUT_POST, TRUE, $message_charset));
347 if (!empty($COMPOSE['reply_msgid'])) {
348 $headers['In-Reply-To'] = $COMPOSE['reply_msgid'];
351 // remember reply/forward UIDs in special headers
352 if (!empty($COMPOSE['reply_uid']) && $savedraft) {
353 $headers['X-Draft-Info'] = array('type' => 'reply', 'uid' => $COMPOSE['reply_uid']);
355 else if (!empty($COMPOSE['forward_uid']) && $savedraft) {
356 $headers['X-Draft-Info'] = array('type' => 'forward', 'uid' => $COMPOSE['forward_uid']);
359 if (!empty($COMPOSE['references'])) {
360 $headers['References'] = $COMPOSE['references'];
363 if (!empty($_POST['_priority'])) {
364 $priority = intval($_POST['_priority']);
365 $a_priorities = array(1=>'highest', 2=>'high', 4=>'low', 5=>'lowest');
366 if ($str_priority = $a_priorities[$priority]) {
367 $headers['X-Priority'] = sprintf("%d (%s)", $priority, ucfirst($str_priority));
371 if (!empty($_POST['_receipt'])) {
372 $headers['Return-Receipt-To'] = $from_string;
373 $headers['Disposition-Notification-To'] = $from_string;
376 // additional headers
377 $headers['Message-ID'] = $message_id;
378 $headers['X-Sender'] = $from;
380 if (is_array($headers['X-Draft-Info'])) {
381 $headers['X-Draft-Info'] = rcmail_draftinfo_encode($headers['X-Draft-Info'] + array('folder' => $COMPOSE['mailbox']));
383 if (!empty($CONFIG['useragent'])) {
384 $headers['User-Agent'] = $CONFIG['useragent'];
387 // exec hook for header checking and manipulation
388 $data = $RCMAIL->plugins->exec_hook('message_outgoing_headers', array('headers' => $headers));
390 // sending aborted by plugin
391 if ($data['abort'] && !$savedraft) {
392 $OUTPUT->show_message($data['message'] ? $data['message'] : 'sendingfailed');
393 $OUTPUT->send('iframe');
396 $headers = $data['headers'];
399 $isHtml = (bool) get_input_value('_is_html', RCUBE_INPUT_POST);
401 // fetch message body
402 $message_body = get_input_value('_message', RCUBE_INPUT_POST, TRUE, $message_charset);
406 // remove signature's div ID
407 $message_body = preg_replace('/\s*id="_rc_sig"/', '', $message_body);
409 // add inline css for blockquotes
410 $bstyle = 'padding-left:5px; border-left:#1010ff 2px solid; margin-left:5px; width:100%';
411 $message_body = preg_replace('/<blockquote>/',
412 '<blockquote type="cite" style="'.$bstyle.'">', $message_body);
414 // append doctype and html/body wrappers
415 $message_body = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">' .
416 "\r\n<html><body>\r\n" . $message_body;
419 // Check spelling before send
420 if ($CONFIG['spellcheck_before_send'] && $CONFIG['enable_spellcheck']
421 && empty($COMPOSE['spell_checked']) && !empty($message_body)
423 $spellchecker = new rcube_spellchecker(get_input_value('_lang', RCUBE_INPUT_GPC));
424 $spell_result = $spellchecker->check($message_body, $isHtml);
426 $COMPOSE['spell_checked'] = true;
428 if (!$spell_result) {
429 $result = $isHtml ? $spellchecker->get_words() : $spellchecker->get_xml();
430 $OUTPUT->show_message('mispellingsfound', 'error');
431 $OUTPUT->command('spellcheck_resume', $isHtml, $result);
432 $OUTPUT->send('iframe');
436 // generic footer for all messages
437 if ($isHtml && !empty($CONFIG['generic_message_footer_html'])) {
438 $footer = file_get_contents(realpath($CONFIG['generic_message_footer_html']));
439 $footer = rcube_charset_convert($footer, RCMAIL_CHARSET, $message_charset);
441 else if (!empty($CONFIG['generic_message_footer'])) {
442 $footer = file_get_contents(realpath($CONFIG['generic_message_footer']));
443 $footer = rcube_charset_convert($footer, RCMAIL_CHARSET, $message_charset);
445 $footer = '<pre>'.$footer.'</pre>';
449 $message_body .= "\r\n" . $footer;
451 $message_body .= "\r\n</body></html>\r\n";
454 // set line length for body wrapping
455 $LINE_LENGTH = $RCMAIL->config->get('line_length', 72);
457 // Since we can handle big messages with disk usage, we need more time to work
460 // create PEAR::Mail_mime instance
461 $MAIL_MIME = new Mail_mime("\r\n");
463 // Check if we have enough memory to handle the message in it
464 // It's faster than using files, so we'll do this if we only can
465 if (is_array($COMPOSE['attachments']) && $CONFIG['smtp_server']
466 && ($mem_limit = parse_bytes(ini_get('memory_limit'))))
468 $memory = function_exists('memory_get_usage') ? memory_get_usage() : 16*1024*1024; // safe value: 16MB
470 foreach ($COMPOSE['attachments'] as $id => $attachment)
471 $memory += $attachment['size'];
473 // Yeah, Net_SMTP needs up to 12x more memory, 1.33 is for base64
474 if ($memory * 1.33 * 12 > $mem_limit)
475 $MAIL_MIME->setParam('delay_file_io', true);
478 // For HTML-formatted messages, construct the MIME message with both
479 // the HTML part and the plain-text part
482 $plugin = $RCMAIL->plugins->exec_hook('message_outgoing_body',
483 array('body' => $message_body, 'type' => 'html', 'message' => $MAIL_MIME));
485 $MAIL_MIME->setHTMLBody($plugin['body']);
488 $plugin['body'] = rcmail_replace_emoticons($plugin['body']);
490 // add a plain text version of the e-mail as an alternative part.
491 $h2t = new html2text($plugin['body'], false, true, 0);
492 $plainTextPart = rc_wordwrap($h2t->get_text(), $LINE_LENGTH, "\r\n");
493 $plainTextPart = wordwrap($plainTextPart, 998, "\r\n", true);
494 if (!$plainTextPart) {
495 // empty message body breaks attachment handling in drafts
496 $plainTextPart = "\r\n";
499 // make sure all line endings are CRLF (#1486712)
500 $plainTextPart = preg_replace('/\r?\n/', "\r\n", $plainTextPart);
503 $plugin = $RCMAIL->plugins->exec_hook('message_outgoing_body',
504 array('body' => $plainTextPart, 'type' => 'alternative', 'message' => $MAIL_MIME));
506 $MAIL_MIME->setTXTBody($plugin['body']);
508 // look for "emoticon" images from TinyMCE and change their src paths to
509 // be file paths on the server instead of URL paths.
510 $message_body = rcmail_fix_emoticon_paths($MAIL_MIME);
513 $plugin = $RCMAIL->plugins->exec_hook('message_outgoing_body',
514 array('body' => $message_body, 'type' => 'plain', 'message' => $MAIL_MIME));
516 $message_body = $plugin['body'];
518 // compose format=flowed content if enabled
519 if ($flowed = $RCMAIL->config->get('send_format_flowed', true))
520 $message_body = rcube_message::format_flowed($message_body, min($LINE_LENGTH+2, 79));
522 $message_body = rc_wordwrap($message_body, $LINE_LENGTH, "\r\n");
524 $message_body = wordwrap($message_body, 998, "\r\n", true);
525 if (!strlen($message_body)) {
526 // empty message body breaks attachment handling in drafts
527 $message_body = "\r\n";
530 $MAIL_MIME->setTXTBody($message_body, false, true);
533 // add stored attachments, if any
534 if (is_array($COMPOSE['attachments']))
536 foreach ($COMPOSE['attachments'] as $id => $attachment) {
537 // This hook retrieves the attachment contents from the file storage backend
538 $attachment = $RCMAIL->plugins->exec_hook('attachment_get', $attachment);
540 $dispurl = '/\ssrc\s*=\s*[\'"]*\S+display-attachment\S+file=rcmfile' . preg_quote($attachment['id']) . '[\s\'"]*/';
541 $message_body = $MAIL_MIME->getHTMLBody();
542 if ($isHtml && (preg_match($dispurl, $message_body) > 0)) {
543 $message_body = preg_replace($dispurl, ' src="'.$attachment['name'].'" ', $message_body);
544 $MAIL_MIME->setHTMLBody($message_body);
546 if ($attachment['data'])
547 $MAIL_MIME->addHTMLImage($attachment['data'], $attachment['mimetype'], $attachment['name'], false);
549 $MAIL_MIME->addHTMLImage($attachment['path'], $attachment['mimetype'], $attachment['name'], true);
552 $ctype = str_replace('image/pjpeg', 'image/jpeg', $attachment['mimetype']); // #1484914
553 $file = $attachment['data'] ? $attachment['data'] : $attachment['path'];
555 // .eml attachments send inline
556 $MAIL_MIME->addAttachment($file,
559 ($attachment['data'] ? false : true),
560 ($ctype == 'message/rfc822' ? '8bit' : 'base64'),
561 ($ctype == 'message/rfc822' ? 'inline' : 'attachment'),
563 $CONFIG['mime_param_folding'] ? 'quoted-printable' : NULL,
564 $CONFIG['mime_param_folding'] == 2 ? 'quoted-printable' : NULL,
571 // choose transfer encoding for plain/text body
572 if (preg_match('/[^\x00-\x7F]/', $MAIL_MIME->getTXTBody()))
573 $transfer_encoding = $RCMAIL->config->get('force_7bit') ? 'quoted-printable' : '8bit';
575 $transfer_encoding = '7bit';
577 // encoding settings for mail composing
578 $MAIL_MIME->setParam('text_encoding', $transfer_encoding);
579 $MAIL_MIME->setParam('html_encoding', 'quoted-printable');
580 $MAIL_MIME->setParam('head_encoding', 'quoted-printable');
581 $MAIL_MIME->setParam('head_charset', $message_charset);
582 $MAIL_MIME->setParam('html_charset', $message_charset);
583 $MAIL_MIME->setParam('text_charset', $message_charset . ($flowed ? ";\r\n format=flowed" : ''));
585 // encoding subject header with mb_encode provides better results with asian characters
586 if (function_exists('mb_encode_mimeheader')) {
587 mb_internal_encoding($message_charset);
588 $headers['Subject'] = mb_encode_mimeheader($headers['Subject'],
589 $message_charset, 'Q', "\r\n", 8);
590 mb_internal_encoding(RCMAIL_CHARSET);
593 // pass headers to message object
594 $MAIL_MIME->headers($headers);
596 // Begin SMTP Delivery Block
599 // check 'From' address (identity may be incomplete)
601 $OUTPUT->show_message('nofromaddress', 'error');
602 $OUTPUT->send('iframe');
605 // Handle Delivery Status Notification request
606 if (!empty($_POST['_dsn'])) {
607 $smtp_opts['dsn'] = true;
610 $sent = rcmail_deliver_message($MAIL_MIME, $from, $mailto,
611 $smtp_error, $mailbody_file, $smtp_opts);
613 // return to compose page if sending failed
617 if ($mailbody_file) {
618 unlink($mailbody_file);
622 $OUTPUT->show_message($smtp_error['label'], 'error', $smtp_error['vars']);
624 $OUTPUT->show_message('sendingfailed', 'error');
625 $OUTPUT->send('iframe');
628 // save message sent time
629 if (!empty($CONFIG['sendmail_delay']))
630 $RCMAIL->user->save_prefs(array('last_message_time' => time()));
632 // set replied/forwarded flag
633 if ($COMPOSE['reply_uid'])
634 $IMAP->set_flag($COMPOSE['reply_uid'], 'ANSWERED', $COMPOSE['mailbox']);
635 else if ($COMPOSE['forward_uid'])
636 $IMAP->set_flag($COMPOSE['forward_uid'], 'FORWARDED', $COMPOSE['mailbox']);
638 } // End of SMTP Delivery Block
641 // Determine which folder to save message
643 $store_target = $CONFIG['drafts_mbox'];
645 $store_target = isset($_POST['_store_target']) ? get_input_value('_store_target', RCUBE_INPUT_POST) : $CONFIG['sent_mbox'];
648 // check if folder is subscribed
649 if ($IMAP->mailbox_exists($store_target, true))
650 $store_folder = true;
651 // folder may be existing but not subscribed (#1485241)
652 else if (!$IMAP->mailbox_exists($store_target))
653 $store_folder = $IMAP->create_mailbox($store_target, true);
654 else if ($IMAP->subscribe($store_target))
655 $store_folder = true;
657 // append message to sent box
659 // message body in file
660 if ($mailbody_file || $MAIL_MIME->getParam('delay_file_io')) {
661 $headers = $MAIL_MIME->txtHeaders();
663 // file already created
665 $msg = $mailbody_file;
667 $temp_dir = $RCMAIL->config->get('temp_dir');
668 $mailbody_file = tempnam($temp_dir, 'rcmMsg');
669 if (!PEAR::isError($msg = $MAIL_MIME->saveMessageBody($mailbody_file)))
670 $msg = $mailbody_file;
674 $msg = $MAIL_MIME->getMessage();
678 if (PEAR::isError($msg))
679 raise_error(array('code' => 650, 'type' => 'php',
680 'file' => __FILE__, 'line' => __LINE__,
681 'message' => "Could not create message: ".$msg->getMessage()),
684 $saved = $IMAP->save_message($store_target, $msg, $headers, $mailbody_file ? true : false);
687 if ($mailbody_file) {
688 unlink($mailbody_file);
689 $mailbody_file = null;
692 // raise error if saving failed
694 raise_error(array('code' => 800, 'type' => 'imap',
695 'file' => __FILE__, 'line' => __LINE__,
696 'message' => "Could not save message in $store_target"), TRUE, FALSE);
699 $OUTPUT->show_message('errorsaving', 'error');
700 $OUTPUT->send('iframe');
705 if ($olddraftmessageid) {
706 // delete previous saved draft
707 // @TODO: use message UID (remember to check UIDVALIDITY) to skip this SEARCH
708 $a_deleteid = $IMAP->search_once($CONFIG['drafts_mbox'],
709 'HEADER Message-ID '.$olddraftmessageid, true);
711 if (!empty($a_deleteid)) {
712 $deleted = $IMAP->delete_message($a_deleteid, $CONFIG['drafts_mbox']);
714 // raise error if deletion of old draft failed
716 raise_error(array('code' => 800, 'type' => 'imap',
717 'file' => __FILE__, 'line' => __LINE__,
718 'message' => "Could not delete message from ".$CONFIG['drafts_mbox']), TRUE, FALSE);
723 else if ($mailbody_file) {
724 unlink($mailbody_file);
729 $msgid = strtr($message_id, array('>' => '', '<' => ''));
731 // remember new draft-uid ($saved could be an UID or TRUE here)
732 if (is_bool($saved)) {
733 $draftuids = $IMAP->search_once($CONFIG['drafts_mbox'], 'HEADER Message-ID '.$msgid, true);
734 $saved = $draftuids[0];
736 $COMPOSE['param']['draft_uid'] = $saved;
737 $plugin = $RCMAIL->plugins->exec_hook('message_draftsaved', array('msgid' => $msgid, 'uid' => $saved, 'folder' => $store_target));
740 $OUTPUT->show_message($plugin['message'] ? $plugin['message'] : 'messagesaved', 'confirmation');
742 // update "_draft_saveid" and the "cmp_hash" to prevent "Unsaved changes" warning
743 $OUTPUT->command('set_draft_id', $msgid);
744 $OUTPUT->command('compose_field_hash', true);
746 // start the auto-save timer again
747 $OUTPUT->command('auto_save_start');
749 $OUTPUT->send('iframe');
752 rcmail_compose_cleanup($COMPOSE_ID);
754 if ($store_folder && !$saved)
755 $OUTPUT->command('sent_successfully', 'error', rcube_label('errorsavingsent'));
757 $OUTPUT->command('sent_successfully', 'confirmation', rcube_label('messagesent'));
758 $OUTPUT->send('iframe');