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, context=None):
141 """ if void and related document: '<Author> posted on <Resource>'
142 :param mail: mail.mail browse_record """
143 if force or (not mail.subject and mail.model and mail.res_id):
144 return '%s posted on %s' % (mail.author_id.name, mail.record_name)
147 def send(self, cr, uid, ids, auto_commit=False, context=None):
148 """ Sends the selected emails immediately, ignoring their current
149 state (mails that have already been sent should not be passed
150 unless they should actually be re-sent).
151 Emails successfully delivered are marked as 'sent', and those
152 that fail to be deliver are marked as 'exception', and the
153 corresponding error mail is output in the server logs.
155 :param bool auto_commit: whether to force a commit of the mail status
156 after sending each mail (meant only for scheduler processing);
157 should never be True during normal transactions (default: False)
160 ir_mail_server = self.pool.get('ir.mail_server')
161 for mail in self.browse(cr, uid, ids, context=context):
163 body = mail.body_html
164 subject = self._send_get_mail_subject(cr, uid, mail, context=context)
168 for attach in mail.attachment_ids:
169 attachments.append((attach.datas_fname, base64.b64decode(attach.datas)))
171 # use only sanitized html and set its plaintexted version as alternative
172 body_alternative = tools.html2plaintext(body)
173 content_subtype_alternative = 'plain'
175 # build an RFC2822 email.message.Message object and send it without queuing
176 msg = ir_mail_server.build_email(
177 email_from = mail.email_from,
178 email_to = tools.email_split(mail.email_to),
181 body_alternative = body_alternative,
182 email_cc = tools.email_split(mail.email_cc),
183 reply_to = mail.reply_to,
184 attachments = attachments,
185 message_id = mail.message_id,
186 references = mail.references,
187 object_id = mail.res_id and ('%s-%s' % (mail.res_id, mail.model)),
189 subtype_alternative = content_subtype_alternative)
190 res = ir_mail_server.send_email(cr, uid, msg,
191 mail_server_id=mail.mail_server_id.id, context=context)
193 mail.write({'state': 'sent', 'message_id': res})
195 mail.write({'state': 'exception'})
197 if mail.state == 'sent':
198 self._postprocess_sent_message(cr, uid, mail, context=context)
200 _logger.exception('failed sending mail.mail %s', mail.id)
201 mail.write({'state': 'exception'})
203 if auto_commit == True: