[FIX]: add author and License in all files
[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 Tiny SPRL (<http://tiny.be>).
7 #
8 #    This program is free software: you can redistribute it and/or modify
9 #    it under the terms of the GNU Affero General Public License as
10 #    published by the Free Software Foundation, either version 3 of the
11 #    License, or (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 Affero General Public License for more details.
17 #
18 #    You should have received a copy of the GNU Affero 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 email_template_engines
26 import netsvc
27 from tools.translate import _
28 import tools
29
30 LOGGER = netsvc.Logger()
31
32 class email_template_mailbox(osv.osv):
33     _name = "email_template.mailbox"
34     _description = 'Email Mailbox'
35     _rec_name = "subject"
36     _order = "date_mail desc"
37     
38     def run_mail_scheduler(self, cursor, user, context=None):
39         """
40         This method is called by Open ERP Scheduler
41         to periodically send emails
42         """
43         try:
44             self.send_all_mail(cursor, user, context)
45         except Exception, e:
46             LOGGER.notifyChannel(
47                                  _("Email Template"),
48                                  netsvc.LOG_ERROR,
49                                  _("Error sending mail: %s" % str(e)))
50         
51     def send_all_mail(self, cr, uid, ids=None, context=None):
52         if ids is None:
53             ids = []
54         if context is None:
55             context = {}
56         filters = [('folder', '=', 'outbox'), ('state', '!=', 'sending')]
57         if 'filters' in context.keys():
58             for each_filter in context['filters']:
59                 filters.append(each_filter)
60         ids = self.search(cr, uid, filters, context=context)
61         self.write(cr, uid, ids, {'state':'sending'}, context)
62         self.send_this_mail(cr, uid, ids, context)
63         return True
64     
65     def send_this_mail(self, cr, uid, ids=None, context=None):
66         result = True
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 = self.pool.get('ir.attachment').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', u'') or u'', 'CC':values.get('email_cc', u'') or u'', 'BCC':values.get('email_bcc', u'') or u''},
79                               values['subject'] or u'',
80                               {'text':values.get('body_text', u'') or u'', 'html':values.get('body_html', u'') or u''},
81                               payload=payload, context=context)
82                 if result == True:
83                     self.write(cr, uid, id, {'folder':'sent', 'state':'na', 'date_mail':time.strftime("%Y-%m-%d %H:%M:%S")}, context)
84                     self.historise(cr, uid, [id], "Email sent successfully", context)
85                 else:
86                     error = result['error_msg']
87                     self.historise(cr, uid, [id], error, context)
88                     
89             except Exception, error:
90                 logger = netsvc.Logger()
91                 logger.notifyChannel(_("Power Email"), netsvc.LOG_ERROR, _("Sending of Mail %s failed. Probable Reason:Could not login to server\nError: %s") % (id, error))
92                 self.historise(cr, uid, [id], error, context)
93             self.write(cr, uid, id, {'state':'na'}, context)
94         return result
95     
96     def historise(self, cr, uid, ids, message='', context=None):
97         for id in ids:
98             history = self.read(cr, uid, id, ['history'], context).get('history', '')
99             self.write(cr, uid, id, {'history':history or '' + "\n" + time.strftime("%Y-%m-%d %H:%M:%S") + ": " + tools.ustr(message)}, context)
100     
101     _columns = {
102             'email_from':fields.char(
103                             'From', 
104                             size=64),
105             'email_to':fields.char(
106                             'Recepient (To)', 
107                             size=250,),
108             'email_cc':fields.char(
109                             ' CC', 
110                             size=250),
111             'email_bcc':fields.char(
112                             ' BCC', 
113                             size=250),
114             'subject':fields.char(
115                             ' Subject', 
116                             size=200,),
117             'body_text':fields.text(
118                             'Standard Body (Text)'),
119             'body_html':fields.text(
120                             'Body (Text-Web Client Only)'),
121             'attachments_ids':fields.many2many(
122                             'ir.attachment', 
123                             'mail_attachments_rel', 
124                             'mail_id', 
125                             'att_id', 
126                             'Attachments'),
127             'account_id' :fields.many2one(
128                             'email_template.account',
129                             'User account', 
130                             required=True),
131             'user':fields.related(
132                             'account_id', 
133                             'user', 
134                             type="many2one", 
135                             relation="res.users", 
136                             string="User"),
137             'server_ref':fields.integer(
138                             'Server Reference of mail', 
139                             help="Applicable for inward items only"),
140             'mail_type':fields.selection([
141                             ('multipart/mixed', 
142                              'Has Attachments'),
143                             ('multipart/alternative', 
144                              'Plain Text & HTML with no attachments'),
145                             ('multipart/related', 
146                              'Intermixed content'),
147                             ('text/plain', 
148                              'Plain Text'),
149                             ('text/html', 
150                              'HTML Body'),
151                             ], 'Mail Contents'),
152             #I like GMAIL which allows putting same mail in many folders
153             #Lets plan it for 0.9
154             'folder':fields.selection([
155                             ('drafts', 'Drafts'),
156                             ('outbox', 'Outbox'),
157                             ('trash', 'Trash'),
158                             ('sent', 'Sent Items'),
159                             ], 'Folder', required=True),
160             'state':fields.selection([
161                             ('na', 'Not Applicable'),
162                             ('sending', 'Sending'),
163                             ], 'Status', required=True),
164             'date_mail':fields.datetime(
165                             'Rec/Sent Date'),
166             'history':fields.text(
167                             'History', 
168                             readonly=True, 
169                             store=True)
170         }
171
172     _defaults = {
173         'state': lambda * a: 'na',
174         'folder': lambda * a: 'outbox',
175     } 
176
177 email_template_mailbox()
178
179 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: