[MERGE] merge from trunk addons
[odoo/odoo.git] / addons / email_template / email_template_mailbox.py
index 1934f4e..7483ade 100755 (executable)
@@ -1,9 +1,31 @@
+# -*- coding: utf-8 -*-
+##############################################################################
+#
+#    OpenERP, Open Source Management Solution
+#    Copyright (C) 2009 Sharoon Thomas
+#    Copyright (C) 2004-2010 OpenERP SA (<http://www.openerp.com>)
+#
+#    This program is free software: you can redistribute it and/or modify
+#    it under the terms of the GNU General Public License as published by
+#    the Free Software Foundation, either version 3 of the License, or
+#    (at your option) any later version.
+#
+#    This program is distributed in the hope that it will be useful,
+#    but WITHOUT ANY WARRANTY; without even the implied warranty of
+#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+#    GNU General Public License for more details.
+#
+#    You should have received a copy of the GNU General Public License
+#    along with this program.  If not, see <http://www.gnu.org/licenses/>
+#
+##############################################################################
+
 from osv import osv, fields
 import time
-import email_template_engines
 import netsvc
 from tools.translate import _
 import tools
+import base64
 
 LOGGER = netsvc.Logger()
 
@@ -15,16 +37,16 @@ class email_template_mailbox(osv.osv):
     
     def run_mail_scheduler(self, cursor, user, context=None):
         """
-        This method is called by Open ERP Scheduler
+        This method is called by OpenERP Scheduler
         to periodically send emails
         """
         try:
-            self.send_all_mail(cursor, user, context)
+            self.send_all_mail(cursor, user, context=context)
         except Exception, e:
             LOGGER.notifyChannel(
-                                 _("Email Template"),
+                                 "Email Template",
                                  netsvc.LOG_ERROR,
-                                 _("Error sending mail: %s" % str(e)))
+                                 _("Error sending mail: %s") % e)
         
     def send_all_mail(self, cr, uid, ids=None, context=None):
         if ids is None:
@@ -41,62 +63,92 @@ class email_template_mailbox(osv.osv):
         return True
     
     def send_this_mail(self, cr, uid, ids=None, context=None):
-        if ids is None:
-            ids = []
-        for id in ids:
+        #previous method to send email (link with email account can be found at the revision 4172 and below
+        result = True
+        attachment_pool = self.pool.get('ir.attachment')
+        for id in (ids or []):
             try:
                 account_obj = self.pool.get('email_template.account')
                 values = self.read(cr, uid, id, [], context) 
-                payload = {}
+                attach_to_send = None
+                
                 if values['attachments_ids']:
-                    for attid in values['attachments_ids']:
-                        attachment = self.pool.get('ir.attachment').browse(cr, uid, attid, context)#,['datas_fname','datas'])
-                        payload[attachment.datas_fname] = attachment.datas
-                    print "233333333333333"
-                result = account_obj.send_mail(cr, uid,
-                              [values['account_id'][0]],
-                              {'To':values.get('email_to', u'') or u'', 'CC':values.get('email_cc', u'') or u'', 'BCC':values.get('email_bcc', u'') or u''},
-                              values['subject'] or u'',
-                              {'text':values.get('body_text', u'') or u'', 'html':values.get('body_html', u'') or u''},
-                              payload=payload, context=context)
+                    attach_to_send = self.pool.get('ir.attachment').read(cr, uid, values['attachments_ids'], ['datas_fname','datas', 'name'])
+                    attach_to_send = map(lambda x: (x['datas_fname'] or x['name'], base64.decodestring(x['datas'])), attach_to_send)
+                
+                if values.get('body_html'):
+                    body = values.get('body_html')
+                    subtype = "html"
+                else :
+                    body = values.get('body_text')
+                    subtype = "plain"
+                    
+                result = tools.email_send(
+                    values.get('email_from') or u'',
+                    [values.get('email_to')],
+                    values['subject'] or u'', 
+                    body or u'',
+                    reply_to=values.get('reply_to') or u'',
+                    email_bcc=values.get('email_bcc') or u'',
+                    email_cc=values.get('email_cc') or u'',
+                    subtype=subtype,
+                    attach=attach_to_send,
+                    openobject_id=values['message_id']
+                )
                 
+
                 if result == True:
-                    self.write(cr, uid, id, {'folder':'sent', 'state':'na', 'date_mail':time.strftime("%Y-%m-%d %H:%M:%S")}, context)
-                    self.historise(cr, uid, [id], "Email sent successfully", context)
+                    account = account_obj.browse(cr, uid, values['account_id'][0], context=context)
+                    if account.auto_delete:
+                        self.write(cr, uid, id, {'folder': 'trash'}, context=context)
+                        self.unlink(cr, uid, [id], context=context)
+                        # Remove attachments for this mail
+                        attachment_pool.unlink(cr, uid, values['attachments_ids'], context=context)
+                    else:
+                        self.write(cr, uid, id, {'folder':'sent', 'state':'na', 'date_mail':time.strftime("%Y-%m-%d %H:%M:%S")}, context)
+                        self.historise(cr, uid, [id], "Email sent successfully", context)
                 else:
-                    self.historise(cr, uid, [id], result, context)
+                    error = result['error_msg']
+                    self.historise(cr, uid, [id], error, context)
+                    
             except Exception, error:
                 logger = netsvc.Logger()
-                logger.notifyChannel(_("Power Email"), netsvc.LOG_ERROR, _("Sending of Mail %s failed. Probable Reason:Could not login to server\nError: %s") % (id, error))
+                logger.notifyChannel("email-template", netsvc.LOG_ERROR, _("Sending of Mail %s failed. Probable Reason:Could not login to server\nError: %s") % (id, error))
                 self.historise(cr, uid, [id], error, context)
             self.write(cr, uid, id, {'state':'na'}, context)
-        return True
+        return result
     
     def historise(self, cr, uid, ids, message='', context=None):
         for id in ids:
             history = self.read(cr, uid, id, ['history'], context).get('history', '')
-            self.write(cr, uid, id, {'history':history or '' + "\n" + time.strftime("%Y-%m-%d %H:%M:%S") + ": " + tools.ustr(message)}, context)
+            self.write(cr, uid, id, {'history': (history or '' )+ "\n" + time.strftime("%Y-%m-%d %H:%M:%S") + ": " + tools.ustr(message)}, context)
     
     _columns = {
             'email_from':fields.char(
                             'From', 
                             size=64),
             'email_to':fields.char(
-                            'Recepient (To)', 
+                            'Recipient (To)', 
                             size=250,),
             'email_cc':fields.char(
-                            ' CC', 
+                            'CC', 
                             size=250),
             'email_bcc':fields.char(
-                            ' BCC', 
+                            'BCC', 
+                            size=250),
+            'reply_to':fields.char(
+                            'Reply-To', 
+                            size=250),
+            'message_id':fields.char(
+                            'Message-ID', 
                             size=250),
             'subject':fields.char(
-                            ' Subject', 
+                            'Subject', 
                             size=200,),
             'body_text':fields.text(
                             'Standard Body (Text)'),
             'body_html':fields.text(
-                            'Body (Text-Web Client Only)'),
+                            'Body (Rich Text Clients Only)'),
             'attachments_ids':fields.many2many(
                             'ir.attachment', 
                             'mail_attachments_rel', 
@@ -140,8 +192,7 @@ class email_template_mailbox(osv.osv):
                             ('na', 'Not Applicable'),
                             ('sending', 'Sending'),
                             ], 'Status', required=True),
-            'date_mail':fields.datetime(
-                            'Rec/Sent Date'),
+            'date_mail':fields.datetime('Rec/Sent Date', help="Date on which Email Sent or Received"),
             'history':fields.text(
                             'History', 
                             readonly=True, 
@@ -153,29 +204,21 @@ class email_template_mailbox(osv.osv):
         'folder': lambda * a: 'outbox',
     } 
 
-    def search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False):
-        if context is None:
-            context = {}
-        if context.get('company', False):
-            users_groups = self.pool.get('res.users').browse(cr, uid, uid, context).groups_id
-            group_acc_rel = {}
-            #get all accounts and get a table of {group1:[account1,account2],group2:[account1]}
-            for each_account_id in self.pool.get('email_template.account').search(cr, uid, [('state', '=', 'approved'), ('company', '=', 'yes')], context=context):
-                account = self.pool.get('email_template.account').browse(cr, uid, each_account_id, context)
-                for each_group in account.allowed_groups:
-                    if not account.id in group_acc_rel.get(each_group, []):
-                        groups = group_acc_rel.get(each_group, [])
-                        groups.append(account.id)
-                        group_acc_rel[each_group] = groups
-            users_company_accounts = []
-            for each_group in group_acc_rel.keys():
-                if each_group in users_groups:
-                    for each_account in group_acc_rel[each_group]:
-                        if not each_account in users_company_accounts:
-                            users_company_accounts.append(each_account)
-            args.append(('account_id', 'in', users_company_accounts))
-        return super(osv.osv, self).search(cr, uid, args, offset, limit,
-                order, context=context, count=count)
+    def unlink(self, cr, uid, ids, context=None):
+        """
+        It just changes the folder of the item to "Trash", if it is no in Trash folder yet, 
+        or completely deletes it if it is already in Trash.
+        """
+        to_update = []
+        to_remove = []
+        for mail in self.browse(cr, uid, ids, context=context):
+            if mail.folder == 'trash':
+                to_remove.append(mail.id)
+            else:
+                to_update.append(mail.id)
+        # Changes the folder to trash
+        self.write(cr, uid, to_update, {'folder': 'trash'}, context=context)
+        return super(email_template_mailbox, self).unlink(cr, uid, to_remove, context=context)
 
 email_template_mailbox()