[IMP]: email_template: Improvement in form view of Mailbox
[odoo/odoo.git] / addons / email_template / email_template_mailbox.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2009 Sharoon Thomas
6 #    Copyright (C) 2004-2010 OpenERP SA (<http://www.openerp.com>)
7 #
8 #    This program is free software: you can redistribute it and/or modify
9 #    it under the terms of the GNU General Public License as published by
10 #    the Free Software Foundation, either version 3 of the License, or
11 #    (at your option) any later version.
12 #
13 #    This program is distributed in the hope that it will be useful,
14 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #    GNU General Public License for more details.
17 #
18 #    You should have received a copy of the GNU General Public License
19 #    along with this program.  If not, see <http://www.gnu.org/licenses/>
20 #
21 ##############################################################################
22
23 from osv import osv, fields
24 import time
25 import netsvc
26 from tools.translate import _
27 import tools
28
29 LOGGER = netsvc.Logger()
30
31 class email_template_mailbox(osv.osv):
32     _name = "email_template.mailbox"
33     _description = 'Email Mailbox'
34     _rec_name = "subject"
35     _order = "date_mail desc"
36     
37     def run_mail_scheduler(self, cursor, user, context=None):
38         """
39         This method is called by OpenERP Scheduler
40         to periodically send emails
41         """
42         try:
43             self.send_all_mail(cursor, user, context)
44         except Exception, e:
45             LOGGER.notifyChannel(
46                                  _("Email Template"),
47                                  netsvc.LOG_ERROR,
48                                  _("Error sending mail: %s" % str(e)))
49         
50     def send_all_mail(self, cr, uid, ids=None, context=None):
51         if ids is None:
52             ids = []
53         if context is None:
54             context = {}
55         filters = [('folder', '=', 'outbox'), ('state', '!=', 'sending')]
56         if 'filters' in context.keys():
57             for each_filter in context['filters']:
58                 filters.append(each_filter)
59         ids = self.search(cr, uid, filters, context=context)
60         self.write(cr, uid, ids, {'state':'sending'}, context)
61         self.send_this_mail(cr, uid, ids, context)
62         return True
63     
64     def send_this_mail(self, cr, uid, ids=None, context=None):
65         result = True
66         for id in (ids or []):
67             try:
68                 account_obj = self.pool.get('email_template.account')
69                 values = self.read(cr, uid, id, [], context) 
70                 payload = {}
71                 if values['attachments_ids']:
72                     for attid in values['attachments_ids']:
73                         attachment = self.pool.get('ir.attachment').browse(cr, uid, attid, context)#,['datas_fname','datas'])
74                         payload[attachment.datas_fname] = attachment.datas
75                 result = account_obj.send_mail(cr, uid,
76                               [values['account_id'][0]],
77                               {'To':values.get('email_to') or u'',
78                                'CC':values.get('email_cc') or u'',
79                                'BCC':values.get('email_bcc') or u'',
80                                'Reply-To':values.get('reply_to') or u''},
81                               values['subject'] or u'',
82                               {'text':values.get('body_text') or u'', 'html':values.get('body_html') or u''},
83                               payload=payload,
84                               message_id=values['message_id'], 
85                               context=context)
86                 if result == True:
87                     self.write(cr, uid, id, {'folder':'sent', 'state':'na', 'date_mail':time.strftime("%Y-%m-%d %H:%M:%S")}, context)
88                     self.historise(cr, uid, [id], "Email sent successfully", context)
89                 else:
90                     error = result['error_msg']
91                     self.historise(cr, uid, [id], error, context)
92                     
93             except Exception, error:
94                 logger = netsvc.Logger()
95                 logger.notifyChannel("email-template", netsvc.LOG_ERROR, _("Sending of Mail %s failed. Probable Reason:Could not login to server\nError: %s") % (id, error))
96                 self.historise(cr, uid, [id], error, context)
97             self.write(cr, uid, id, {'state':'na'}, context)
98         return result
99     
100     def historise(self, cr, uid, ids, message='', context=None):
101         for id in ids:
102             history = self.read(cr, uid, id, ['history'], context).get('history', '')
103             self.write(cr, uid, id, {'history':history or '' + "\n" + time.strftime("%Y-%m-%d %H:%M:%S") + ": " + tools.ustr(message)}, context)
104     
105     _columns = {
106             'email_from':fields.char(
107                             'From', 
108                             size=64),
109             'email_to':fields.char(
110                             'Recipient (To)', 
111                             size=250,),
112             'email_cc':fields.char(
113                             'CC', 
114                             size=250),
115             'email_bcc':fields.char(
116                             'BCC', 
117                             size=250),
118             'reply_to':fields.char(
119                             'Reply-To', 
120                             size=250),
121             'message_id':fields.char(
122                             'Message-ID', 
123                             size=250),
124             'subject':fields.char(
125                             'Subject', 
126                             size=200,),
127             'body_text':fields.text(
128                             'Standard Body (Text)'),
129             'body_html':fields.text(
130                             'Body (Rich Text Clients Only)'),
131             'attachments_ids':fields.many2many(
132                             'ir.attachment', 
133                             'mail_attachments_rel', 
134                             'mail_id', 
135                             'att_id', 
136                             'Attachments'),
137             'account_id' :fields.many2one(
138                             'email_template.account',
139                             'User account', 
140                             required=True),
141             'user':fields.related(
142                             'account_id', 
143                             'user', 
144                             type="many2one", 
145                             relation="res.users", 
146                             string="User"),
147             'server_ref':fields.integer(
148                             'Server Reference of mail', 
149                             help="Applicable for inward items only"),
150             'mail_type':fields.selection([
151                             ('multipart/mixed', 
152                              'Has Attachments'),
153                             ('multipart/alternative', 
154                              'Plain Text & HTML with no attachments'),
155                             ('multipart/related', 
156                              'Intermixed content'),
157                             ('text/plain', 
158                              'Plain Text'),
159                             ('text/html', 
160                              'HTML Body'),
161                             ], 'Mail Contents'),
162             #I like GMAIL which allows putting same mail in many folders
163             #Lets plan it for 0.9
164             'folder':fields.selection([
165                             ('drafts', 'Drafts'),
166                             ('outbox', 'Outbox'),
167                             ('trash', 'Trash'),
168                             ('sent', 'Sent Items'),
169                             ], 'Folder', required=True),
170             'state':fields.selection([
171                             ('na', 'Not Applicable'),
172                             ('sending', 'Sending'),
173                             ], 'Status', required=True),
174             'date_mail':fields.datetime('Rec/Sent Date', help="Date on which Email Sent or Received"),
175             'history':fields.text(
176                             'History', 
177                             readonly=True, 
178                             store=True)
179         }
180
181     _defaults = {
182         'state': lambda * a: 'na',
183         'folder': lambda * a: 'outbox',
184     } 
185
186     def unlink(self, cr, uid, ids, context=None):
187         """
188         It just changes the folder of the item to "Trash", if it is no in Trash folder yet, 
189         or completely deletes it if it is already in Trash.
190         """
191         if not context:
192             context = {}
193         to_update = []
194         to_remove = []
195         for mail in self.browse(cr, uid, ids, context=context):
196             if mail.folder == 'trash':
197                 to_remove.append(mail.id)
198             else:
199                 to_update.append(mail.id)
200         # Changes the folder to trash
201         self.write(cr, uid, to_update, {'folder': 'trash'}, context=context)
202         return super(email_template_mailbox, self).unlink(cr, uid, to_remove, context=context)
203
204 email_template_mailbox()
205
206 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: