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 2320 2009-03-01 07:55:39Z 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 // get identity record
59 function rcmail_get_identity($id)
61 global $USER, $OUTPUT;
63 if ($sql_arr = $USER->get_identity($id))
66 $out['mailto'] = $sql_arr['email'];
68 // Special chars as defined by RFC 822 need to in quoted string (or escaped).
69 if (preg_match('/[\(\)\<\>\\\.\[\]@,;:"]/', $sql_arr['name']))
70 $name = '"' . addcslashes($sql_arr['name'], '"') . '"';
72 $name = $sql_arr['name'];
74 $out['string'] = rcube_charset_convert($name, RCMAIL_CHARSET, $OUTPUT->get_charset());
75 if ($sql_arr['email'])
76 $out['string'] .= ' <' . $sql_arr['email'] . '>';
86 * <img src=".../tiny_mce/plugins/emotions/images/smiley-cool.gif" border="0" alt="Cool" title="Cool" />
90 * <IMG src="cid:smiley-cool.gif"/>
93 * Content-Type: image/gif
94 * Content-Transfer-Encoding: base64
95 * Content-ID: <smiley-cool.gif>
97 function rcmail_attach_emoticons(&$mime_message)
101 $body = $mime_message->getHtmlBody();
103 // remove any null-byte characters before parsing
104 $body = preg_replace('/\x00/', '', $body);
106 $searchstr = 'program/js/tiny_mce/plugins/emotions/img/';
109 // keep track of added images, so they're only added once
110 $included_images = array();
112 if (preg_match_all('# src=[\'"]([^\'"]+)#', $body, $matches, PREG_OFFSET_CAPTURE)) {
113 foreach ($matches[1] as $m) {
114 // find emoticon image tags
115 if (preg_match('#'.$searchstr.'(.*)$#', $m[0], $imatches)) {
116 $image_name = $imatches[1];
118 // sanitize image name so resulting attachment doesn't leave images dir
119 $image_name = preg_replace('/[^a-zA-Z0-9_\.\-]/i', '', $image_name);
120 $img_file = INSTALL_PATH . '/' . $searchstr . $image_name;
122 if (! in_array($image_name, $included_images)) {
123 // add the image to the MIME message
124 if(! $mime_message->addHTMLImage($img_file, 'image/gif', '', true, $image_name))
125 $OUTPUT->show_message("emoticonerror", 'error');
126 array_push($included_images, $image_name);
129 $body = substr_replace($body, $img_file, $m[1] + $offset, strlen($m[0]));
130 $offset += strlen($img_file) - strlen($m[0]);
135 $mime_message->setHTMLBody($body);
140 // parse email address input
141 function rcmail_mailto_format($mailto)
143 $regexp = array('/[,;]\s*[\r\n]+/', '/[\r\n]+/', '/[,;]\s*$/m', '/;/', '/(\S{1})(<\S+@\S+>)/U');
144 $replace = array(', ', ', ', '', ',', '\\1 \\2');
146 // replace new lines and strip ending ', ', make address input more valid
147 $mailto = trim(preg_replace($regexp, $replace, $mailto));
150 $items = rcube_explode_quoted_string(',', $mailto);
152 foreach($items as $item) {
154 // address in brackets without name (do nothing)
155 if (preg_match('/^<\S+@\S+>$/', $item)) {
157 // address without brackets and without name (add brackets)
158 } else if (preg_match('/^\S+@\S+$/', $item)) {
159 $result[] = '<'.$item.'>';
160 // address with name (handle name)
161 } else if (preg_match('/\S+@\S+>*$/', $item, $matches)) {
162 $address = $matches[0];
163 $name = str_replace($address, '', $item);
165 if ($name && ($name[0] != '"' || $name[strlen($name)-1] != '"')
166 && preg_match('/[\(\)\<\>\\\.\[\]@,;:"]/', $name)) {
167 $name = '"'.addcslashes($name, '"').'"';
169 if (!preg_match('/^<\S+@\S+>$/', $address))
170 $address = '<'.$address.'>';
172 $result[] = $name.' '.$address;
173 } else if (trim($item)) {
174 // @TODO: handle errors
178 return implode(', ', $result);
181 /****** compose message ********/
183 if (strlen($_POST['_draft_saveid']) > 3)
184 $olddraftmessageid = get_input_value('_draft_saveid', RCUBE_INPUT_POST);
186 $message_id = sprintf('<%s@%s>', md5(uniqid('rcmail'.rand(),true)), $RCMAIL->config->mail_domain($_SESSION['imap_host']));
188 // set default charset
189 $input_charset = $OUTPUT->get_charset();
190 $message_charset = isset($_POST['_charset']) ? $_POST['_charset'] : $input_charset;
192 $mailto = rcmail_mailto_format(get_input_value('_to', RCUBE_INPUT_POST, TRUE, $message_charset));
193 $mailcc = rcmail_mailto_format(get_input_value('_cc', RCUBE_INPUT_POST, TRUE, $message_charset));
194 $mailbcc = rcmail_mailto_format(get_input_value('_bcc', RCUBE_INPUT_POST, TRUE, $message_charset));
196 if (empty($mailto) && !empty($mailcc)) {
200 else if (empty($mailto))
201 $mailto = 'undisclosed-recipients:;';
203 // get sender name and address
204 $from = get_input_value('_from', RCUBE_INPUT_POST);
205 $identity_arr = rcmail_get_identity($from);
208 $from = $identity_arr['mailto'];
210 if (empty($identity_arr['string']))
211 $identity_arr['string'] = $from;
213 // compose headers array
214 $headers = array('Date' => date('r'),
215 'From' => rcube_charset_convert($identity_arr['string'], RCMAIL_CHARSET, $message_charset),
218 // additional recipients
220 $headers['Cc'] = $mailcc;
222 if (!empty($mailbcc))
223 $headers['Bcc'] = $mailbcc;
225 if (!empty($identity_arr['bcc']))
226 $headers['Bcc'] = ($headers['Bcc'] ? $headers['Bcc'].', ' : '') . $identity_arr['bcc'];
229 $headers['Subject'] = trim(get_input_value('_subject', RCUBE_INPUT_POST, FALSE, $message_charset));
231 if (!empty($identity_arr['organization']))
232 $headers['Organization'] = $identity_arr['organization'];
234 if (!empty($_POST['_replyto']))
235 $headers['Reply-To'] = rcmail_mailto_format(get_input_value('_replyto', RCUBE_INPUT_POST, TRUE, $message_charset));
236 else if (!empty($identity_arr['reply-to']))
237 $headers['Reply-To'] = $identity_arr['reply-to'];
239 if (!empty($_SESSION['compose']['reply_msgid']))
240 $headers['In-Reply-To'] = $_SESSION['compose']['reply_msgid'];
242 if (!empty($_SESSION['compose']['references']))
243 $headers['References'] = $_SESSION['compose']['references'];
245 if (!empty($_POST['_priority']))
247 $priority = intval($_POST['_priority']);
248 $a_priorities = array(1=>'highest', 2=>'high', 4=>'low', 5=>'lowest');
249 if ($str_priority = $a_priorities[$priority])
250 $headers['X-Priority'] = sprintf("%d (%s)", $priority, ucfirst($str_priority));
253 if (!empty($_POST['_receipt']))
255 $headers['Return-Receipt-To'] = $identity_arr['string'];
256 $headers['Disposition-Notification-To'] = $identity_arr['string'];
259 // additional headers
260 if ($CONFIG['http_received_header'])
262 $nldlm = $RCMAIL->config->header_delimiter() . "\t";
263 $headers['Received'] = wordwrap('from ' . (isset($_SERVER['HTTP_X_FORWARDED_FOR']) ?
264 gethostbyaddr($_SERVER['HTTP_X_FORWARDED_FOR']).' ['.$_SERVER['HTTP_X_FORWARDED_FOR'].']'.$nldlm.' via ' : '') .
265 gethostbyaddr($_SERVER['REMOTE_ADDR']).' ['.$_SERVER['REMOTE_ADDR'].']'.$nldlm.'with ' .
266 $_SERVER['SERVER_PROTOCOL'].' ('.$_SERVER['REQUEST_METHOD'].'); ' . date('r'),
270 $headers['Message-ID'] = $message_id;
271 $headers['X-Sender'] = $from;
273 if (!empty($CONFIG['useragent']))
274 $headers['User-Agent'] = $CONFIG['useragent'];
276 $isHtmlVal = strtolower(get_input_value('_is_html', RCUBE_INPUT_POST));
277 $isHtml = ($isHtmlVal == "1");
279 // fetch message body
280 $message_body = get_input_value('_message', RCUBE_INPUT_POST, TRUE, $message_charset);
283 // remove signature's div ID
285 $message_body = preg_replace('/\s*id="_rc_sig"/', '', $message_body);
287 // generic footer for all messages
288 if (!empty($CONFIG['generic_message_footer'])) {
289 $footer = file_get_contents(realpath($CONFIG['generic_message_footer']));
290 $footer = rcube_charset_convert($footer, 'UTF-8', $message_charset);
294 // create extended PEAR::Mail_mime instance
295 $MAIL_MIME = new rcube_mail_mime($RCMAIL->config->header_delimiter());
297 // For HTML-formatted messages, construct the MIME message with both
298 // the HTML part and the plain-text part
302 $MAIL_MIME->setHTMLBody($message_body . ($footer ? "\r\n<pre>".$footer.'</pre>' : ''));
304 // add a plain text version of the e-mail as an alternative part.
305 $h2t = new html2text($message_body);
306 $plainTextPart = $h2t->get_text() . ($footer ? "\r\n".$footer : '');
307 $plainTextPart = wordwrap($plainTextPart, 998, "\r\n", true);
308 if (!strlen($plainTextPart))
310 // empty message body breaks attachment handling in drafts
311 $plainTextPart = "\r\n";
313 $MAIL_MIME->setTXTBody($plainTextPart);
315 // look for "emoticon" images from TinyMCE and copy into message as attachments
316 $message_body = rcmail_attach_emoticons($MAIL_MIME);
320 $message_body = wordwrap($message_body, 75, "\r\n");
322 $message_body .= "\r\n" . $footer;
323 $message_body = wordwrap($message_body, 998, "\r\n", true);
324 if (!strlen($message_body))
326 // empty message body breaks attachment handling in drafts
327 $message_body = "\r\n";
329 $MAIL_MIME->setTXTBody($message_body, FALSE, TRUE);
332 // chose transfer encoding
333 $charset_7bit = array('ASCII', 'ISO-2022-JP', 'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-15');
334 $transfer_encoding = in_array(strtoupper($message_charset), $charset_7bit) ? '7bit' : '8bit';
336 // add stored attachments, if any
337 if (is_array($_SESSION['compose']['attachments']))
338 foreach ($_SESSION['compose']['attachments'] as $id => $attachment)
340 $dispurl = '/\ssrc\s*=\s*[\'"]*\S+display-attachment\S+file=rcmfile' . $id . '[\s\'"]\s*/';
341 $match = preg_match($dispurl, $message_body, $matches);
342 if ($isHtml && ($match > 0))
344 $message_body = preg_replace($dispurl, ' src="'.$attachment['name'].'" ', $message_body);
345 $MAIL_MIME->setHTMLBody($message_body. ($footer ? "\r\n<pre>".$footer.'</pre>' : ''));
346 $MAIL_MIME->addHTMLImage($attachment['path'], $attachment['mimetype'], $attachment['name']);
350 $ctype = str_replace('image/pjpeg', 'image/jpeg', $attachment['mimetype']); // #1484914
352 // .eml attachments send inline
353 $MAIL_MIME->addAttachment($attachment['path'],
355 $attachment['name'], true,
356 ($ctype == 'message/rfc822' ? $transfer_encoding : 'base64'),
357 ($ctype == 'message/rfc822' ? 'inline' : 'attachment'),
358 $message_charset, '', '',
359 $CONFIG['mime_param_folding'] ? 'quoted-printable' : NULL,
360 $CONFIG['mime_param_folding'] == 2 ? 'quoted-printable' : NULL
365 // add submitted attachments
366 if (is_array($_FILES['_attachments']['tmp_name']))
367 foreach ($_FILES['_attachments']['tmp_name'] as $i => $filepath)
369 $ctype = $files['type'][$i];
370 $ctype = str_replace('image/pjpeg', 'image/jpeg', $ctype); // #1484914
372 $MAIL_MIME->addAttachment($filepath, $ctype, $files['name'][$i], true,
373 $ctype == 'message/rfc822' ? $transfer_encoding : 'base64',
374 'attachment', $message_charset, '', '',
375 $CONFIG['mime_param_folding'] ? 'quoted-printable' : NULL,
376 $CONFIG['mime_param_folding'] == 2 ? 'quoted-printable' : NULL
381 // encoding settings for mail composing
382 $MAIL_MIME->setParam(array(
383 'text_encoding' => $transfer_encoding,
384 'html_encoding' => 'quoted-printable',
385 'head_encoding' => 'quoted-printable',
386 'head_charset' => $message_charset,
387 'html_charset' => $message_charset,
388 'text_charset' => $message_charset,
391 // encoding subject header with mb_encode provides better results with asian characters
392 if (function_exists("mb_encode_mimeheader"))
394 mb_internal_encoding($message_charset);
395 $headers['Subject'] = mb_encode_mimeheader($headers['Subject'], $message_charset, 'Q');
396 mb_internal_encoding(RCMAIL_CHARSET);
399 // pass headers to message object
400 $MAIL_MIME->headers($headers);
402 // Begin SMTP Delivery Block
405 // check for 'From' address (identity may be incomplete)
406 if ($identity_arr && !$identity_arr['mailto']) {
407 $OUTPUT->show_message('nofromaddress', 'error');
408 $OUTPUT->send('iframe');
411 $sent = rcmail_deliver_message($MAIL_MIME, $from, $mailto);
413 // return to compose page if sending failed
416 $OUTPUT->show_message("sendingfailed", 'error');
417 $OUTPUT->send('iframe');
420 // save message sent time
421 if (!empty($CONFIG['sendmail_delay']))
422 $RCMAIL->user->save_prefs(array('last_message_time' => time()));
424 // set replied/forwarded flag
425 if ($_SESSION['compose']['reply_uid'])
426 $IMAP->set_flag($_SESSION['compose']['reply_uid'], 'ANSWERED');
427 else if ($_SESSION['compose']['forward_uid'])
428 $IMAP->set_flag($_SESSION['compose']['forward_uid'], 'FORWARDED');
430 } // End of SMTP Delivery Block
434 // Determine which folder to save message
436 $store_target = $CONFIG['drafts_mbox'];
438 $store_target = isset($_POST['_store_target']) ? get_input_value('_store_target', RCUBE_INPUT_POST) : $CONFIG['sent_mbox'];
442 // check if mailbox exists
443 if (!in_array_nocase($store_target, $IMAP->list_mailboxes()))
445 // folder may be existing but not subscribed (#1485241)
446 if (!in_array_nocase($store_target, $IMAP->list_unsubscribed()))
447 $store_folder = $IMAP->create_mailbox($store_target, TRUE);
448 else if ($IMAP->subscribe($store_target))
449 $store_folder = TRUE;
452 $store_folder = TRUE;
454 // append message to sent box
456 $saved = $IMAP->save_message($store_target, $MAIL_MIME->getMessage());
458 // raise error if saving failed
461 raise_error(array('code' => 800, 'type' => 'imap', 'file' => __FILE__,
462 'message' => "Could not save message in $store_target"), TRUE, FALSE);
465 $OUTPUT->show_message('errorsaving', 'error');
466 $OUTPUT->send('iframe');
470 if ($olddraftmessageid)
472 // delete previous saved draft
473 $a_deleteid = $IMAP->search($CONFIG['drafts_mbox'], 'HEADER Message-ID '.$olddraftmessageid);
475 $deleted = $IMAP->delete_message($IMAP->get_uid($a_deleteid[0], $CONFIG['drafts_mbox']), $CONFIG['drafts_mbox']);
477 // raise error if deletion of old draft failed
479 raise_error(array('code' => 800, 'type' => 'imap', 'file' => __FILE__,
480 'message' => "Could not delete message from ".$CONFIG['drafts_mbox']), TRUE, FALSE);
486 $msgid = strtr($message_id, array('>' => '', '<' => ''));
488 // remember new draft-uid
489 $draftids = $IMAP->search($CONFIG['drafts_mbox'], 'HEADER Message-ID '.$msgid);
490 $_SESSION['compose']['param']['_draft_uid'] = $IMAP->get_uid($draftids[0], $CONFIG['drafts_mbox']);
493 $OUTPUT->show_message('messagesaved', 'confirmation');
495 // update "_draft_saveid" and the "cmp_hash" to prevent "Unsaved changes" warning
496 $OUTPUT->command('set_draft_id', $msgid);
497 $OUTPUT->command('compose_field_hash', true);
499 // start the auto-save timer again
500 $OUTPUT->command('auto_save_start');
502 $OUTPUT->send('iframe');
506 rcmail_compose_cleanup();
508 if ($store_folder && !$saved)
509 $OUTPUT->command('sent_successfully', 'error', rcube_label('errorsavingsent'));
511 $OUTPUT->command('sent_successfully', 'confirmation', rcube_label('messagesent'));
512 $OUTPUT->send('iframe');