4 +-----------------------------------------------------------------------+
5 | program/steps/mail/sendmail.inc |
7 | This file is part of the RoundCube Webmail client |
8 | Copyright (C) 2005, 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 IlohaMail's SMTP methods or with PHP mail() |
15 +-----------------------------------------------------------------------+
16 | Author: Thomas Bruederli <roundcube@gmail.com> |
17 +-----------------------------------------------------------------------+
19 $Id: sendmail.inc 288 2006-07-31 22:51:23Z thomasb $
24 //require_once('lib/smtp.inc');
25 require_once('include/rcube_smtp.inc');
26 require_once('Mail/mime.php');
29 if (!isset($_SESSION['compose']['id']))
31 rcmail_overwrite_action('list');
36 /****** message sending functions ********/
39 function rcmail_get_identity($id)
41 global $DB, $CHARSET, $OUTPUT;
43 // get identity record
44 $sql_result = $DB->query("SELECT *, email AS mailto
45 FROM ".get_table_name('identities')."
49 $id,$_SESSION['user_id']);
51 if ($DB->num_rows($sql_result))
53 $sql_arr = $DB->fetch_assoc($sql_result);
55 $name = strpos($sql_arr['name'], ",") ? '"'.$sql_arr['name'].'"' : $sql_arr['name'];
56 $out['string'] = sprintf('%s <%s>',
57 rcube_charset_convert($name, $CHARSET, $OUTPUT->get_charset()),
66 if (strlen($_POST['_draft_saveid']) > 3)
67 $olddraftmessageid = get_input_value('_draft_saveid', RCUBE_INPUT_POST);
69 $message_id = sprintf('<%s@%s>', md5(uniqid('rcmail'.rand(),true)), $_SESSION['imap_host']);
70 $savedraft = !empty($_POST['_draft']) ? TRUE : FALSE;
72 // remove all scripts and act as called in frame
77 /****** check submission and compose message ********/
80 if (empty($_POST['_to']) && empty($_POST['_subject']) && $_POST['_message'])
82 show_message("sendingfailed", 'error');
83 //rcmail_overwrite_action('compose');
84 rcube_iframe_response();
89 // set default charset
90 $input_charset = $OUTPUT->get_charset();
91 $message_charset = isset($_POST['_charset']) ? $_POST['_charset'] : $input_charset;
93 $mailto_regexp = array('/[,;]\s*[\r\n]+/', '/[\r\n]+/', '/[,;]\s*$/m');
94 $mailto_replace = array(', ', ', ', '');
96 // replace new lines and strip ending ', '
97 $mailto = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_to', RCUBE_INPUT_POST, TRUE, $message_charset));
99 // decode address strings
100 $to_address_arr = $IMAP->decode_address_list($mailto);
101 $identity_arr = rcmail_get_identity(get_input_value('_from', RCUBE_INPUT_POST));
103 $from = $identity_arr['mailto'];
104 $first_to = is_array($to_address_arr[0]) ? $to_address_arr[0]['mailto'] : $mailto;
106 if (empty($identity_arr['string']))
107 $identity_arr['string'] = $from;
109 // compose headers array
110 $headers = array('Date' => date('D, j M Y G:i:s O'),
111 'From' => $identity_arr['string'],
112 'To' => rcube_charset_convert($mailto, $input_charset, $message_charset));
114 // additional recipients
115 if (!empty($_POST['_cc']))
116 $headers['Cc'] = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_cc', RCUBE_INPUT_POST, TRUE, $message_charset));
118 if (!empty($_POST['_bcc']))
119 $headers['Bcc'] = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_bcc', RCUBE_INPUT_POST, TRUE, $message_charset));
121 if (!empty($identity_arr['bcc']))
122 $headers['Bcc'] = ($headers['Bcc'] ? $headers['Bcc'].', ' : '') . $identity_arr['bcc'];
125 $headers['Subject'] = trim(get_input_value('_subject', RCUBE_INPUT_POST, FALSE, $message_charset));
127 if (!empty($identity_arr['organization']))
128 $headers['Organization'] = $identity_arr['organization'];
130 if (!empty($identity_arr['reply-to']))
131 $headers['Reply-To'] = $identity_arr['reply-to'];
133 if (!empty($_SESSION['compose']['reply_msgid']))
134 $headers['In-Reply-To'] = $_SESSION['compose']['reply_msgid'];
136 if (!empty($_SESSION['compose']['references']))
137 $headers['References'] = $_SESSION['compose']['references'];
139 if (!empty($_POST['_priority']))
141 $priority = (int)$_POST['_priority'];
142 $a_priorities = array(1=>'lowest', 2=>'low', 4=>'high', 5=>'highest');
143 if ($str_priority = $a_priorities[$priority])
144 $headers['X-Priority'] = sprintf("%d (%s)", $priority, ucfirst($str_priority));
147 if (!empty($_POST['_receipt']))
149 $headers['Return-Receipt-To'] = $identity_arr['string'];
150 $headers['Disposition-Notification-To'] = $identity_arr['string'];
153 // additional headers
154 $headers['Message-ID'] = $message_id;
155 $headers['X-Sender'] = $from;
157 if (!empty($CONFIG['useragent']))
158 $headers['User-Agent'] = $CONFIG['useragent'];
160 // fetch message body
161 $message_body = get_input_value('_message', RCUBE_INPUT_POST, TRUE, $message_charset);
163 // append generic footer to all messages
164 if (!empty($CONFIG['generic_message_footer']))
166 $file = realpath($CONFIG['generic_message_footer']);
167 if($fp = fopen($file, 'r'))
169 $content = fread($fp, filesize($file));
171 $message_body .= "\r\n" . rcube_charset_convert($content, 'UTF-8', $message_charset);
175 // try to autodetect operating system and use the correct line endings
176 // use the configured delimiter for headers
177 if (!empty($CONFIG['mail_header_delimiter']))
178 $header_delm = $CONFIG['mail_header_delimiter'];
179 else if (strtolower(substr(PHP_OS, 0, 3)=='win'))
180 $header_delm = "\r\n";
181 else if (strtolower(substr(PHP_OS, 0, 3)=='mac'))
182 $header_delm = "\r\n";
186 // create PEAR::Mail_mime instance
187 $MAIL_MIME = new Mail_mime($header_delm);
188 $MAIL_MIME->setTXTBody($message_body, FALSE, TRUE);
189 //$MAIL_MIME->setTXTBody(wordwrap($message_body), FALSE, TRUE);
192 // add stored attachments, if any
193 if (is_array($_SESSION['compose']['attachments']))
194 foreach ($_SESSION['compose']['attachments'] as $attachment)
195 $MAIL_MIME->addAttachment($attachment['path'], $attachment['mimetype'], $attachment['name'], TRUE);
198 // add submitted attachments
199 if (is_array($_FILES['_attachments']['tmp_name']))
200 foreach ($_FILES['_attachments']['tmp_name'] as $i => $filepath)
201 $MAIL_MIME->addAttachment($filepath, $files['type'][$i], $files['name'][$i], TRUE);
204 // chose transfer encoding
205 $charset_7bit = array('ASCII', 'ISO-2022-JP', 'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-15');
206 $transfer_encoding = in_array(strtoupper($message_charset), $charset_7bit) ? '7bit' : '8bit';
208 // encoding settings for mail composing
209 $message_param = array('text_encoding' => $transfer_encoding,
210 'html_encoding' => 'quoted-printable',
211 'head_encoding' => 'quoted-printable',
212 'head_charset' => $message_charset,
213 'html_charset' => $message_charset,
214 'text_charset' => $message_charset);
216 // compose message body and get headers
217 $msg_body = &$MAIL_MIME->get($message_param);
219 $msg_subject = $headers['Subject'];
221 if ($MBSTRING && function_exists("mb_encode_mimeheader"))
222 $headers['Subject'] = mb_encode_mimeheader($headers['Subject'], $message_charset);
224 // Begin SMTP Delivery Block
227 // send thru SMTP server using custom SMTP library
228 if ($CONFIG['smtp_server'])
230 // generate list of recipients
231 $a_recipients = array($mailto);
233 if (strlen($headers['Cc']))
234 $a_recipients[] = $headers['Cc'];
235 if (strlen($headers['Bcc']))
236 $a_recipients[] = $headers['Bcc'];
238 // clean Bcc from header for recipients
239 $send_headers = $headers;
240 unset($send_headers['Bcc']);
242 // generate message headers
243 $header_str = $MAIL_MIME->txtHeaders($send_headers);
246 $sent = smtp_mail($from, $a_recipients, $header_str, $msg_body);
251 raise_error(array('code' => 800,
255 'message' => "SMTP error: $SMTP_ERROR"), TRUE, FALSE);
259 // send mail using PHP's mail() function
262 // unset some headers because they will be added by the mail() function
263 $headers_enc = $MAIL_MIME->headers($headers);
264 $headers_php = $MAIL_MIME->_headers;
265 unset($headers_php['To'], $headers_php['Subject']);
267 // reset stored headers and overwrite
268 $MAIL_MIME->_headers = array();
269 $header_str = $MAIL_MIME->txtHeaders($headers_php);
271 if (ini_get('safe_mode'))
272 $sent = mail($headers_enc['To'], $headers_enc['Subject'], $msg_body, $header_str);
274 $sent = mail($headers_enc['To'], $headers_enc['Subject'], $msg_body, $header_str, "-f$from");
278 // return to compose page if sending failed
281 show_message("sendingfailed", 'error');
282 rcube_iframe_response();
288 if ($_SESSION['compose']['reply_uid'])
289 $IMAP->set_flag($_SESSION['compose']['reply_uid'], 'ANSWERED');
291 } // End of SMTP Delivery Block
295 // Determine which folder to save message
297 $store_target = 'drafts_mbox';
299 $store_target = 'sent_mbox';
301 if ($CONFIG[$store_target])
303 // create string of complete message headers
304 $header_str = $MAIL_MIME->txtHeaders($headers);
306 // check if mailbox exists
307 if (!in_array_nocase($CONFIG[$store_target], $IMAP->list_mailboxes()))
308 $store_folder = $IMAP->create_mailbox($CONFIG[$store_target], TRUE);
310 $store_folder = TRUE;
312 // add headers to message body
313 $msg_body = $header_str."\r\n".$msg_body;
315 // append message to sent box
317 $saved = $IMAP->save_message($CONFIG[$store_target], $msg_body);
319 // raise error if saving failed
322 raise_error(array('code' => 800,
325 'message' => "Could not save message in $CONFIG[$store_target]"), TRUE, FALSE);
327 show_message('errorsaving', 'error');
328 rcube_iframe_response($errorout);
331 if ($olddraftmessageid)
333 // delete previous saved draft
334 $a_deleteid = $IMAP->search($CONFIG['drafts_mbox'],'HEADER Message-ID',$olddraftmessageid);
335 $deleted = $IMAP->delete_message($IMAP->get_uid($a_deleteid[0],$CONFIG['drafts_mbox']),$CONFIG['drafts_mbox']);
337 // raise error if deletion of old draft failed
339 raise_error(array('code' => 800,
342 'message' => "Could not delete message from ".$CONFIG['drafts_mbox']), TRUE, FALSE);
348 // clear the "saving message" busy status, and display success
349 show_message('messagesaved', 'confirmation');
351 // update "_draft_saveid" on the page, which is used to delete a previous draft
352 $frameout = "var foundid = parent.rcube_find_object('_draft_saveid', parent.document);\n";
353 $frameout .= sprintf("foundid.value = '%s';\n", str_replace(array('<','>'), "", $message_id));
355 // update the "cmp_hash" to prevent "Unsaved changes" warning
356 $frameout .= sprintf("parent.%s.cmp_hash = parent.%s.compose_field_hash();\n", $JS_OBJECT_NAME, $JS_OBJECT_NAME);
358 // start the auto-save timer again
359 $frameout .= sprintf("parent.%s.auto_save_start();", $JS_OBJECT_NAME);
361 // send html page with JS calls as response
362 rcube_iframe_response($frameout);
366 if ($CONFIG['smtp_log'])
368 $log_entry = sprintf("[%s] User: %d on %s; Message for %s; Subject: %s\n",
369 date("d-M-Y H:i:s O", mktime()),
370 $_SESSION['user_id'],
371 $_SERVER['REMOTE_ADDR'],
375 if ($fp = @fopen($CONFIG['log_dir'].'/sendmail', 'a'))
377 fwrite($fp, $log_entry);
382 rcmail_compose_cleanup();
383 rcube_iframe_response(sprintf("parent.$JS_OBJECT_NAME.sent_successfully('%s');",
384 rep_specialchars_output(rcube_label('messagesent'), 'js')));