[FIX] email_tempalte : view and error on email
[odoo/odoo.git] / addons / email_template / email_template_mailbox.py
1 from osv import osv, fields
2 import time
3 import email_template_engines
4 import netsvc
5 from tools.translate import _
6 import tools
7
8 LOGGER = netsvc.Logger()
9
10 class email_template_mailbox(osv.osv):
11     _name = "email_template.mailbox"
12     _description = 'Email Mailbox'
13     _rec_name = "subject"
14     _order = "date_mail desc"
15     
16     def run_mail_scheduler(self, cursor, user, context=None):
17         """
18         This method is called by Open ERP Scheduler
19         to periodically send emails
20         """
21         try:
22             self.send_all_mail(cursor, user, context)
23         except Exception, e:
24             LOGGER.notifyChannel(
25                                  _("Email Template"),
26                                  netsvc.LOG_ERROR,
27                                  _("Error sending mail: %s" % str(e)))
28         
29     def send_all_mail(self, cr, uid, ids=None, context=None):
30         if ids is None:
31             ids = []
32         if context is None:
33             context = {}
34         filters = [('folder', '=', 'outbox'), ('state', '!=', 'sending')]
35         if 'filters' in context.keys():
36             for each_filter in context['filters']:
37                 filters.append(each_filter)
38         ids = self.search(cr, uid, filters, context=context)
39         self.write(cr, uid, ids, {'state':'sending'}, context)
40         self.send_this_mail(cr, uid, ids, context)
41         return True
42     
43     def send_this_mail(self, cr, uid, ids=None, context=None):
44         for id in (ids or []):
45             try:
46                 account_obj = self.pool.get('email_template.account')
47                 values = self.read(cr, uid, id, [], context) 
48                 payload = {}
49                 if values['attachments_ids']:
50                     for attid in values['attachments_ids']:
51                         attachment = self.pool.get('ir.attachment').browse(cr, uid, attid, context)#,['datas_fname','datas'])
52                         payload[attachment.datas_fname] = attachment.datas
53                 result = account_obj.send_mail(cr, uid,
54                               [values['account_id'][0]],
55                               {'To':values.get('email_to', u'') or u'', 'CC':values.get('email_cc', u'') or u'', 'BCC':values.get('email_bcc', u'') or u''},
56                               values['subject'] or u'',
57                               {'text':values.get('body_text', u'') or u'', 'html':values.get('body_html', u'') or u''},
58                               payload=payload, context=context)
59                 if result == True:
60                     self.write(cr, uid, id, {'folder':'sent', 'state':'na', 'date_mail':time.strftime("%Y-%m-%d %H:%M:%S")}, context)
61                     self.historise(cr, uid, [id], "Email sent successfully", context)
62                 else:
63                     error = result['error_msg']
64                     self.historise(cr, uid, [id], error, context)
65                     
66             except Exception, error:
67                 logger = netsvc.Logger()
68                 logger.notifyChannel(_("Power Email"), netsvc.LOG_ERROR, _("Sending of Mail %s failed. Probable Reason:Could not login to server\nError: %s") % (id, error))
69                 self.historise(cr, uid, [id], error, context)
70             self.write(cr, uid, id, {'state':'na'}, context)
71         return result
72     
73     def historise(self, cr, uid, ids, message='', context=None):
74         for id in ids:
75             history = self.read(cr, uid, id, ['history'], context).get('history', '')
76             self.write(cr, uid, id, {'history':history or '' + "\n" + time.strftime("%Y-%m-%d %H:%M:%S") + ": " + tools.ustr(message)}, context)
77     
78     _columns = {
79             'email_from':fields.char(
80                             'From', 
81                             size=64),
82             'email_to':fields.char(
83                             'Recepient (To)', 
84                             size=250,),
85             'email_cc':fields.char(
86                             ' CC', 
87                             size=250),
88             'email_bcc':fields.char(
89                             ' BCC', 
90                             size=250),
91             'subject':fields.char(
92                             ' Subject', 
93                             size=200,),
94             'body_text':fields.text(
95                             'Standard Body (Text)'),
96             'body_html':fields.text(
97                             'Body (Text-Web Client Only)'),
98             'attachments_ids':fields.many2many(
99                             'ir.attachment', 
100                             'mail_attachments_rel', 
101                             'mail_id', 
102                             'att_id', 
103                             'Attachments'),
104             'account_id' :fields.many2one(
105                             'email_template.account',
106                             'User account', 
107                             required=True),
108             'user':fields.related(
109                             'account_id', 
110                             'user', 
111                             type="many2one", 
112                             relation="res.users", 
113                             string="User"),
114             'server_ref':fields.integer(
115                             'Server Reference of mail', 
116                             help="Applicable for inward items only"),
117             'mail_type':fields.selection([
118                             ('multipart/mixed', 
119                              'Has Attachments'),
120                             ('multipart/alternative', 
121                              'Plain Text & HTML with no attachments'),
122                             ('multipart/related', 
123                              'Intermixed content'),
124                             ('text/plain', 
125                              'Plain Text'),
126                             ('text/html', 
127                              'HTML Body'),
128                             ], 'Mail Contents'),
129             #I like GMAIL which allows putting same mail in many folders
130             #Lets plan it for 0.9
131             'folder':fields.selection([
132                             ('drafts', 'Drafts'),
133                             ('outbox', 'Outbox'),
134                             ('trash', 'Trash'),
135                             ('sent', 'Sent Items'),
136                             ], 'Folder', required=True),
137             'state':fields.selection([
138                             ('na', 'Not Applicable'),
139                             ('sending', 'Sending'),
140                             ], 'Status', required=True),
141             'date_mail':fields.datetime(
142                             'Rec/Sent Date'),
143             'history':fields.text(
144                             'History', 
145                             readonly=True, 
146                             store=True)
147         }
148
149     _defaults = {
150         'state': lambda * a: 'na',
151         'folder': lambda * a: 'outbox',
152     } 
153
154 email_template_mailbox()
155
156 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: