1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2010-today OpenERP SA (<http://www.openerp.com>)
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
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
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/>
20 ##############################################################################
28 from osv import fields
29 from tools.translate import _
31 _logger = logging.getLogger(__name__)
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. """
38 _description = 'Outgoing Mails'
39 _inherits = {'mail.message': 'mail_message_id'}
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'),
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"),
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')
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
74 'email_from': lambda self, cr, uid, ctx=None: self._get_default_from(cr, uid, ctx),
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)
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)
90 def mark_outgoing(self, cr, uid, ids, context=None):
91 return self.write(cr, uid, ids, {'state': 'outgoing'}, context=context)
93 def cancel(self, cr, uid, ids, context=None):
94 return self.write(cr, uid, ids, {'state': 'cancel'}, context=context)
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!
101 :param list ids: optional list of emails ids to send. If passed
102 no search is performed, and these ids are used
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'
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)
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)
124 _logger.exception("Failed processing mail queue")
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.
133 :param browse_record mail: the mail that was just sent
140 def _send_get_mail_subject(self, cr, uid, mail, force=False, partner=None, context=None):
141 """ if void and related document: '<Author> posted on <Resource>'
143 :param force: force the 'Author posted'... subject
144 :param mail: mail.mail browse_record
145 :param partner: browse_record of the specific recipient partner
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)
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.
156 :param mail: mail.mail browse_record
157 :param partner: browse_record of the specific recipient partner
159 return mail.body_html
161 def _send_get_ir_email_dict(self, cr, uid, mail, partner=None, context=None):
162 """ Return a dictionary for specific ir_email values, depending on a
163 partner, or generic to the whole recipients given by mail.email_to.
165 :param mail: mail.mail browse_record
166 :param partner: browse_record of the specific recipient partner
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)
174 'body_alternative': body_alternative,
176 'email_to': email_to,
179 def send(self, cr, uid, ids, auto_commit=False, notifier_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.
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)
192 ir_mail_server = self.pool.get('ir.mail_server')
193 for mail in self.browse(cr, uid, ids, context=context):
197 for attach in mail.attachment_ids:
198 attachments.append((attach.datas_fname, base64.b64decode(attach.datas)))
199 # specific behavior to customize the send email for notified partners
202 for partner in self.pool.get('res.partner').browse(cr, uid, notifier_ids, context=context):
203 ir_email_list.append(self._send_get_ir_email_dict(cr, uid, mail, partner=partner, context=context))
205 ir_email_list.append(self._send_get_ir_email_dict(cr, uid, mail, context=context))
207 # build an RFC2822 email.message.Message object and send it without queuing
208 for ir_email in ir_email_list:
209 msg = ir_mail_server.build_email(
210 email_from = mail.email_from,
211 email_to = ir_email.get('email_to'),
212 subject = ir_email.get('subject'),
213 body = ir_email.get('body'),
214 body_alternative = ir_email.get('body_alternative'),
215 email_cc = tools.email_split(mail.email_cc),
216 reply_to = mail.reply_to,
217 attachments = attachments,
218 message_id = mail.message_id,
219 references = mail.references,
220 object_id = mail.res_id and ('%s-%s' % (mail.res_id, mail.model)),
222 subtype_alternative = 'plain')
223 res = ir_mail_server.send_email(cr, uid, msg,
224 mail_server_id=mail.mail_server_id.id, context=context)
226 mail.write({'state': 'sent', 'message_id': res})
228 mail.write({'state': 'exception'})
230 if mail.state == 'sent':
231 self._postprocess_sent_message(cr, uid, mail, context=context)
233 _logger.exception('failed sending mail.mail %s', mail.id)
234 mail.write({'state': 'exception'})
236 if auto_commit == True: