[CLEAN] mail: cleaned mail-invite before merging. Updated some methods and var names...
[odoo/odoo.git] / addons / mail / mail_mail.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2010-today OpenERP SA (<http://www.openerp.com>)
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>
19 #
20 ##############################################################################
21
22 # import ast
23 import base64
24 import logging
25 import tools
26
27 from osv import osv
28 from osv import fields
29 from tools.translate import _
30
31 _logger = logging.getLogger(__name__)
32
33
34 class mail_mail(osv.Model):
35     """ Model holding RFC2822 email messages to send. This model also provides
36         facilities to queue and send new email messages.  """
37     _name = 'mail.mail'
38     _description = 'Outgoing Mails'
39     _inherits = {'mail.message': 'mail_message_id'}
40     _order = 'id desc'
41
42     _columns = {
43         'mail_message_id': fields.many2one('mail.message', 'Message', required=True, ondelete='cascade'),
44         'mail_server_id': fields.many2one('ir.mail_server', 'Outgoing mail server', readonly=1),
45         'state': fields.selection([
46             ('outgoing', 'Outgoing'),
47             ('sent', 'Sent'),
48             ('received', 'Received'),
49             ('exception', 'Delivery Failed'),
50             ('cancel', 'Cancelled'),
51         ], 'Status', readonly=True),
52         'auto_delete': fields.boolean('Auto Delete',
53             help="Permanently delete this email after sending it, to save space"),
54         'references': fields.text('References', help='Message references, such as identifiers of previous messages', readonly=1),
55         'email_from': fields.char('From', help='Message sender, taken from user preferences.'),
56         'email_to': fields.text('To', help='Message recipients'),
57         'email_cc': fields.char('Cc', help='Carbon copy message recipients'),
58         'reply_to': fields.char('Reply-To', help='Preferred response address for the message'),
59         'body_html': fields.text('Rich-text Contents', help="Rich-text/HTML message"),
60
61         # Auto-detected based on create() - if 'mail_message_id' was passed then this mail is a notification
62         # and during unlink() we will not cascade delete the parent and its attachments
63         'notification': fields.boolean('Is Notification')
64     }
65
66     def _get_default_from(self, cr, uid, context=None):
67         cur = self.pool.get('res.users').browse(cr, uid, uid, context=context)
68         if not cur.alias_domain:
69             raise osv.except_osv(_('Invalid Action!'), _('Unable to send email, set an alias domain in your server settings.'))
70         return cur.alias_name + '@' + cur.alias_domain
71
72     _defaults = {
73         'state': 'outgoing',
74         'email_from': lambda self, cr, uid, ctx=None: self._get_default_from(cr, uid, ctx),
75     }
76
77     def create(self, cr, uid, values, context=None):
78         if 'notification' not in values and values.get('mail_message_id'):
79             values['notification'] = True
80         return super(mail_mail, self).create(cr, uid, values, context=context)
81
82     def unlink(self, cr, uid, ids, context=None):
83         # cascade-delete the parent message for all mails that are not created for a notification
84         ids_to_cascade = self.search(cr, uid, [('notification', '=', False), ('id', 'in', ids)])
85         parent_msg_ids = [m.mail_message_id.id for m in self.browse(cr, uid, ids_to_cascade, context=context)]
86         res = super(mail_mail, self).unlink(cr, uid, ids, context=context)
87         self.pool.get('mail.message').unlink(cr, uid, parent_msg_ids, context=context)
88         return res
89
90     def mark_outgoing(self, cr, uid, ids, context=None):
91         return self.write(cr, uid, ids, {'state': 'outgoing'}, context=context)
92
93     def cancel(self, cr, uid, ids, context=None):
94         return self.write(cr, uid, ids, {'state': 'cancel'}, context=context)
95
96     def process_email_queue(self, cr, uid, ids=None, context=None):
97         """Send immediately queued messages, committing after each
98            message is sent - this is not transactional and should
99            not be called during another transaction!
100
101            :param list ids: optional list of emails ids to send. If passed
102                             no search is performed, and these ids are used
103                             instead.
104            :param dict context: if a 'filters' key is present in context,
105                                 this value will be used as an additional
106                                 filter to further restrict the outgoing
107                                 messages to send (by default all 'outgoing'
108                                 messages are sent).
109         """
110         if context is None:
111             context = {}
112         if not ids:
113             filters = ['&', ('state', '=', 'outgoing'), ('type', '=', 'email')]
114             if 'filters' in context:
115                 filters.extend(context['filters'])
116             ids = self.search(cr, uid, filters, context=context)
117         res = None
118         try:
119             # Force auto-commit - this is meant to be called by
120             # the scheduler, and we can't allow rolling back the status
121             # of previously sent emails!
122             res = self.send(cr, uid, ids, auto_commit=True, context=context)
123         except Exception:
124             _logger.exception("Failed processing mail queue")
125         return res
126
127     def _postprocess_sent_message(self, cr, uid, mail, context=None):
128         """Perform any post-processing necessary after sending ``mail``
129         successfully, including deleting it completely along with its
130         attachment if the ``auto_delete`` flag of the mail was set.
131         Overridden by subclasses for extra post-processing behaviors.
132
133         :param browse_record mail: the mail that was just sent
134         :return: True
135         """
136         if mail.auto_delete:
137             mail.unlink()
138         return True
139
140     def send_get_mail_subject(self, cr, uid, mail, force=False, partner=None, context=None):
141         """ If subject is void and record_name defined: '<Author> posted on <Resource>'
142
143             :param boolean force: force the subject replacement
144             :param browse_record mail: mail.mail browse_record
145             :param browse_record partner: specific recipient partner
146         """
147         if force or (not mail.subject and mail.model and mail.res_id):
148             return '%s posted on %s' % (mail.author_id.name, mail.record_name)
149         return mail.subject
150
151     def send_get_mail_body(self, cr, uid, mail, partner=None, context=None):
152         """ Return a specific ir_email body. The main purpose of this method
153             is to be inherited by Portal, to add a link for signing in, in
154             each notification email a partner receives.
155
156             :param browse_record mail: mail.mail browse_record
157             :param browse_record partner: specific recipient partner
158         """
159         return mail.body_html
160
161     def send_get_email_dict(self, cr, uid, mail, partner=None, context=None):
162         """ Return a dictionary for specific email values, depending on a
163             partner, or generic to the whole recipients given by mail.email_to.
164
165             :param browse_record mail: mail.mail browse_record
166             :param browse_record partner: specific recipient partner
167         """
168         body = self.send_get_mail_body(cr, uid, mail, partner=partner, context=context)
169         subject = self.send_get_mail_subject(cr, uid, mail, partner=partner, context=context)
170         body_alternative = tools.html2plaintext(body)
171         email_to = [partner.email] if partner else tools.email_split(mail.email_to)
172         return {
173             'body': body,
174             'body_alternative': body_alternative,
175             'subject': subject,
176             'email_to': email_to,
177         }
178
179     def send(self, cr, uid, ids, auto_commit=False, recipient_ids=None, context=None):
180         """ Sends the selected emails immediately, ignoring their current
181             state (mails that have already been sent should not be passed
182             unless they should actually be re-sent).
183             Emails successfully delivered are marked as 'sent', and those
184             that fail to be deliver are marked as 'exception', and the
185             corresponding error mail is output in the server logs.
186
187             :param bool auto_commit: whether to force a commit of the mail status
188                 after sending each mail (meant only for scheduler processing);
189                 should never be True during normal transactions (default: False)
190             :param list recipient_ids: specific list of res.partner recipients.
191                 If set, one email is sent to each partner. Its is possible to
192                 tune the sent email through ``send_get_mail_body`` and ``send_get_mail_subject``.
193                 If not specified, one email is sent to mail_mail.email_to.
194             :return: True
195         """
196         ir_mail_server = self.pool.get('ir.mail_server')
197         for mail in self.browse(cr, uid, ids, context=context):
198             try:
199                 # handle attachments
200                 attachments = []
201                 for attach in mail.attachment_ids:
202                     attachments.append((attach.datas_fname, base64.b64decode(attach.datas)))
203                 # specific behavior to customize the send email for notified partners
204                 email_list = []
205                 if recipient_ids:
206                     for partner in self.pool.get('res.partner').browse(cr, uid, recipient_ids, context=context):
207                         email_list.append(self.send_get_email_dict(cr, uid, mail, partner=partner, context=context))
208                 else:
209                     email_list.append(self.send_get_email_dict(cr, uid, mail, context=context))
210
211                 # build an RFC2822 email.message.Message object and send it without queuing
212                 for email in email_list:
213                     msg = ir_mail_server.build_email(
214                         email_from = mail.email_from,
215                         email_to = email.get('email_to'),
216                         subject = email.get('subject'),
217                         body = email.get('body'),
218                         body_alternative = email.get('body_alternative'),
219                         email_cc = tools.email_split(mail.email_cc),
220                         reply_to = mail.reply_to,
221                         attachments = attachments,
222                         message_id = mail.message_id,
223                         references = mail.references,
224                         object_id = mail.res_id and ('%s-%s' % (mail.res_id, mail.model)),
225                         subtype = 'html',
226                         subtype_alternative = 'plain')
227                     res = ir_mail_server.send_email(cr, uid, msg,
228                         mail_server_id=mail.mail_server_id.id, context=context)
229                 if res:
230                     mail.write({'state': 'sent', 'message_id': res})
231                 else:
232                     mail.write({'state': 'exception'})
233                 mail.refresh()
234                 if mail.state == 'sent':
235                     self._postprocess_sent_message(cr, uid, mail, context=context)
236             except Exception:
237                 _logger.exception('failed sending mail.mail %s', mail.id)
238                 mail.write({'state': 'exception'})
239
240             if auto_commit == True:
241                 cr.commit()
242         return True