如何以编程方式向用户发送电子邮件? (OpenERP & Python)

How to send an email to a user programatically? (OpenERP & Python)

在我的 OpenERP 模块中,我偶尔需要向我的用户发送通知或消息,但是使用 res.users.message_post 的明显方式(至少对我而言)是在用户记录上放置消息而不是发送给用户的消息。有什么想法吗?

在发送消息之前,您需要安装 Social Network 模块(如果您想查看其代码,它位于 .../addons/mail 中)。

之后,以下代码片段将完成这项工作:

from openerp import SUPERUSER_ID

def send_message(oe, cr, user_ids, subject, body):
    "sends message to user_ids"
    mail_message = oe.pool.get('mail.message')
    mail_message_subtype = oe.pool.get('mail.message.subtype')
    [discussion_id] = mail_message_subtype.browse(
            cr, SUPERUSER_ID, [('name','=','Discussions')]
            )
    users = oe.pool.get('res.users').search(cr, uid, user_ids)
    mail_message.create(cr, SUPERUSER_ID, values=dict(
            type='email',
            subtype_id=discussion.id,
            partner_ids=[(4, u.partner_id.id) for u in users],
            subject=subject,
            body=body,
            ))

将其填充到某个实用程序模块中,您就可以开始了。

一些评论:

  • 调用时,将self作为第一个参数传递 send_message(self, cr, ...)
  • 如果你想让它成为 class 的方法,只需将 oe 替换为 self,并从参数中省略 self
  • 这将在 OpenERP 中向用户发送一条消息,如果任何用户 his/her 首选项设置为转发到外部电子邮件,将为他们生成一封实际电子邮件。