4 +-----------------------------------------------------------------------+
5 | program/steps/mail/sendmail.inc |
7 | This file is part of the RoundCube Webmail client |
8 | Copyright (C) 2005-2009, RoundCube Dev. - Switzerland |
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 2713 2009-07-06 09:13:10Z alec $
24 // remove all scripts and act as called in frame
26 $OUTPUT->framed = TRUE;
28 $savedraft = !empty($_POST['_draft']) ? TRUE : FALSE;
30 /****** checks ********/
32 if (!isset($_SESSION['compose']['id'])) {
33 raise_error(array('code' => 500, 'type' => 'smtp', 'file' => __FILE__, 'message' => "Invalid compose ID"), true, false);
34 console("Sendmail error", $_SESSION['compose']);
35 $OUTPUT->show_message("An internal error occured. Please try again.", 'error');
36 $OUTPUT->send('iframe');
40 if (empty($_POST['_to']) && empty($_POST['_cc']) && empty($_POST['_bcc'])
41 && empty($_POST['_subject']) && $_POST['_message']) {
42 $OUTPUT->show_message('sendingfailed', 'error');
43 $OUTPUT->send('iframe');
46 if(!empty($CONFIG['sendmail_delay'])) {
47 $wait_sec = time() - intval($CONFIG['sendmail_delay']) - intval($CONFIG['last_message_time']);
49 $OUTPUT->show_message('senttooquickly', 'error', array('sec' => $wait_sec * -1));
50 $OUTPUT->send('iframe');
56 /****** message sending functions ********/
58 // encrypt parts of the header
59 function rcmail_encrypt_header($what)
61 global $CONFIG, $RCMAIL;
62 if (!$CONFIG['http_received_header_encrypt'])
66 return $RCMAIL->encrypt($what);
69 // get identity record
70 function rcmail_get_identity($id)
72 global $USER, $OUTPUT;
74 if ($sql_arr = $USER->get_identity($id))
77 $out['mailto'] = $sql_arr['email'];
79 // Special chars as defined by RFC 822 need to in quoted string (or escaped).
80 if (preg_match('/[\(\)\<\>\\\.\[\]@,;:"]/', $sql_arr['name']))
81 $name = '"' . addcslashes($sql_arr['name'], '"') . '"';
83 $name = $sql_arr['name'];
85 $out['string'] = rcube_charset_convert($name, RCMAIL_CHARSET, $OUTPUT->get_charset());
86 if ($sql_arr['email'])
87 $out['string'] .= ' <' . $sql_arr['email'] . '>';
97 * <img src=".../tiny_mce/plugins/emotions/images/smiley-cool.gif" border="0" alt="Cool" title="Cool" />
101 * <IMG src="cid:smiley-cool.gif"/>
104 * Content-Type: image/gif
105 * Content-Transfer-Encoding: base64
106 * Content-ID: <smiley-cool.gif>
108 function rcmail_attach_emoticons(&$mime_message)
112 $body = $mime_message->getHtmlBody();
114 // remove any null-byte characters before parsing
115 $body = preg_replace('/\x00/', '', $body);
117 $searchstr = 'program/js/tiny_mce/plugins/emotions/img/';
120 // keep track of added images, so they're only added once
121 $included_images = array();
123 if (preg_match_all('# src=[\'"]([^\'"]+)#', $body, $matches, PREG_OFFSET_CAPTURE)) {
124 foreach ($matches[1] as $m) {
125 // find emoticon image tags
126 if (preg_match('#'.$searchstr.'(.*)$#', $m[0], $imatches)) {
127 $image_name = $imatches[1];
129 // sanitize image name so resulting attachment doesn't leave images dir
130 $image_name = preg_replace('/[^a-zA-Z0-9_\.\-]/i', '', $image_name);
131 $img_file = INSTALL_PATH . '/' . $searchstr . $image_name;
133 if (! in_array($image_name, $included_images)) {
134 // add the image to the MIME message
135 if(! $mime_message->addHTMLImage($img_file, 'image/gif', '', true, $image_name))
136 $OUTPUT->show_message("emoticonerror", 'error');
137 array_push($included_images, $image_name);
140 $body = substr_replace($body, $img_file, $m[1] + $offset, strlen($m[0]));
141 $offset += strlen($img_file) - strlen($m[0]);
146 $mime_message->setHTMLBody($body);
151 // parse email address input
152 function rcmail_email_input_format($mailto)
154 $regexp = array('/[,;]\s*[\r\n]+/', '/[\r\n]+/', '/[,;]\s*$/m', '/;/', '/(\S{1})(<\S+@\S+>)/U');
155 $replace = array(', ', ', ', '', ',', '\\1 \\2');
157 // replace new lines and strip ending ', ', make address input more valid
158 $mailto = trim(preg_replace($regexp, $replace, $mailto));
161 $items = rcube_explode_quoted_string(',', $mailto);
163 foreach($items as $item) {
165 // address in brackets without name (do nothing)
166 if (preg_match('/^<\S+@\S+>$/', $item)) {
168 // address without brackets and without name (add brackets)
169 } else if (preg_match('/^\S+@\S+$/', $item)) {
170 $result[] = '<'.$item.'>';
171 // address with name (handle name)
172 } else if (preg_match('/\S+@\S+>*$/', $item, $matches)) {
173 $address = $matches[0];
174 $name = str_replace($address, '', $item);
176 if ($name && ($name[0] != '"' || $name[strlen($name)-1] != '"')
177 && preg_match('/[\(\)\<\>\\\.\[\]@,;:"]/', $name)) {
178 $name = '"'.addcslashes($name, '"').'"';
180 if (!preg_match('/^<\S+@\S+>$/', $address))
181 $address = '<'.$address.'>';
183 $result[] = $name.' '.$address;
184 } else if (trim($item)) {
185 // @TODO: handle errors
189 return implode(', ', $result);
192 /****** compose message ********/
194 if (strlen($_POST['_draft_saveid']) > 3)
195 $olddraftmessageid = get_input_value('_draft_saveid', RCUBE_INPUT_POST);
197 $message_id = sprintf('<%s@%s>', md5(uniqid('rcmail'.rand(),true)), $RCMAIL->config->mail_domain($_SESSION['imap_host']));
199 // set default charset
200 $input_charset = $OUTPUT->get_charset();
201 $message_charset = isset($_POST['_charset']) ? $_POST['_charset'] : $input_charset;
203 $mailto = rcmail_email_input_format(get_input_value('_to', RCUBE_INPUT_POST, TRUE, $message_charset));
204 $mailcc = rcmail_email_input_format(get_input_value('_cc', RCUBE_INPUT_POST, TRUE, $message_charset));
205 $mailbcc = rcmail_email_input_format(get_input_value('_bcc', RCUBE_INPUT_POST, TRUE, $message_charset));
207 if (empty($mailto) && !empty($mailcc)) {
211 else if (empty($mailto))
212 $mailto = 'undisclosed-recipients:;';
214 // get sender name and address
215 $from = get_input_value('_from', RCUBE_INPUT_POST, true, $message_charset);
216 $identity_arr = rcmail_get_identity($from);
218 if (!$identity_arr && ($from = rcmail_email_input_format($from))) {
219 if (preg_match('/(\S+@\S+)/', $from, $m))
220 $identity_arr['mailto'] = $m[1];
222 $from = $identity_arr['mailto'];
224 if (empty($identity_arr['string']))
225 $identity_arr['string'] = $from;
227 // compose headers array
230 // if configured, the Received headers goes to top, for good measure
231 if ($CONFIG['http_received_header'])
233 $nldlm = $RCMAIL->config->header_delimiter() . "\t";
234 $http_header = 'from ';
235 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
236 $http_header .= rcmail_encrypt_header(gethostbyaddr($_SERVER['HTTP_X_FORWARDED_FOR'])) .
237 ' [' . rcmail_encrypt_header($_SERVER['HTTP_X_FORWARDED_FOR']) . ']';
238 $http_header .= $nldlm . ' via ';
240 $http_header .= rcmail_encrypt_header(gethostbyaddr($_SERVER['REMOTE_ADDR'])) .
241 ' [' . rcmail_encrypt_header($_SERVER['REMOTE_ADDR']) .']';
242 $http_header .= $nldlm . 'with ' . $_SERVER['SERVER_PROTOCOL'] .
243 ' ('.$_SERVER['REQUEST_METHOD'] . '); ' . date('r');
244 $http_header = wordwrap($http_header, 69, $nldlm);
245 $headers['Received'] = $http_header;
248 $headers['Date'] = date('r');
249 $headers['From'] = rcube_charset_convert($identity_arr['string'], RCMAIL_CHARSET, $message_charset);
250 $headers['To'] = $mailto;
252 // additional recipients
254 $headers['Cc'] = $mailcc;
256 if (!empty($mailbcc))
257 $headers['Bcc'] = $mailbcc;
259 if (!empty($identity_arr['bcc']))
260 $headers['Bcc'] = ($headers['Bcc'] ? $headers['Bcc'].', ' : '') . $identity_arr['bcc'];
263 $headers['Subject'] = trim(get_input_value('_subject', RCUBE_INPUT_POST, TRUE, $message_charset));
265 if (!empty($identity_arr['organization']))
266 $headers['Organization'] = $identity_arr['organization'];
268 if (!empty($_POST['_replyto']))
269 $headers['Reply-To'] = rcmail_email_input_format(get_input_value('_replyto', RCUBE_INPUT_POST, TRUE, $message_charset));
270 else if (!empty($identity_arr['reply-to']))
271 $headers['Reply-To'] = $identity_arr['reply-to'];
273 if (!empty($_SESSION['compose']['reply_msgid']))
274 $headers['In-Reply-To'] = $_SESSION['compose']['reply_msgid'];
276 if (!empty($_SESSION['compose']['references']))
277 $headers['References'] = $_SESSION['compose']['references'];
279 if (!empty($_POST['_priority']))
281 $priority = intval($_POST['_priority']);
282 $a_priorities = array(1=>'highest', 2=>'high', 4=>'low', 5=>'lowest');
283 if ($str_priority = $a_priorities[$priority])
284 $headers['X-Priority'] = sprintf("%d (%s)", $priority, ucfirst($str_priority));
287 if (!empty($_POST['_receipt']))
289 $headers['Return-Receipt-To'] = $identity_arr['string'];
290 $headers['Disposition-Notification-To'] = $identity_arr['string'];
293 // additional headers
294 $headers['Message-ID'] = $message_id;
295 $headers['X-Sender'] = $from;
297 if (!empty($CONFIG['useragent']))
298 $headers['User-Agent'] = $CONFIG['useragent'];
300 $isHtmlVal = strtolower(get_input_value('_is_html', RCUBE_INPUT_POST));
301 $isHtml = ($isHtmlVal == "1");
303 // fetch message body
304 $message_body = get_input_value('_message', RCUBE_INPUT_POST, TRUE, $message_charset);
307 // remove signature's div ID
309 $message_body = preg_replace('/\s*id="_rc_sig"/', '', $message_body);
311 // generic footer for all messages
312 if (!empty($CONFIG['generic_message_footer'])) {
313 $footer = file_get_contents(realpath($CONFIG['generic_message_footer']));
314 $footer = rcube_charset_convert($footer, RCMAIL_CHARSET, $message_charset);
318 // create extended PEAR::Mail_mime instance
319 $MAIL_MIME = new rcube_mail_mime($RCMAIL->config->header_delimiter());
321 // For HTML-formatted messages, construct the MIME message with both
322 // the HTML part and the plain-text part
325 $plugin = $RCMAIL->plugins->exec_hook('outgoing_message_body', array('body' => $message_body, 'type' => 'html', 'message' => $MAIL_MIME));
326 $MAIL_MIME->setHTMLBody($plugin['body'] . ($footer ? "\r\n<pre>".$footer.'</pre>' : ''));
328 // add a plain text version of the e-mail as an alternative part.
329 $h2t = new html2text($plugin['body'], false, true, 0);
330 $plainTextPart = rc_wordwrap($h2t->get_text(), 75, "\r\n") . ($footer ? "\r\n".$footer : '');
331 $plainTextPart = wordwrap($plainTextPart, 998, "\r\n", true);
332 if (!strlen($plainTextPart)) {
333 // empty message body breaks attachment handling in drafts
334 $plainTextPart = "\r\n";
336 $plugin = $RCMAIL->plugins->exec_hook('outgoing_message_body', array('body' => $plainTextPart, 'type' => 'alternative', 'message' => $MAIL_MIME));
337 $MAIL_MIME->setTXTBody($plugin['body']);
339 // look for "emoticon" images from TinyMCE and copy into message as attachments
340 $message_body = rcmail_attach_emoticons($MAIL_MIME);
344 $message_body = rc_wordwrap($message_body, 75, "\r\n");
346 $message_body .= "\r\n" . $footer;
347 $message_body = wordwrap($message_body, 998, "\r\n", true);
348 if (!strlen($message_body)) {
349 // empty message body breaks attachment handling in drafts
350 $message_body = "\r\n";
352 $plugin = $RCMAIL->plugins->exec_hook('outgoing_message_body', array('body' => $message_body, 'type' => 'plain', 'message' => $MAIL_MIME));
353 $MAIL_MIME->setTXTBody($plugin['body'], false, true);
356 // chose transfer encoding
357 $charset_7bit = array('ASCII', 'ISO-2022-JP', 'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-15');
358 $transfer_encoding = in_array(strtoupper($message_charset), $charset_7bit) ? '7bit' : '8bit';
360 // add stored attachments, if any
361 if (is_array($_SESSION['compose']['attachments'])) {
362 foreach ($_SESSION['compose']['attachments'] as $id => $attachment) {
363 // This hook retrieves the attachment contents from the file storage backend
364 $attachment = $RCMAIL->plugins->exec_hook('get_attachment', $attachment);
366 $dispurl = '/\ssrc\s*=\s*[\'"]*\S+display-attachment\S+file=rcmfile' . preg_quote($attachment['id']) . '[\s\'"]\s*/';
367 $message_body = $MAIL_MIME->getHTMLBody();
368 if ($isHtml && (preg_match($dispurl, $message_body) > 0)) {
369 $message_body = preg_replace($dispurl, ' src="'.$attachment['name'].'" ', $message_body);
370 $MAIL_MIME->setHTMLBody($message_body);
372 if ($attachment['data'])
373 $MAIL_MIME->addHTMLImage($attachment['data'], $attachment['mimetype'], $attachment['name'], false);
375 $MAIL_MIME->addHTMLImage($attachment['path'], $attachment['mimetype'], $attachment['name'], true);
378 $ctype = str_replace('image/pjpeg', 'image/jpeg', $attachment['mimetype']); // #1484914
379 $file = $attachment['data'] ? $attachment['data'] : $attachment['path'];
381 // .eml attachments send inline
382 $MAIL_MIME->addAttachment($file,
385 ($attachment['data'] ? false : true),
386 ($ctype == 'message/rfc822' ? $transfer_encoding : 'base64'),
387 ($ctype == 'message/rfc822' ? 'inline' : 'attachment'),
388 $message_charset, '', '',
389 $CONFIG['mime_param_folding'] ? 'quoted-printable' : NULL,
390 $CONFIG['mime_param_folding'] == 2 ? 'quoted-printable' : NULL
396 // add submitted attachments
397 if (is_array($_FILES['_attachments']['tmp_name'])) {
398 foreach ($_FILES['_attachments']['tmp_name'] as $i => $filepath) {
399 $ctype = $files['type'][$i];
400 $ctype = str_replace('image/pjpeg', 'image/jpeg', $ctype); // #1484914
402 $MAIL_MIME->addAttachment($filepath, $ctype, $files['name'][$i], true,
403 $ctype == 'message/rfc822' ? $transfer_encoding : 'base64',
404 'attachment', $message_charset, '', '',
405 $CONFIG['mime_param_folding'] ? 'quoted-printable' : NULL,
406 $CONFIG['mime_param_folding'] == 2 ? 'quoted-printable' : NULL
411 // encoding settings for mail composing
412 $MAIL_MIME->setParam(array(
413 'text_encoding' => $transfer_encoding,
414 'html_encoding' => 'quoted-printable',
415 'head_encoding' => 'quoted-printable',
416 'head_charset' => $message_charset,
417 'html_charset' => $message_charset,
418 'text_charset' => $message_charset,
421 $data = $RCMAIL->plugins->exec_hook('outgoing_message_headers', array('headers' => $headers));
422 $headers = $data['headers'];
424 // encoding subject header with mb_encode provides better results with asian characters
425 if (function_exists("mb_encode_mimeheader"))
427 mb_internal_encoding($message_charset);
428 $headers['Subject'] = mb_encode_mimeheader($headers['Subject'], $message_charset, 'Q');
429 mb_internal_encoding(RCMAIL_CHARSET);
432 // pass headers to message object
433 $MAIL_MIME->headers($headers);
435 // Begin SMTP Delivery Block
438 // check for 'From' address (identity may be incomplete)
439 if ($identity_arr && !$identity_arr['mailto']) {
440 $OUTPUT->show_message('nofromaddress', 'error');
441 $OUTPUT->send('iframe');
444 $sent = rcmail_deliver_message($MAIL_MIME, $from, $mailto, $smtp_error);
446 // return to compose page if sending failed
450 $OUTPUT->show_message($smtp_error['label'], 'error', $smtp_error['vars']);
452 $OUTPUT->show_message('sendingfailed', 'error');
453 $OUTPUT->send('iframe');
456 // save message sent time
457 if (!empty($CONFIG['sendmail_delay']))
458 $RCMAIL->user->save_prefs(array('last_message_time' => time()));
460 // set replied/forwarded flag
461 if ($_SESSION['compose']['reply_uid'])
462 $IMAP->set_flag($_SESSION['compose']['reply_uid'], 'ANSWERED', $_SESSION['compose']['mailbox']);
463 else if ($_SESSION['compose']['forward_uid'])
464 $IMAP->set_flag($_SESSION['compose']['forward_uid'], 'FORWARDED', $_SESSION['compose']['mailbox']);
466 } // End of SMTP Delivery Block
470 // Determine which folder to save message
472 $store_target = $CONFIG['drafts_mbox'];
474 $store_target = isset($_POST['_store_target']) ? get_input_value('_store_target', RCUBE_INPUT_POST) : $CONFIG['sent_mbox'];
478 // check if mailbox exists
479 if (!in_array_nocase($store_target, $IMAP->list_mailboxes()))
481 // folder may be existing but not subscribed (#1485241)
482 if (!in_array_nocase($store_target, $IMAP->list_unsubscribed()))
483 $store_folder = $IMAP->create_mailbox($store_target, TRUE);
484 else if ($IMAP->subscribe($store_target))
485 $store_folder = TRUE;
488 $store_folder = TRUE;
490 // append message to sent box
492 $saved = $IMAP->save_message($store_target, $MAIL_MIME->getMessage());
494 // raise error if saving failed
497 raise_error(array('code' => 800, 'type' => 'imap', 'file' => __FILE__,
498 'message' => "Could not save message in $store_target"), TRUE, FALSE);
501 $OUTPUT->show_message('errorsaving', 'error');
502 $OUTPUT->send('iframe');
506 if ($olddraftmessageid)
508 // delete previous saved draft
509 $a_deleteid = $IMAP->search($CONFIG['drafts_mbox'], 'HEADER Message-ID '.$olddraftmessageid);
511 $deleted = $IMAP->delete_message($IMAP->get_uid($a_deleteid[0], $CONFIG['drafts_mbox']), $CONFIG['drafts_mbox']);
513 // raise error if deletion of old draft failed
515 raise_error(array('code' => 800, 'type' => 'imap', 'file' => __FILE__,
516 'message' => "Could not delete message from ".$CONFIG['drafts_mbox']), TRUE, FALSE);
522 $msgid = strtr($message_id, array('>' => '', '<' => ''));
524 // remember new draft-uid
525 $draftids = $IMAP->search($CONFIG['drafts_mbox'], 'HEADER Message-ID '.$msgid);
526 $_SESSION['compose']['param']['_draft_uid'] = $IMAP->get_uid($draftids[0], $CONFIG['drafts_mbox']);
529 $OUTPUT->show_message('messagesaved', 'confirmation');
531 // update "_draft_saveid" and the "cmp_hash" to prevent "Unsaved changes" warning
532 $OUTPUT->command('set_draft_id', $msgid);
533 $OUTPUT->command('compose_field_hash', true);
535 // start the auto-save timer again
536 $OUTPUT->command('auto_save_start');
538 $OUTPUT->send('iframe');
542 rcmail_compose_cleanup();
544 if ($store_folder && !$saved)
545 $OUTPUT->command('sent_successfully', 'error', rcube_label('errorsavingsent'));
547 $OUTPUT->command('sent_successfully', 'confirmation', rcube_label('messagesent'));
548 $OUTPUT->send('iframe');