4 +-----------------------------------------------------------------------+
5 | program/steps/mail/sendmail.inc |
7 | This file is part of the RoundCube Webmail client |
8 | Copyright (C) 2005-2008, 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 2193 2008-12-29 14:43:45Z 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, '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 $htmlContents = $mime_message->getHtmlBody();
103 // remove any null-byte characters before parsing
104 $body = preg_replace('/\x00/', '', $htmlContents);
107 $searchstr = 'program/js/tiny_mce/plugins/emotions/img/';
108 $path_len = strlen(INSTALL_PATH . '/');
110 // keep track of added images, so they're only added once
111 $included_images = array();
113 // find emoticon image tags
114 while ($pos = strpos($body, $searchstr, $last_img_pos))
116 $pos2 = strpos($body, '"', $pos);
117 $body_pre = substr($body, 0, $pos);
118 $body_post = substr($body, $pos2);
120 $image_name = substr($body,
121 $pos + strlen($searchstr),
122 $pos2 - ($pos + strlen($searchstr)));
124 // sanitize image name so resulting attachment doesn't leave images dir
125 $image_name = preg_replace('/[^a-zA-Z0-9_\.\-]/i','',$image_name);
126 $img_file = INSTALL_PATH . '/' . $searchstr . $image_name;
128 if (! in_array($image_name, $included_images))
130 // add the image to the MIME message
131 if(! $mime_message->addHTMLImage($img_file, 'image/gif', '', true, $image_name))
132 $OUTPUT->show_message("emoticonerror", 'error');
133 array_push($included_images, $image_name);
136 $body = $body_pre . $img_file . $body_post;
138 $last_img_pos = $pos2 + $path_len;
141 $mime_message->setHTMLBody($body);
145 /****** compose message ********/
147 if (strlen($_POST['_draft_saveid']) > 3)
148 $olddraftmessageid = get_input_value('_draft_saveid', RCUBE_INPUT_POST);
150 $message_id = sprintf('<%s@%s>', md5(uniqid('rcmail'.rand(),true)), $RCMAIL->config->mail_domain($_SESSION['imap_host']));
152 // set default charset
153 $input_charset = $OUTPUT->get_charset();
154 $message_charset = isset($_POST['_charset']) ? $_POST['_charset'] : $input_charset;
156 $mailto_regexp = array('/[,;]\s*[\r\n]+/', '/[\r\n]+/', '/[,;]\s*$/m', '/;/', '/(\S{1})(<\S+@\S+>)/U');
157 $mailto_replace = array(', ', ', ', '', ',', '\\1 \\2');
159 // replace new lines and strip ending ', ', make address strings more valid also
160 $mailto = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_to', RCUBE_INPUT_POST, TRUE, $message_charset));
161 $mailcc = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_cc', RCUBE_INPUT_POST, TRUE, $message_charset));
162 $mailbcc = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_bcc', RCUBE_INPUT_POST, TRUE, $message_charset));
164 if (empty($mailto) && !empty($mailcc)) {
168 else if (empty($mailto))
169 $mailto = 'undisclosed-recipients:;';
171 // get sender name and address
172 $from = get_input_value('_from', RCUBE_INPUT_POST);
173 $identity_arr = rcmail_get_identity($from);
176 $from = $identity_arr['mailto'];
178 if (empty($identity_arr['string']))
179 $identity_arr['string'] = $from;
181 // compose headers array
182 $headers = array('Date' => date('r'),
183 'From' => rcube_charset_convert($identity_arr['string'], RCMAIL_CHARSET, $message_charset),
186 // additional recipients
188 $headers['Cc'] = $mailcc;
190 if (!empty($mailbcc))
191 $headers['Bcc'] = $mailbcc;
193 if (!empty($identity_arr['bcc']))
194 $headers['Bcc'] = ($headers['Bcc'] ? $headers['Bcc'].', ' : '') . $identity_arr['bcc'];
197 $headers['Subject'] = trim(get_input_value('_subject', RCUBE_INPUT_POST, FALSE, $message_charset));
199 if (!empty($identity_arr['organization']))
200 $headers['Organization'] = $identity_arr['organization'];
202 if (!empty($_POST['_replyto']))
203 $headers['Reply-To'] = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_replyto', RCUBE_INPUT_POST, TRUE, $message_charset));
204 else if (!empty($identity_arr['reply-to']))
205 $headers['Reply-To'] = $identity_arr['reply-to'];
207 if (!empty($_SESSION['compose']['reply_msgid']))
208 $headers['In-Reply-To'] = $_SESSION['compose']['reply_msgid'];
210 if (!empty($_SESSION['compose']['references']))
211 $headers['References'] = $_SESSION['compose']['references'];
213 if (!empty($_POST['_priority']))
215 $priority = intval($_POST['_priority']);
216 $a_priorities = array(1=>'highest', 2=>'high', 4=>'low', 5=>'lowest');
217 if ($str_priority = $a_priorities[$priority])
218 $headers['X-Priority'] = sprintf("%d (%s)", $priority, ucfirst($str_priority));
221 if (!empty($_POST['_receipt']))
223 $headers['Return-Receipt-To'] = $identity_arr['string'];
224 $headers['Disposition-Notification-To'] = $identity_arr['string'];
227 // additional headers
228 if ($CONFIG['http_received_header'])
230 $nldlm = $RCMAIL->config->header_delimiter() . "\t";
231 $headers['Received'] = wordwrap('from ' . (isset($_SERVER['HTTP_X_FORWARDED_FOR']) ?
232 gethostbyaddr($_SERVER['HTTP_X_FORWARDED_FOR']).' ['.$_SERVER['HTTP_X_FORWARDED_FOR'].']'.$nldlm.' via ' : '') .
233 gethostbyaddr($_SERVER['REMOTE_ADDR']).' ['.$_SERVER['REMOTE_ADDR'].']'.$nldlm.'with ' .
234 $_SERVER['SERVER_PROTOCOL'].' ('.$_SERVER['REQUEST_METHOD'].'); ' . date('r'),
238 $headers['Message-ID'] = $message_id;
239 $headers['X-Sender'] = $from;
241 if (!empty($CONFIG['useragent']))
242 $headers['User-Agent'] = $CONFIG['useragent'];
244 $isHtmlVal = strtolower(get_input_value('_is_html', RCUBE_INPUT_POST));
245 $isHtml = ($isHtmlVal == "1");
247 // fetch message body
248 $message_body = get_input_value('_message', RCUBE_INPUT_POST, TRUE, $message_charset);
250 // remove signature's div ID
251 if (!$savedraft && $isHtml)
252 $message_body = preg_replace('/\s*id="_rc_sig"/', '', $message_body);
254 // append generic footer to all messages
255 if (!$savedraft && !empty($CONFIG['generic_message_footer']) && ($footer = file_get_contents(realpath($CONFIG['generic_message_footer']))))
256 $message_body .= "\r\n" . rcube_charset_convert($footer, 'UTF-8', $message_charset);
258 // create extended PEAR::Mail_mime instance
259 $MAIL_MIME = new rcube_mail_mime($RCMAIL->config->header_delimiter());
261 // For HTML-formatted messages, construct the MIME message with both
262 // the HTML part and the plain-text part
266 $MAIL_MIME->setHTMLBody($message_body);
268 // add a plain text version of the e-mail as an alternative part.
269 $h2t = new html2text($message_body);
270 $plainTextPart = wordwrap($h2t->get_text(), 998, "\r\n", true);
271 if (!strlen($plainTextPart))
273 // empty message body breaks attachment handling in drafts
274 $plainTextPart = "\r\n";
276 $MAIL_MIME->setTXTBody($plainTextPart);
278 // look for "emoticon" images from TinyMCE and copy into message as attachments
279 rcmail_attach_emoticons($MAIL_MIME);
283 $message_body = wordwrap($message_body, 75, "\r\n");
284 $message_body = wordwrap($message_body, 998, "\r\n", true);
285 if (!strlen($message_body))
287 // empty message body breaks attachment handling in drafts
288 $message_body = "\r\n";
290 $MAIL_MIME->setTXTBody($message_body, FALSE, TRUE);
293 // chose transfer encoding
294 $charset_7bit = array('ASCII', 'ISO-2022-JP', 'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-15');
295 $transfer_encoding = in_array(strtoupper($message_charset), $charset_7bit) ? '7bit' : '8bit';
297 // add stored attachments, if any
298 if (is_array($_SESSION['compose']['attachments']))
299 foreach ($_SESSION['compose']['attachments'] as $id => $attachment)
301 $dispurl = '/\ssrc\s*=\s*[\'"]?\S+display-attachment\S+file=rcmfile' . $id . '[\'"]?/';
302 $match = preg_match($dispurl, $message_body);
303 if ($isHtml && ($match > 0))
305 $message_body = preg_replace($dispurl, ' src="'.$attachment['name'].'"', $message_body);
306 $MAIL_MIME->setHTMLBody($message_body);
307 $MAIL_MIME->addHTMLImage($attachment['path'], $attachment['mimetype'], $attachment['name']);
311 $ctype = str_replace('image/pjpeg', 'image/jpeg', $attachment['mimetype']); // #1484914
313 // .eml attachments send inline
314 $MAIL_MIME->addAttachment($attachment['path'],
316 $attachment['name'], true,
317 ($ctype == 'message/rfc822' ? $transfer_encoding : 'base64'),
318 ($ctype == 'message/rfc822' ? 'inline' : 'attachment'),
319 $message_charset, '', '',
320 $CONFIG['mime_param_folding'] ? 'quoted-printable' : NULL,
321 $CONFIG['mime_param_folding'] == 2 ? 'quoted-printable' : NULL
326 // add submitted attachments
327 if (is_array($_FILES['_attachments']['tmp_name']))
328 foreach ($_FILES['_attachments']['tmp_name'] as $i => $filepath)
330 $ctype = $files['type'][$i];
331 $ctype = str_replace('image/pjpeg', 'image/jpeg', $ctype); // #1484914
333 $MAIL_MIME->addAttachment($filepath, $ctype, $files['name'][$i], true,
334 $ctype == 'message/rfc822' ? $transfer_encoding : 'base64',
335 'attachment', $message_charset, '', '',
336 $CONFIG['mime_param_folding'] ? 'quoted-printable' : NULL,
337 $CONFIG['mime_param_folding'] == 2 ? 'quoted-printable' : NULL
342 // encoding settings for mail composing
343 $MAIL_MIME->setParam(array(
344 'text_encoding' => $transfer_encoding,
345 'html_encoding' => 'quoted-printable',
346 'head_encoding' => 'quoted-printable',
347 'head_charset' => $message_charset,
348 'html_charset' => $message_charset,
349 'text_charset' => $message_charset,
352 // encoding subject header with mb_encode provides better results with asian characters
353 if (function_exists("mb_encode_mimeheader"))
355 mb_internal_encoding($message_charset);
356 $headers['Subject'] = mb_encode_mimeheader($headers['Subject'], $message_charset, 'Q');
357 mb_internal_encoding(RCMAIL_CHARSET);
360 // pass headers to message object
361 $MAIL_MIME->headers($headers);
363 // Begin SMTP Delivery Block
366 // check for 'From' address (identity may be incomplete)
367 if ($identity_arr && !$identity_arr['mailto']) {
368 $OUTPUT->show_message('nofromaddress', 'error');
369 $OUTPUT->send('iframe');
372 $sent = rcmail_deliver_message($MAIL_MIME, $from, $mailto);
374 // return to compose page if sending failed
377 $OUTPUT->show_message("sendingfailed", 'error');
378 $OUTPUT->send('iframe');
381 // save message sent time
382 if (!empty($CONFIG['sendmail_delay']))
383 $RCMAIL->user->save_prefs(array('last_message_time' => time()));
385 // set replied/forwarded flag
386 if ($_SESSION['compose']['reply_uid'])
387 $IMAP->set_flag($_SESSION['compose']['reply_uid'], 'ANSWERED');
388 else if ($_SESSION['compose']['forward_uid'])
389 $IMAP->set_flag($_SESSION['compose']['forward_uid'], 'FORWARDED');
391 } // End of SMTP Delivery Block
395 // Determine which folder to save message
397 $store_target = $CONFIG['drafts_mbox'];
399 $store_target = isset($_POST['_store_target']) ? get_input_value('_store_target', RCUBE_INPUT_POST) : $CONFIG['sent_mbox'];
403 // check if mailbox exists
404 if (!in_array_nocase($store_target, $IMAP->list_mailboxes()))
406 // folder may be existing but not subscribed (#1485241)
407 if (!in_array_nocase($store_target, $IMAP->list_unsubscribed()))
408 $store_folder = $IMAP->create_mailbox($store_target, TRUE);
409 else if ($IMAP->subscribe($store_target))
410 $store_folder = TRUE;
413 $store_folder = TRUE;
415 // append message to sent box
417 $saved = $IMAP->save_message($store_target, $MAIL_MIME->getMessage());
419 // raise error if saving failed
422 raise_error(array('code' => 800, 'type' => 'imap', 'file' => __FILE__,
423 'message' => "Could not save message in $store_target"), TRUE, FALSE);
426 $OUTPUT->show_message('errorsaving', 'error');
427 $OUTPUT->send('iframe');
431 if ($olddraftmessageid)
433 // delete previous saved draft
434 $a_deleteid = $IMAP->search($CONFIG['drafts_mbox'], 'HEADER Message-ID '.$olddraftmessageid);
436 $deleted = $IMAP->delete_message($IMAP->get_uid($a_deleteid[0], $CONFIG['drafts_mbox']), $CONFIG['drafts_mbox']);
438 // raise error if deletion of old draft failed
440 raise_error(array('code' => 800, 'type' => 'imap', 'file' => __FILE__,
441 'message' => "Could not delete message from ".$CONFIG['drafts_mbox']), TRUE, FALSE);
447 $msgid = strtr($message_id, array('>' => '', '<' => ''));
449 // remember new draft-uid
450 $draftids = $IMAP->search($CONFIG['drafts_mbox'], 'HEADER Message-ID '.$msgid);
451 $_SESSION['compose']['param']['_draft_uid'] = $IMAP->get_uid($draftids[0], $CONFIG['drafts_mbox']);
454 $OUTPUT->show_message('messagesaved', 'confirmation');
456 // update "_draft_saveid" and the "cmp_hash" to prevent "Unsaved changes" warning
457 $OUTPUT->command('set_draft_id', $msgid);
458 $OUTPUT->command('compose_field_hash', true);
460 // start the auto-save timer again
461 $OUTPUT->command('auto_save_start');
463 $OUTPUT->send('iframe');
467 rcmail_compose_cleanup();
469 if ($store_folder && !$saved)
470 $OUTPUT->command('sent_successfully', 'error', rcube_label('errorsavingsent'));
472 $OUTPUT->command('sent_successfully', 'confirmation', rcube_label('messagesent'));
473 $OUTPUT->send('iframe');