~zaber/openupgrade-addons/missing-import

« back to all changes in this revision

Viewing changes to email_template/email_template_mailbox.py

[NEW] email_template (extracted from poweremail) just to send emails -specially for the marketing_campaign

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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
        if ids is None:
 
45
            ids = []
 
46
        for id in ids:
 
47
            try:
 
48
                account_obj = self.pool.get('email_template.account')
 
49
                values = self.read(cr, uid, id, [], context) 
 
50
                payload = {}
 
51
                if values['attachments_ids']:
 
52
                    for attid in values['attachments_ids']:
 
53
                        attachment = self.pool.get('ir.attachment').browse(cr, uid, attid, context)#,['datas_fname','datas'])
 
54
                        payload[attachment.datas_fname] = attachment.datas
 
55
                    print "233333333333333"
 
56
                result = account_obj.send_mail(cr, uid,
 
57
                              [values['account_id'][0]],
 
58
                              {'To':values.get('email_to', u'') or u'', 'CC':values.get('email_cc', u'') or u'', 'BCC':values.get('email_bcc', u'') or u''},
 
59
                              values['subject'] or u'',
 
60
                              {'text':values.get('body_text', u'') or u'', 'html':values.get('body_html', u'') or u''},
 
61
                              payload=payload, context=context)
 
62
                
 
63
                if result == True:
 
64
                    self.write(cr, uid, id, {'folder':'sent', 'state':'na', 'date_mail':time.strftime("%Y-%m-%d %H:%M:%S")}, context)
 
65
                    self.historise(cr, uid, [id], "Email sent successfully", context)
 
66
                else:
 
67
                    self.historise(cr, uid, [id], result, context)
 
68
            except Exception, error:
 
69
                logger = netsvc.Logger()
 
70
                logger.notifyChannel(_("Power Email"), netsvc.LOG_ERROR, _("Sending of Mail %s failed. Probable Reason:Could not login to server\nError: %s") % (id, error))
 
71
                self.historise(cr, uid, [id], error, context)
 
72
            self.write(cr, uid, id, {'state':'na'}, context)
 
73
        return True
 
74
    
 
75
    def historise(self, cr, uid, ids, message='', context=None):
 
76
        for id in ids:
 
77
            history = self.read(cr, uid, id, ['history'], context).get('history', '')
 
78
            self.write(cr, uid, id, {'history':history or '' + "\n" + time.strftime("%Y-%m-%d %H:%M:%S") + ": " + tools.ustr(message)}, context)
 
79
    
 
80
    _columns = {
 
81
            'email_from':fields.char(
 
82
                            'From', 
 
83
                            size=64),
 
84
            'email_to':fields.char(
 
85
                            'Recepient (To)', 
 
86
                            size=250,),
 
87
            'email_cc':fields.char(
 
88
                            ' CC', 
 
89
                            size=250),
 
90
            'email_bcc':fields.char(
 
91
                            ' BCC', 
 
92
                            size=250),
 
93
            'subject':fields.char(
 
94
                            ' Subject', 
 
95
                            size=200,),
 
96
            'body_text':fields.text(
 
97
                            'Standard Body (Text)'),
 
98
            'body_html':fields.text(
 
99
                            'Body (Text-Web Client Only)'),
 
100
            'attachments_ids':fields.many2many(
 
101
                            'ir.attachment', 
 
102
                            'mail_attachments_rel', 
 
103
                            'mail_id', 
 
104
                            'att_id', 
 
105
                            'Attachments'),
 
106
            'account_id' :fields.many2one(
 
107
                            'email_template.account',
 
108
                            'User account', 
 
109
                            required=True),
 
110
            'user':fields.related(
 
111
                            'account_id', 
 
112
                            'user', 
 
113
                            type="many2one", 
 
114
                            relation="res.users", 
 
115
                            string="User"),
 
116
            'server_ref':fields.integer(
 
117
                            'Server Reference of mail', 
 
118
                            help="Applicable for inward items only"),
 
119
            'mail_type':fields.selection([
 
120
                            ('multipart/mixed', 
 
121
                             'Has Attachments'),
 
122
                            ('multipart/alternative', 
 
123
                             'Plain Text & HTML with no attachments'),
 
124
                            ('multipart/related', 
 
125
                             'Intermixed content'),
 
126
                            ('text/plain', 
 
127
                             'Plain Text'),
 
128
                            ('text/html', 
 
129
                             'HTML Body'),
 
130
                            ], 'Mail Contents'),
 
131
            #I like GMAIL which allows putting same mail in many folders
 
132
            #Lets plan it for 0.9
 
133
            'folder':fields.selection([
 
134
                            ('drafts', 'Drafts'),
 
135
                            ('outbox', 'Outbox'),
 
136
                            ('trash', 'Trash'),
 
137
                            ('sent', 'Sent Items'),
 
138
                            ], 'Folder', required=True),
 
139
            'state':fields.selection([
 
140
                            ('na', 'Not Applicable'),
 
141
                            ('sending', 'Sending'),
 
142
                            ], 'Status', required=True),
 
143
            'date_mail':fields.datetime(
 
144
                            'Rec/Sent Date'),
 
145
            'history':fields.text(
 
146
                            'History', 
 
147
                            readonly=True, 
 
148
                            store=True)
 
149
        }
 
150
 
 
151
    _defaults = {
 
152
        'state': lambda * a: 'na',
 
153
        'folder': lambda * a: 'outbox',
 
154
    } 
 
155
 
 
156
    def search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False):
 
157
        if context is None:
 
158
            context = {}
 
159
        if context.get('company', False):
 
160
            users_groups = self.pool.get('res.users').browse(cr, uid, uid, context).groups_id
 
161
            group_acc_rel = {}
 
162
            #get all accounts and get a table of {group1:[account1,account2],group2:[account1]}
 
163
            for each_account_id in self.pool.get('email_template.account').search(cr, uid, [('state', '=', 'approved'), ('company', '=', 'yes')], context=context):
 
164
                account = self.pool.get('email_template.account').browse(cr, uid, each_account_id, context)
 
165
                for each_group in account.allowed_groups:
 
166
                    if not account.id in group_acc_rel.get(each_group, []):
 
167
                        groups = group_acc_rel.get(each_group, [])
 
168
                        groups.append(account.id)
 
169
                        group_acc_rel[each_group] = groups
 
170
            users_company_accounts = []
 
171
            for each_group in group_acc_rel.keys():
 
172
                if each_group in users_groups:
 
173
                    for each_account in group_acc_rel[each_group]:
 
174
                        if not each_account in users_company_accounts:
 
175
                            users_company_accounts.append(each_account)
 
176
            args.append(('account_id', 'in', users_company_accounts))
 
177
        return super(osv.osv, self).search(cr, uid, args, offset, limit,
 
178
                order, context=context, count=count)
 
179
 
 
180
email_template_mailbox()
 
181
 
 
182
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: