4 +-----------------------------------------------------------------------+
5 | program/steps/mail/sendmail.inc |
7 | This file is part of the RoundCube Webmail client |
8 | Copyright (C) 2005-2007, 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 1255 2008-04-05 12:49:21Z thomasb $
24 //require_once('lib/smtp.inc');
25 require_once('lib/html2text.inc');
26 require_once('lib/rc_mail_mime.inc');
29 if (!isset($_SESSION['compose']['id']))
31 rcmail_overwrite_action('list');
36 /****** message sending functions ********/
39 // get identity record
40 function rcmail_get_identity($id)
42 global $USER, $OUTPUT;
44 if ($sql_arr = $USER->get_identity($id))
47 $out['mailto'] = $sql_arr['email'];
48 $name = strpos($sql_arr['name'], ",") ? '"'.$sql_arr['name'].'"' : $sql_arr['name'];
49 $out['string'] = sprintf('%s <%s>',
50 rcube_charset_convert($name, RCMAIL_CHARSET, $OUTPUT->get_charset()),
60 * <img src=".../tiny_mce/plugins/emotions/images/smiley-cool.gif" border="0" alt="Cool" title="Cool" />
64 * <IMG src="cid:smiley-cool.gif"/>
67 * Content-Type: image/gif
68 * Content-Transfer-Encoding: base64
69 * Content-ID: <smiley-cool.gif>
71 function rcmail_attach_emoticons(&$mime_message)
73 global $CONFIG, $INSTALL_PATH;
75 $htmlContents = $mime_message->getHtmlBody();
77 // remove any null-byte characters before parsing
78 $body = preg_replace('/\x00/', '', $htmlContents);
82 $searchstr = 'program/js/tiny_mce/plugins/emotions/images/';
84 // keep track of added images, so they're only added once
85 $included_images = array();
87 // find emoticon image tags
88 while ($pos = strpos($body, $searchstr, $last_img_pos))
90 $pos2 = strpos($body, '"', $pos);
91 $body_pre = substr($body, 0, $pos);
92 $image_name = substr($body,
93 $pos + strlen($searchstr),
94 $pos2 - ($pos + strlen($searchstr)));
95 // sanitize image name so resulting attachment doesn't leave images dir
96 $image_name = preg_replace('/[^a-zA-Z0-9_\.\-]/i','',$image_name);
98 $body_post = substr($body, $pos2);
100 if (! in_array($image_name, $included_images))
102 // add the image to the MIME message
103 $img_file = $INSTALL_PATH . '/' . $searchstr . $image_name;
104 if(! $mime_message->addHTMLImage($img_file, 'image/gif', '', true, '_' . $image_name))
105 $OUTPUT->show_message("emoticonerror", 'error');
107 array_push($included_images, $image_name);
110 $body = $body_pre . 'cid:_' . $image_name . $body_post;
112 $last_img_pos = $pos2;
115 $mime_message->setHTMLBody($body);
118 if (strlen($_POST['_draft_saveid']) > 3)
119 $olddraftmessageid = get_input_value('_draft_saveid', RCUBE_INPUT_POST);
121 $message_id = sprintf('<%s@%s>', md5(uniqid('rcmail'.rand(),true)), rcmail_mail_domain($_SESSION['imap_host']));
122 $savedraft = !empty($_POST['_draft']) ? TRUE : FALSE;
124 // remove all scripts and act as called in frame
126 $OUTPUT->framed = TRUE;
129 /****** check submission and compose message ********/
132 if (!$savedraft && empty($_POST['_to']) && empty($_POST['_cc']) && empty($_POST['_bcc']) && empty($_POST['_subject']) && $_POST['_message'])
134 $OUTPUT->show_message("sendingfailed", 'error');
135 $OUTPUT->send('iframe');
140 // set default charset
141 $input_charset = $OUTPUT->get_charset();
142 $message_charset = isset($_POST['_charset']) ? $_POST['_charset'] : $input_charset;
144 $mailto_regexp = array('/[,;]\s*[\r\n]+/', '/[\r\n]+/', '/[,;]\s*$/m', '/;/');
145 $mailto_replace = array(', ', ', ', '', ',');
147 // replace new lines and strip ending ', '
148 $mailto = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_to', RCUBE_INPUT_POST, TRUE, $message_charset));
149 $mailcc = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_cc', RCUBE_INPUT_POST, TRUE, $message_charset));
150 $mailbcc = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_bcc', RCUBE_INPUT_POST, TRUE, $message_charset));
152 if (empty($mailto) && !empty($mailcc)) {
156 else if (empty($mailto))
157 $mailto = 'undisclosed-recipients:;';
159 // get sender name and address
160 $identity_arr = rcmail_get_identity(get_input_value('_from', RCUBE_INPUT_POST));
161 $from = $identity_arr['mailto'];
163 if (empty($identity_arr['string']))
164 $identity_arr['string'] = $from;
166 // compose headers array
167 $headers = array('Date' => date('r'),
168 'From' => rcube_charset_convert($identity_arr['string'], RCMAIL_CHARSET, $message_charset),
171 // additional recipients
173 $headers['Cc'] = $mailcc;
175 if (!empty($mailbcc))
176 $headers['Bcc'] = $mailbcc;
178 if (!empty($identity_arr['bcc']))
179 $headers['Bcc'] = ($headers['Bcc'] ? $headers['Bcc'].', ' : '') . $identity_arr['bcc'];
182 $headers['Subject'] = trim(get_input_value('_subject', RCUBE_INPUT_POST, FALSE, $message_charset));
184 if (!empty($identity_arr['organization']))
185 $headers['Organization'] = $identity_arr['organization'];
187 if (!empty($_POST['_replyto']))
188 $headers['Reply-To'] = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_replyto', RCUBE_INPUT_POST, TRUE, $message_charset));
189 else if (!empty($identity_arr['reply-to']))
190 $headers['Reply-To'] = $identity_arr['reply-to'];
192 if (!empty($_SESSION['compose']['reply_msgid']))
193 $headers['In-Reply-To'] = $_SESSION['compose']['reply_msgid'];
195 if (!empty($_SESSION['compose']['references']))
196 $headers['References'] = $_SESSION['compose']['references'];
198 if (!empty($_POST['_priority']))
200 $priority = intval($_POST['_priority']);
201 $a_priorities = array(1=>'highest', 2=>'high', 4=>'low', 5=>'lowest');
202 if ($str_priority = $a_priorities[$priority])
203 $headers['X-Priority'] = sprintf("%d (%s)", $priority, ucfirst($str_priority));
206 if (!empty($_POST['_receipt']))
208 $headers['Return-Receipt-To'] = $identity_arr['string'];
209 $headers['Disposition-Notification-To'] = $identity_arr['string'];
212 // additional headers
213 $headers['Message-ID'] = $message_id;
214 $headers['X-Sender'] = $from;
216 if ($CONFIG['http_received_header'])
218 $nldlm = rcmail_header_delm() . "\t";
219 $headers['Received'] = wordwrap('from ' . (isset($_SERVER['HTTP_X_FORWARDED_FOR']) ?
220 gethostbyaddr($_SERVER['HTTP_X_FORWARDED_FOR']).' ['.$_SERVER['HTTP_X_FORWARDED_FOR'].']'.$nldlm.' via ' : '') .
221 gethostbyaddr($_SERVER['REMOTE_ADDR']).' ['.$_SERVER['REMOTE_ADDR'].']'.$nldlm.'with ' .
222 $_SERVER['SERVER_PROTOCOL'].' ('.$_SERVER['REQUEST_METHOD'].'); ' . date('r'),
226 if (!empty($CONFIG['useragent']))
227 $headers['User-Agent'] = $CONFIG['useragent'];
229 // fetch message body
230 $message_body = get_input_value('_message', RCUBE_INPUT_POST, TRUE, $message_charset);
232 // append generic footer to all messages
233 if (!$savedraft && !empty($CONFIG['generic_message_footer']) && ($footer = file_get_contents(realpath($CONFIG['generic_message_footer']))))
234 $message_body .= "\r\n" . rcube_charset_convert($footer, 'UTF-8', $message_charset);
236 $isHtmlVal = strtolower(get_input_value('_is_html', RCUBE_INPUT_POST));
237 $isHtml = ($isHtmlVal == "1");
239 // create extended PEAR::Mail_mime instance
240 $MAIL_MIME = new rc_mail_mime(rcmail_header_delm());
242 // For HTML-formatted messages, construct the MIME message with both
243 // the HTML part and the plain-text part
247 $MAIL_MIME->setHTMLBody($message_body);
249 // add a plain text version of the e-mail as an alternative part.
250 $h2t = new html2text($message_body);
251 $plainTextPart = wordwrap($h2t->get_text(), 998, "\r\n", true);
252 if (!strlen($plainTextPart))
254 // empty message body breaks attachment handling in drafts
255 $plainTextPart = "\r\n";
257 $MAIL_MIME->setTXTBody(html_entity_decode($plainTextPart, ENT_COMPAT, 'utf-8'));
259 // look for "emoticon" images from TinyMCE and copy into message as attachments
260 rcmail_attach_emoticons($MAIL_MIME);
264 $message_body = wordwrap($message_body, 75, "\r\n");
265 $message_body = wordwrap($message_body, 998, "\r\n", true);
266 if (!strlen($message_body))
268 // empty message body breaks attachment handling in drafts
269 $message_body = "\r\n";
271 $MAIL_MIME->setTXTBody($message_body, FALSE, TRUE);
275 // add stored attachments, if any
276 if (is_array($_SESSION['compose']['attachments']))
277 foreach ($_SESSION['compose']['attachments'] as $id => $attachment)
279 $dispurl = '/\ssrc\s*=\s*[\'"]?\S+display-attachment\S+file=rcmfile' . $id . '[\'"]?/';
280 $match = preg_match($dispurl, $message_body);
281 if ($isHtml && ($match > 0))
283 $message_body = preg_replace($dispurl, ' src="'.$attachment['name'].'"', $message_body);
284 $MAIL_MIME->setHTMLBody($message_body);
285 $MAIL_MIME->addHTMLImage($attachment['path'], $attachment['mimetype'], $attachment['name']);
290 We need to replace mime_content_type in a later release because the function
291 is deprecated in favour of File_Info
293 $MAIL_MIME->addAttachment($attachment['path'],
294 rc_mime_content_type($attachment['path'], $attachment['mimetype']),
295 $attachment['name'], true, 'base64',
296 'attachment', $message_charset);
300 // add submitted attachments
301 if (is_array($_FILES['_attachments']['tmp_name']))
302 foreach ($_FILES['_attachments']['tmp_name'] as $i => $filepath)
303 $MAIL_MIME->addAttachment($filepath, $files['type'][$i], $files['name'][$i], true, 'base64', 'attachment', $message_charset);
306 // chose transfer encoding
307 $charset_7bit = array('ASCII', 'ISO-2022-JP', 'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-15');
308 $transfer_encoding = in_array(strtoupper($message_charset), $charset_7bit) ? '7bit' : '8bit';
310 // encoding settings for mail composing
311 $MAIL_MIME->setParam(array(
312 'text_encoding' => $transfer_encoding,
313 'html_encoding' => 'quoted-printable',
314 'head_encoding' => 'quoted-printable',
315 'head_charset' => $message_charset,
316 'html_charset' => $message_charset,
317 'text_charset' => $message_charset,
320 // encoding subject header with mb_encode provides better results with asian characters
321 if ($MBSTRING && function_exists("mb_encode_mimeheader"))
323 mb_internal_encoding($message_charset);
324 $headers['Subject'] = mb_encode_mimeheader($headers['Subject'], $message_charset, 'Q');
325 mb_internal_encoding(RCMAIL_CHARSET);
328 // pass headers to message object
329 $MAIL_MIME->headers($headers);
331 // Begin SMTP Delivery Block
334 $sent = rcmail_deliver_message($MAIL_MIME, $from, $mailto);
336 // return to compose page if sending failed
339 $OUTPUT->show_message("sendingfailed", 'error');
340 $OUTPUT->send('iframe');
345 if ($_SESSION['compose']['reply_uid'])
346 $IMAP->set_flag($_SESSION['compose']['reply_uid'], 'ANSWERED');
348 } // End of SMTP Delivery Block
352 // Determine which folder to save message
354 $store_target = 'drafts_mbox';
356 $store_target = 'sent_mbox';
358 if ($CONFIG[$store_target])
360 // check if mailbox exists
361 if (!in_array_nocase($CONFIG[$store_target], $IMAP->list_mailboxes()))
362 $store_folder = $IMAP->create_mailbox($CONFIG[$store_target], TRUE);
364 $store_folder = TRUE;
366 // append message to sent box
368 $saved = $IMAP->save_message($CONFIG[$store_target], $MAIL_MIME->getMessage());
370 // raise error if saving failed
373 raise_error(array('code' => 800, 'type' => 'imap', 'file' => __FILE__,
374 'message' => "Could not save message in $CONFIG[$store_target]"), TRUE, FALSE);
376 $OUTPUT->show_message('errorsaving', 'error');
377 $OUTPUT->send('iframe');
380 if ($olddraftmessageid)
382 // delete previous saved draft
383 $a_deleteid = $IMAP->search($CONFIG['drafts_mbox'],'HEADER Message-ID',$olddraftmessageid);
384 $deleted = $IMAP->delete_message($IMAP->get_uid($a_deleteid[0],$CONFIG['drafts_mbox']),$CONFIG['drafts_mbox']);
386 // raise error if deletion of old draft failed
388 raise_error(array('code' => 800, 'type' => 'imap', 'file' => __FILE__,
389 'message' => "Could not delete message from ".$CONFIG['drafts_mbox']), TRUE, FALSE);
396 $OUTPUT->show_message('messagesaved', 'confirmation');
398 // update "_draft_saveid" and the "cmp_hash" to prevent "Unsaved changes" warning
399 $OUTPUT->command('set_draft_id', str_replace(array('<','>'), "", $message_id));
400 $OUTPUT->command('compose_field_hash', true);
402 // start the auto-save timer again
403 $OUTPUT->command('auto_save_start');
405 $OUTPUT->send('iframe');
409 if ($CONFIG['smtp_log'])
411 $log_entry = sprintf(
412 "[%s] User: %d on %s; Message for %s; %s\n",
413 date("d-M-Y H:i:s O", mktime()),
414 $_SESSION['user_id'],
415 $_SERVER['REMOTE_ADDR'],
417 !empty($smtp_response) ? join('; ', $smtp_response) : '');
419 if ($fp = @fopen($CONFIG['log_dir'].'/sendmail', 'a'))
421 fwrite($fp, $log_entry);
426 rcmail_compose_cleanup();
427 $OUTPUT->command('sent_successfully', rcube_label('messagesent'));
428 $OUTPUT->send('iframe');