merged with trunk
[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=context)
44         except Exception, e:
45             LOGGER.notifyChannel(
46                                  "Email Template",
47                                  netsvc.LOG_ERROR,
48                                  _("Error sending mail: %s") % 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         attachment_pool = self.pool.get('ir.attachment')
67         for id in (ids or []):
68             try:
69                 account_obj = self.pool.get('email_template.account')
70                 values = self.read(cr, uid, id, [], context) 
71                 payload = {}
72                 if values['attachments_ids']:
73                     for attid in values['attachments_ids']:
74                         attachment = attachment_pool.browse(cr, uid, attid, context)#,['datas_fname','datas'])
75                         payload[attachment.datas_fname] = attachment.datas
76                 result = account_obj.send_mail(cr, uid,
77                               [values['account_id'][0]],
78                               {'To':values.get('email_to') or u'',
79                                'CC':values.get('email_cc') or u'',
80                                'BCC':values.get('email_bcc') or u'',
81                                'Reply-To':values.get('reply_to') or u''},
82                               values['subject'] or u'',
83                               {'text':values.get('body_text') or u'', 'html':values.get('body_html') or u''},
84                               payload=payload,
85                               message_id=values['message_id'], 
86                               context=context)
87                 if result == True:
88                     account = account_obj.browse(cr, uid, values['account_id'][0], context=context)
89                     if account.auto_delete:
90                         self.write(cr, uid, id, {'folder': 'trash'}, context=context)
91                         self.unlink(cr, uid, [id], context=context)
92                         # Remove attachments for this mail
93                         attachment_pool.unlink(cr, uid, values['attachments_ids'], context=context)
94                     else:
95                         self.write(cr, uid, id, {'folder':'sent', 'state':'na', 'date_mail':time.strftime("%Y-%m-%d %H:%M:%S")}, context)
96                         self.historise(cr, uid, [id], "Email sent successfully", context)
97                 else:
98                     error = result['error_msg']
99                     self.historise(cr, uid, [id], error, context)
100                     
101             except Exception, error:
102                 logger = netsvc.Logger()
103                 logger.notifyChannel("email-template", netsvc.LOG_ERROR, _("Sending of Mail %s failed. Probable Reason:Could not login to server\nError: %s") % (id, error))
104                 self.historise(cr, uid, [id], error, context)
105             self.write(cr, uid, id, {'state':'na'}, context)
106         return result
107     
108     def historise(self, cr, uid, ids, message='', context=None):
109         for id in ids:
110             history = self.read(cr, uid, id, ['history'], context).get('history', '')
111             self.write(cr, uid, id, {'history': (history or '' )+ "\n" + time.strftime("%Y-%m-%d %H:%M:%S") + ": " + tools.ustr(message)}, context)
112     
113     _columns = {
114             'email_from':fields.char(
115                             'From', 
116                             size=64),
117             'email_to':fields.char(
118                             'Recipient (To)', 
119                             size=250,),
120             'email_cc':fields.char(
121                             'CC', 
122                             size=250),
123             'email_bcc':fields.char(
124                             'BCC', 
125                             size=250),
126             'reply_to':fields.char(
127                             'Reply-To', 
128                             size=250),
129             'message_id':fields.char(
130                             'Message-ID', 
131                             size=250),
132             'subject':fields.char(
133                             'Subject', 
134                             size=200,),
135             'body_text':fields.text(
136                             'Standard Body (Text)'),
137             'body_html':fields.text(
138                             'Body (Rich Text Clients Only)'),
139             'attachments_ids':fields.many2many(
140                             'ir.attachment', 
141                             'mail_attachments_rel', 
142                             'mail_id', 
143                             'att_id', 
144                             'Attachments'),
145             'account_id' :fields.many2one(
146                             'email_template.account',
147                             'User account', 
148                             required=True),
149             'user':fields.related(
150                             'account_id', 
151                             'user', 
152                             type="many2one", 
153                             relation="res.users", 
154                             string="User"),
155             'server_ref':fields.integer(
156                             'Server Reference of mail', 
157                             help="Applicable for inward items only"),
158             'mail_type':fields.selection([
159                             ('multipart/mixed', 
160                              'Has Attachments'),
161                             ('multipart/alternative', 
162                              'Plain Text & HTML with no attachments'),
163                             ('multipart/related', 
164                              'Intermixed content'),
165                             ('text/plain', 
166                              'Plain Text'),
167                             ('text/html', 
168                              'HTML Body'),
169                             ], 'Mail Contents'),
170             #I like GMAIL which allows putting same mail in many folders
171             #Lets plan it for 0.9
172             'folder':fields.selection([
173                             ('drafts', 'Drafts'),
174                             ('outbox', 'Outbox'),
175                             ('trash', 'Trash'),
176                             ('sent', 'Sent Items'),
177                             ], 'Folder', required=True),
178             'state':fields.selection([
179                             ('na', 'Not Applicable'),
180                             ('sending', 'Sending'),
181                             ], 'Status', required=True),
182             'date_mail':fields.datetime('Rec/Sent Date', help="Date on which Email Sent or Received"),
183             'history':fields.text(
184                             'History', 
185                             readonly=True, 
186                             store=True)
187         }
188
189     _defaults = {
190         'state': lambda * a: 'na',
191         'folder': lambda * a: 'outbox',
192     } 
193
194     def unlink(self, cr, uid, ids, context=None):
195         """
196         It just changes the folder of the item to "Trash", if it is no in Trash folder yet, 
197         or completely deletes it if it is already in Trash.
198         """
199         to_update = []
200         to_remove = []
201         for mail in self.browse(cr, uid, ids, context=context):
202             if mail.folder == 'trash':
203                 to_remove.append(mail.id)
204             else:
205                 to_update.append(mail.id)
206         # Changes the folder to trash
207         self.write(cr, uid, to_update, {'folder': 'trash'}, context=context)
208         return super(email_template_mailbox, self).unlink(cr, uid, to_remove, context=context)
209
210 email_template_mailbox()
211
212 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: