-
Notifications
You must be signed in to change notification settings - Fork 20
/
core.py
1232 lines (1176 loc) · 57 KB
/
core.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#########################################################################
# #
# Copyright (C) 2010-2011 Openlabs Technologies & Consulting (P) LTD #
# Copyright (C) 2009 Sharoon Thomas #
# #
#This program is free software: you can redistribute it and/or modify #
#it under the terms of the GNU General Public License as published by #
#the Free Software Foundation, either version 3 of the License, or #
#(at your option) any later version. #
# #
#This program is distributed in the hope that it will be useful, #
#but WITHOUT ANY WARRANTY; without even the implied warranty of #
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
#GNU General Public License for more details. #
# #
#You should have received a copy of the GNU General Public License #
#along with this program. If not, see <http://www.gnu.org/licenses/>. #
#########################################################################
import re
import smtplib
import poplib
import imaplib
import base64
import string
import email
import time
import datetime
import warnings
from email import Encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import decode_header, Header
from email.utils import formatdate
import netsvc
from osv import osv, fields
from tools.translate import _
import tools
class poweremail_core_accounts(osv.osv):
"""Email Accounts"""
_name = "poweremail.core_accounts"
_description = __doc__
_known_content_types = [
'multipart/mixed',
'multipart/alternative',
'multipart/related',
'text/plain',
'text/html',
]
_columns = {
'name': fields.char(
'Name', size=64, required=True,
readonly=True, select=True, states={
'draft': [('readonly', False)]
},
),
'user': fields.many2one(
'res.users', 'Related User', required=True,
readonly=True, states={
'draft':[('readonly', False)]
},
),
'email_id': fields.char(
'Email ID', size=120, required=True,
readonly=True, states={
'draft':[('readonly', False)]
}, help="eg: [email protected]"
),
'smtpserver': fields.char(
'Server', size=120, required=True,
readonly=True, states={
'draft':[('readonly', False)]
}, help="Enter name of outgoing server, eg: smtp.gmail.com"
),
'smtpport': fields.integer(
'SMTP Port ', size=64, required=True,
readonly=True, states={
'draft':[('readonly', False)]
}, help="Enter port number, eg: SMTP-587"
),
'smtpuname': fields.char(
'User Name', size=120, required=False,
readonly=True, states={
'draft':[('readonly', False)]
},
),
'smtppass': fields.char(
'Password', size=120,
required=False, readonly=True, states={
'draft':[('readonly', False)]
},
),
'smtptls': fields.boolean(
'Use TLS', readonly=True, states={
'draft':[('readonly', False)]
},
),
'smtpssl': fields.boolean(
'Use SSL/TLS (only in python 2.6)', readonly=True, states={
'draft':[('readonly', False)]
},
),
'send_pref': fields.selection([
('html', 'HTML otherwise Text'),
('text', 'Text otherwise HTML'),
('both', 'Both HTML & Text'),
], 'Mail Format', required=True
),
'iserver': fields.char(
'Incoming Server', size=100, readonly=True,
states={
'draft':[('readonly', False)]
}, help="Enter name of incoming server, eg: imap.gmail.com"
),
'isport': fields.integer(
'Port', readonly=True, states={
'draft':[('readonly', False)]
}, help="For example IMAP: 993,POP3:995"
),
'isuser': fields.char(
'User Name', size=100, readonly=True, states={
'draft':[('readonly', False)]
},
),
'ispass': fields.char(
'Password', size=100, readonly=True,
states={
'draft':[('readonly', False)]
},
),
'iserver_type': fields.selection([
('imap', 'IMAP'),
('pop3', 'POP3')
], 'Server Type', readonly=True, states={
'draft':[('readonly', False)]
},
),
'isssl': fields.boolean(
'Use SSL', readonly=True, states={
'draft':[('readonly', False)],
},
),
'isfolder': fields.char(
'Folder', readonly=True, size=100, help="Folder to be used for "
"downloading IMAP mails.\n Click on adjacent button to select "
"from a list of folders."
),
'last_mail_id': fields.integer(
'Last Downloaded Mail', readonly=True
),
'rec_headers_den_mail': fields.boolean(
'First Receive headers, then download mail'
),
'dont_auto_down_attach': fields.boolean(
'Dont Download attachments automatically'
),
'allowed_groups': fields.many2many(
'res.groups', 'account_group_rel', 'templ_id', 'group_id',
string="Allowed User Groups", help="Only users from these groups "
"will be allowed to send mails from this ID."
),
'company': fields.selection([
('yes', 'Yes'),
('no', 'No'),
], 'Company Mail A/c', readonly=True, required=True, states={
'draft':[('readonly', False)]
}, help="Select if this mail account does not belong to specific "
"user but the organisation as a whole. eg: [email protected]"
),
'state': fields.selection([
('draft', 'Initiated'),
('suspended', 'Suspended'),
('approved', 'Approved'),
], 'Account Status', required=True, readonly=True
),
}
_defaults = {
'name':lambda self, cursor, user, context:self.pool.get(
'res.users'
).read(
cursor,
user,
user,
['name'],
context
)['name'],
'smtpssl':lambda * a:True,
'state':lambda * a:'draft',
'user':lambda self, cursor, user, context:user,
'iserver_type':lambda * a:'imap',
'isssl': lambda * a: True,
'last_mail_id':lambda * a:0,
'rec_headers_den_mail':lambda * a:True,
'dont_auto_down_attach':lambda * a:True,
'send_pref':lambda * a: 'html',
'smtptls':lambda * a:True,
}
_sql_constraints = [
(
'email_uniq',
'unique (email_id)',
'Another setting already exists with this email ID !')
]
def _constraint_unique(self, cursor, user, ids):
"""
This makes sure that you dont give personal
users two accounts with same ID (Validated in sql constaints)
However this constraint exempts company accounts.
Any no of co accounts for a user is allowed
"""
if self.read(cursor, user, ids, ['company'])[0]['company'] == 'no':
accounts = self.search(cursor, user, [
('user', '=', user),
('company', '=', 'no')
])
if len(accounts) > 1 :
return False
else :
return True
else:
return True
_constraints = [
(_constraint_unique,
'Error: You are not allowed to have more than 1 account.',
[])
]
def on_change_emailid(self, cursor, user, ids, name=None, email_id=None, context=None):
"""
Called when the email ID field changes.
UI enhancement
Writes the same email value to the smtpusername
and incoming username
"""
#TODO: Check and remove the write. Is it needed?
self.write(cursor, user, ids, {'state':'draft'}, context=context)
return {
'value': {
'state': 'draft',
'smtpuname':email_id,
'isuser':email_id
}
}
def _get_outgoing_server(self, cursor, user, account_id, context=None):
"""Returns the Out Going Connection (SMTP) object
.. attention:
DO NOT USE except_osv IN THIS METHOD
:param cursor: Database Cursor
:param user: ID of current user
:param account_id: ID of email account
:param context: Context
:return: SMTP server object
"""
if type(account_id) == list:
warnings.warn(
"Support for passing list of ids to _get_outgoing_server "
"will be deprecated in 0.8", DeprecationWarning
)
account_id = account_id[0]
account = self.browse(cursor, user, account_id, context)
if not account:
raise Exception(_("Connection for the given ID does not exist"))
if not (account.smtpserver and account.smtpport):
raise Exception(_("SMTP SERVER or PORT not specified"))
if account.smtpssl:
server = smtplib.SMTP_SSL(account.smtpserver, account.smtpport)
else:
server = smtplib.SMTP(account.smtpserver, account.smtpport)
if account.smtptls:
server.ehlo()
server.starttls()
server.ehlo()
if server.has_extn('AUTH') and account.smtpuname and account.smtppass:
server.login(
account.smtpuname.encode('UTF-8'),
account.smtppass.encode('UTF-8')
)
return server
def check_outgoing_connection(self, cursor, user, ids, context=None):
"""
checks SMTP credentials and confirms if outgoing connection works
(Attached to button)
@param cursor: Database Cursor
@param user: ID of current user
@param ids: list of ids of current object for
which connection is required
@param context: Context
"""
try:
self._get_outgoing_server(cursor, user, ids, context)
raise osv.except_osv(_("SMTP Test Connection Was Successful"), '')
except osv.except_osv, success_message:
raise success_message
except Exception, error:
raise osv.except_osv(
_("Out going connection test failed"),
_("Reason: %s") % error
)
def _get_imap_server(self, record):
"""
@param record: Browse record of current connection
@return: IMAP or IMAP_SSL object
"""
if record:
if record.isssl:
serv = imaplib.IMAP4_SSL(record.iserver, record.isport)
else:
serv = imaplib.IMAP4(record.iserver, record.isport)
#Now try to login
serv.login(record.isuser, record.ispass)
return serv
raise Exception(
_("Programming Error in _get_imap_server method. The record received is invalid.")
)
def _get_pop3_server(self, record):
"""
@param record: Browse record of current connection
@return: POP3 or POP3_SSL object
"""
if record:
if record.isssl:
serv = poplib.POP3_SSL(record.iserver, record.isport)
else:
serv = poplib.POP3(record.iserver, record.isport)
#Now try to login
serv.user(record.isuser)
serv.pass_(record.ispass)
return serv
raise Exception(
_("Programming Error in _get_pop3_server method. The record received is invalid.")
)
def _get_incoming_server(self, cursor, user, ids, context=None):
"""
Returns the Incoming Server object
Could be IMAP/IMAP_SSL/POP3/POP3_SSL
@attention: DO NOT USE except_osv IN THIS METHOD
@param cursor: Database Cursor
@param user: ID of current user
@param ids: ID/list of ids of current object for
which connection is required
First ID will be chosen from lists
@param context: Context
@return: IMAP/POP3 server object or Exception
"""
#Type cast ids to integer
if type(ids) == list:
ids = ids[0]
this_object = self.browse(cursor, user, ids, context)
if this_object:
#First validate data
if not this_object.iserver:
raise Exception(_("Incoming server is not defined"))
if not this_object.isport:
raise Exception(_("Incoming port is not defined"))
if not this_object.isuser:
raise Exception(_("Incoming server user name is not defined"))
if not this_object.isuser:
raise Exception(_("Incoming server password is not defined"))
#Now fetch the connection
if this_object.iserver_type == 'imap':
serv = self._get_imap_server(this_object)
elif this_object.iserver_type == 'pop3':
serv = self._get_pop3_server(this_object)
return serv
raise Exception(
_("The specified record for connection does not exist")
)
def check_incoming_connection(self, cursor, user, ids, context=None):
"""
checks incoming credentials and confirms if outgoing connection works
(Attached to button)
@param cursor: Database Cursor
@param user: ID of current user
@param ids: list of ids of current object for
which connection is required
@param context: Context
"""
try:
self._get_incoming_server(cursor, user, ids, context)
raise osv.except_osv(_("Incoming Test Connection Was Successful"), '')
except osv.except_osv, success_message:
raise success_message
except Exception, error:
raise osv.except_osv(
_("In coming connection test failed"),
_("Reason: %s") % error
)
def do_approval(self, cr, uid, ids, context={}):
#TODO: Check if user has rights
self.write(cr, uid, ids, {'state':'approved'}, context=context)
# wf_service = netsvc.LocalService("workflow")
def smtp_connection(self, cursor, user, id, context=None):
"""
This method should now wrap smtp_connection
"""
#This function returns a SMTP server object
logger = netsvc.Logger()
core_obj = self.browse(cursor, user, id, context)
if core_obj.smtpserver and core_obj.smtpport and core_obj.state == 'approved':
try:
serv = self._get_outgoing_server(cursor, user, id, context)
except Exception, error:
logger.notifyChannel(_("Power Email"), netsvc.LOG_ERROR, _("Mail from Account %s failed on login. Probable Reason: Could not login to server\nError: %s") % (id, error))
return False
#Everything is complete, now return the connection
return serv
else:
logger.notifyChannel(_("Power Email"), netsvc.LOG_ERROR, _("Mail from Account %s failed. Probable Reason: Account not approved") % id)
return False
#**************************** MAIL SENDING FEATURES ***********************#
def split_to_ids(self, ids_as_str):
"""
Identifies email IDs separated by separators
and returns a list
TODO: Doc this
"""
email_sep_by_commas = ids_as_str \
.replace('; ', ',') \
.replace(';', ',') \
.replace(', ', ',')
return email_sep_by_commas.split(',')
def get_ids_from_dict(self, addresses={}):
"""
TODO: Doc this
"""
result = {'all':[]}
keys = ['To', 'CC', 'BCC']
for each in keys:
ids_as_list = self.split_to_ids(addresses.get(each, u''))
while u'' in ids_as_list:
ids_as_list.remove(u'')
result[each] = ids_as_list
result['all'].extend(ids_as_list)
return result
def send_mail(self, cr, uid, ids, addresses, subject='', body=None, payload=None, context=None):
#TODO: Replace all this crap with a single email object
if body is None:
body = {}
if payload is None:
payload = {}
if context is None:
context = {}
logger = netsvc.Logger()
for id in ids:
core_obj = self.browse(cr, uid, id, context)
serv = self.smtp_connection(cr, uid, id)
if serv:
try:
msg = MIMEMultipart()
if subject:
msg['Subject'] = subject
sender_name = Header(core_obj.name, 'utf-8').encode()
msg['From'] = sender_name + " <" + core_obj.email_id + ">"
msg['Organization'] = tools.ustr(core_obj.user.company_id.name)
msg['Date'] = formatdate()
addresses_l = self.get_ids_from_dict(addresses)
if addresses_l['To']:
msg['To'] = u','.join(addresses_l['To'])
if addresses_l['CC']:
msg['CC'] = u','.join(addresses_l['CC'])
# if addresses_l['BCC']:
# msg['BCC'] = u','.join(addresses_l['BCC'])
if body.get('text', False):
temp_body_text = body.get('text', '')
l = len(temp_body_text.replace(' ', '').replace('\r', '').replace('\n', ''))
if l == 0:
body['text'] = u'No Mail Message'
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
if core_obj.send_pref == 'text' or core_obj.send_pref == 'both':
body_text = body.get('text', u'No Mail Message')
body_text = tools.ustr(body_text)
msg.attach(MIMEText(body_text.encode("utf-8"), _charset='UTF-8'))
if core_obj.send_pref == 'html' or core_obj.send_pref == 'both':
html_body = body.get('html', u'')
if len(html_body) == 0 or html_body == u'':
html_body = body.get('text', u'<p>No Mail Message</p>').replace('\n', '<br/>').replace('\r', '<br/>')
html_body = tools.ustr(html_body)
msg.attach(MIMEText(html_body.encode("utf-8"), _subtype='html', _charset='UTF-8'))
#Now add attachments if any
for file in payload.keys():
part = MIMEBase('application', "octet-stream")
part.set_payload(base64.decodestring(payload[file]))
part.add_header('Content-Disposition', 'attachment; filename="%s"' % file)
Encoders.encode_base64(part)
msg.attach(part)
except Exception, error:
logger.notifyChannel(_("Power Email"), netsvc.LOG_ERROR, _("Mail from Account %s failed. Probable Reason: MIME Error\nDescription: %s") % (id, error))
return error
try:
#print msg['From'],toadds
serv.sendmail(msg['From'], addresses_l['all'], msg.as_string())
except Exception, error:
logger.notifyChannel(_("Power Email"), netsvc.LOG_ERROR, _("Mail from Account %s failed. Probable Reason: Server Send Error\nDescription: %s") % (id, error))
return error
#The mail sending is complete
serv.close()
logger.notifyChannel(_("Power Email"), netsvc.LOG_INFO, _("Mail from Account %s successfully Sent.") % (id))
return True
else:
logger.notifyChannel(_("Power Email"), netsvc.LOG_ERROR, _("Mail from Account %s failed. Probable Reason: Account not approved") % id)
def extracttime(self, time_as_string):
"""
TODO: DOC THis
"""
logger = netsvc.Logger()
#The standard email dates are of format similar to:
#Thu, 8 Oct 2009 09:35:42 +0200
#print time_as_string
date_as_date = False
convertor = {'+':1, '-':-1}
try:
time_as_string = time_as_string.replace(',', '')
date_list = time_as_string.split(' ')
date_temp_str = ' '.join(date_list[1:5])
if len(date_list) >= 6:
sign = convertor.get(date_list[5][0], False)
else:
sign = False
try:
dt = datetime.datetime.strptime(
date_temp_str,
"%d %b %Y %H:%M:%S")
except:
try:
dt = datetime.datetime.strptime(
date_temp_str,
"%d %b %Y %H:%M")
except:
return False
if sign:
try:
offset = datetime.timedelta(
hours=sign * int(
date_list[5][1:3]
),
minutes=sign * int(
date_list[5][3:5]
)
)
except Exception, e2:
"""Looks like UT or GMT, just forget decoding"""
return False
else:
offset = datetime.timedelta(hours=0)
dt = dt + offset
date_as_date = dt.strftime('%Y-%m-%d %H:%M:%S')
#print date_as_date
except Exception, e:
logger.notifyChannel(
_("Power Email"),
netsvc.LOG_WARNING,
_(
"Datetime Extraction failed. Date: %s\nError: %s") % (
time_as_string,
e)
)
return date_as_date
def save_header(self, cr, uid, mail, coreaccountid, serv_ref, context=None):
"""
TODO:DOC this
"""
if context is None:
context = {}
#Internal function for saving of mail headers to mailbox
#mail: eMail Object
#coreaccounti: ID of poeremail core account
logger = netsvc.Logger()
mail_obj = self.pool.get('poweremail.mailbox')
vals = {
'pem_from':self.decode_header_text(mail['From']),
'pem_to':mail['To'] and self.decode_header_text(mail['To']) or 'no recepient',
'pem_cc':self.decode_header_text(mail['cc']),
'pem_bcc':self.decode_header_text(mail['bcc']),
'pem_recd':mail['date'],
'date_mail':self.extracttime(mail['date']) or time.strftime("%Y-%m-%d %H:%M:%S"),
'pem_subject':self.decode_header_text(mail['subject']),
'server_ref':serv_ref,
'folder':'inbox',
'state':context.get('state', 'unread'),
'pem_body_text':'Mail not downloaded...',
'pem_body_html':'Mail not downloaded...',
'pem_account_id':coreaccountid
}
#Identify Mail Type
if mail.get_content_type() in self._known_content_types:
vals['mail_type'] = mail.get_content_type()
else:
logger.notifyChannel(
_("Power Email"),
netsvc.LOG_WARNING,
_("Saving Header of unknown payload (%s) Account: %s.") % (
mail.get_content_type(),
coreaccountid)
)
#Create mailbox entry in Mail
crid = False
try:
#print vals
crid = mail_obj.create(cr, uid, vals, context)
except Exception, e:
logger.notifyChannel(
_("Power Email"),
netsvc.LOG_ERROR,
_("Save Header -> Mailbox create error. Account: %s, Mail: %s, Error: %s") % (coreaccountid,
serv_ref, str(e)))
#Check if a create was success
if crid:
logger.notifyChannel(
_("Power Email"),
netsvc.LOG_INFO,
_("Header for Mail %s Saved successfully as ID: %s for Account: %s.") % (serv_ref, crid, coreaccountid)
)
crid = False
return True
else:
logger.notifyChannel(
_("Power Email"),
netsvc.LOG_ERROR,
_("IMAP Mail -> Mailbox create error. Account: %s, Mail: %s") % (coreaccountid, serv_ref))
def save_fullmail(self, cr, uid, mail, coreaccountid, serv_ref, context=None):
"""
TODO: Doc this
"""
if context is None:
context = {}
#Internal function for saving of mails to mailbox
#mail: eMail Object
#coreaccounti: ID of poeremail core account
logger = netsvc.Logger()
mail_obj = self.pool.get('poweremail.mailbox')
#TODO:If multipart save attachments and save ids
vals = {
'pem_from':self.decode_header_text(mail['From']),
'pem_to':self.decode_header_text(mail['To']),
'pem_cc':self.decode_header_text(mail['cc']),
'pem_bcc':self.decode_header_text(mail['bcc']),
'pem_recd':mail['date'],
'date_mail':self.extracttime(
mail['date']
) or time.strftime("%Y-%m-%d %H:%M:%S"),
'pem_subject':self.decode_header_text(mail['subject']),
'server_ref':serv_ref,
'folder':'inbox',
'state':context.get('state', 'unread'),
'pem_body_text':'Mail not downloaded...', #TODO:Replace with mail text
'pem_body_html':'Mail not downloaded...', #TODO:Replace
'pem_account_id':coreaccountid
}
parsed_mail = self.get_payloads(mail)
vals['pem_body_text'] = parsed_mail['text']
vals['pem_body_html'] = parsed_mail['html']
#Create the mailbox item now
crid = False
try:
crid = mail_obj.create(cr, uid, vals, context)
except Exception, e:
logger.notifyChannel(
_("Power Email"),
netsvc.LOG_ERROR,
_("Save Header -> Mailbox create error. Account: %s, Mail: %s, Error: %s") % (
coreaccountid,
serv_ref,
str(e))
)
#Check if a create was success
if crid:
logger.notifyChannel(
_("Power Email"),
netsvc.LOG_INFO,
_("Header for Mail %s Saved successfully as ID: %s for Account: %s.") % (serv_ref,
crid,
coreaccountid))
#If there are attachments save them as well
if parsed_mail['attachments']:
self.save_attachments(cr, uid, mail, crid,
parsed_mail, coreaccountid, context)
crid = False
return True
else:
logger.notifyChannel(
_("Power Email"),
netsvc.LOG_ERROR,
_("IMAP Mail -> Mailbox create error. Account: %s, Mail: %s") % (
coreaccountid,
mail[0].split()[0]))
def complete_mail(self, cr, uid, mail, coreaccountid, serv_ref, mailboxref, context=None):
if context is None:
context = {}
#Internal function for saving of mails to mailbox
#mail: eMail Object
#coreaccountid: ID of poeremail core account
#serv_ref:Mail ID in the IMAP/POP server
#mailboxref: ID of record in malbox to complete
logger = netsvc.Logger()
mail_obj = self.pool.get('poweremail.mailbox')
#TODO:If multipart save attachments and save ids
vals = {
'pem_from':self.decode_header_text(mail['From']),
'pem_to':mail['To'] and self.decode_header_text(mail['To']) or 'no recepient',
'pem_cc':self.decode_header_text(mail['cc']),
'pem_bcc':self.decode_header_text(mail['bcc']),
'pem_recd':mail['date'],
'date_mail':time.strftime("%Y-%m-%d %H:%M:%S"),
'pem_subject':self.decode_header_text(mail['subject']),
'server_ref':serv_ref,
'folder':'inbox',
'state':context.get('state', 'unread'),
'pem_body_text':'Mail not downloaded...', #TODO:Replace with mail text
'pem_body_html':'Mail not downloaded...', #TODO:Replace
'pem_account_id':coreaccountid
}
#Identify Mail Type and get payload
parsed_mail = self.get_payloads(mail)
vals['pem_body_text'] = tools.ustr(parsed_mail['text'])
vals['pem_body_html'] = tools.ustr(parsed_mail['html'])
#Create the mailbox item now
crid = False
try:
crid = mail_obj.write(cr, uid, mailboxref, vals, context)
except Exception, e:
logger.notifyChannel(_("Power Email"), netsvc.LOG_ERROR, _("Save Mail -> Mailbox write error Account: %s, Mail: %s") % (coreaccountid, serv_ref))
#Check if a create was success
if crid:
logger.notifyChannel(_("Power Email"), netsvc.LOG_INFO, _("Mail %s Saved successfully as ID: %s for Account: %s.") % (serv_ref, crid, coreaccountid))
#If there are attachments save them as well
if parsed_mail['attachments']:
self.save_attachments(cr, uid, mail, mailboxref, parsed_mail, coreaccountid, context)
return True
else:
logger.notifyChannel(_("Power Email"), netsvc.LOG_ERROR, _("IMAP Mail -> Mailbox create error Account: %s, Mail: %s") % (coreaccountid, mail[0].split()[0]))
def save_attachments(self, cr, uid, mail, id, parsed_mail, coreaccountid, context=None):
logger = netsvc.Logger()
att_obj = self.pool.get('ir.attachment')
mail_obj = self.pool.get('poweremail.mailbox')
att_ids = []
for each in parsed_mail['attachments']:#Get each attachment
new_att_vals = {
'name':self.decode_header_text(mail['subject']) + '(' + each[0] + ')',
'datas':base64.b64encode(each[2] or ''),
'datas_fname':each[1],
'description':(self.decode_header_text(mail['subject']) or _('No Subject')) + " [Type:" + (each[0] or 'Unknown') + ", Filename:" + (each[1] or 'No Name') + "]",
'res_model':'poweremail.mailbox',
'res_id':id
}
att_ids.append(att_obj.create(cr, uid, new_att_vals, context))
logger.notifyChannel(_("Power Email"), netsvc.LOG_INFO, _("Downloaded & saved %s attachments Account: %s.") % (len(att_ids), coreaccountid))
#Now attach the attachment ids to mail
if mail_obj.write(cr, uid, id, {'pem_attachments_ids':[[6, 0, att_ids]]}, context):
logger.notifyChannel(_("Power Email"), netsvc.LOG_INFO, _("Attachment to mail for %s relation success! Account: %s.") % (id, coreaccountid))
else:
logger.notifyChannel(_("Power Email"), netsvc.LOG_ERROR, _("Attachment to mail for %s relation failed Account: %s.") % (id, coreaccountid))
def get_mails(self, cr, uid, ids, context=None):
if context is None:
context = {}
#The function downloads the mails from the POP3 or IMAP server
#The headers/full mail download depends on settings in the account
#IDS should be list of id of poweremail_coreaccounts
logger = netsvc.Logger()
#The Main reception function starts here
for id in ids:
logger.notifyChannel(_("Power Email"), netsvc.LOG_INFO, _("Starting Header reception for account: %s.") % (id))
rec = self.browse(cr, uid, id, context)
if rec:
if rec.iserver and rec.isport and rec.isuser and rec.ispass :
if rec.iserver_type == 'imap' and rec.isfolder:
#Try Connecting to Server
try:
if rec.isssl:
serv = imaplib.IMAP4_SSL(rec.iserver, rec.isport)
else:
serv = imaplib.IMAP4(rec.iserver, rec.isport)
except imaplib.IMAP4.error, error:
logger.notifyChannel(_("Power Email"), netsvc.LOG_ERROR, _("IMAP Server Error Account: %s Error: %s.") % (id, error))
#Try logging in to server
try:
serv.login(rec.isuser, rec.ispass)
except imaplib.IMAP4.error, error:
logger.notifyChannel(_("Power Email"), netsvc.LOG_ERROR, _("IMAP Server Login Error Account: %s Error: %s.") % (id, error))
logger.notifyChannel(_("Power Email"), netsvc.LOG_INFO, _("IMAP Server Connected & logged in successfully Account: %s.") % (id))
#Select IMAP folder
try:
typ, msg_count = serv.select('"%s"' % rec.isfolder)
except imaplib.IMAP4.error, error:
logger.notifyChannel(_("Power Email"), netsvc.LOG_ERROR, _("IMAP Server Folder Selection Error Account: %s Error: %s.") % (id, error))
raise osv.except_osv(_('Power Email'), _('IMAP Server Folder Selection Error Account: %s Error: %s.\nCheck account settings if you have selected a folder.') % (id, error))
logger.notifyChannel(_("Power Email"), netsvc.LOG_INFO, _("IMAP Folder selected successfully Account:%s.") % (id))
logger.notifyChannel(_("Power Email"), netsvc.LOG_INFO, _("IMAP Folder Statistics for Account: %s: %s") % (id, serv.status('"%s"' % rec.isfolder, '(MESSAGES RECENT UIDNEXT UIDVALIDITY UNSEEN)')[1][0]))
#If there are newer mails than the ones in mailbox
#print int(msg_count[0]),rec.last_mail_id
if rec.last_mail_id < int(msg_count[0]):
if rec.rec_headers_den_mail:
#Download Headers Only
for i in range(rec.last_mail_id + 1, int(msg_count[0]) + 1):
typ, msg = serv.fetch(str(i), '(FLAGS BODY.PEEK[HEADER])')
for mails in msg:
if type(mails) == type(('tuple', 'type')):
mail = email.message_from_string(mails[1])
ctx = context.copy()
if '\Seen' in mails[0]:
ctx['state'] = 'read'
if self.save_header(cr, uid, mail, id, mails[0].split()[0], ctx):#If saved succedfully then increment last mail recd
self.write(cr, uid, id, {'last_mail_id':mails[0].split()[0]}, context)
else:#Receive Full Mail first time itself
#Download Full RF822 Mails
for i in range(rec.last_mail_id + 1, int(msg_count[0]) + 1):
typ, msg = serv.fetch(str(i), '(FLAGS RFC822)')
for j in range(0, len(msg) / 2):
mails = msg[j * 2]
flags = msg[(j * 2) + 1]
if type(mails) == type(('tuple', 'type')):
ctx = context.copy()
if '\Seen' in flags:
ctx['state'] = 'read'
mail = email.message_from_string(mails[1])
if self.save_fullmail(cr, uid, mail, id, mails[0].split()[0], ctx):#If saved succedfully then increment last mail recd
self.write(cr, uid, id, {'last_mail_id':mails[0].split()[0]}, context)
serv.close()
serv.logout()
elif rec.iserver_type == 'pop3':
#Try Connecting to Server
try:
if rec.isssl:
serv = poplib.POP3_SSL(rec.iserver, rec.isport)
else:
serv = poplib.POP3(rec.iserver, rec.isport)
except Exception, error:
logger.notifyChannel(_("Power Email"), netsvc.LOG_ERROR, _("POP3 Server Error Account: %s Error: %s.") % (id, error))
#Try logging in to server
try:
serv.user(rec.isuser)
serv.pass_(rec.ispass)
except Exception, error:
logger.notifyChannel(_("Power Email"), netsvc.LOG_ERROR, _("POP3 Server Login Error Account: %s Error: %s.") % (id, error))
logger.notifyChannel(_("Power Email"), netsvc.LOG_INFO, _("POP3 Server Connected & logged in successfully Account: %s.") % (id))
logger.notifyChannel(_("Power Email"), netsvc.LOG_INFO, _("POP3 Statistics: %s mails of %s size for Account: %s") % (serv.stat()[0], serv.stat()[1], id))
#If there are newer mails than the ones in mailbox
if rec.last_mail_id < serv.stat()[0]:
if rec.rec_headers_den_mail:
#Download Headers Only
for msgid in range(rec.last_mail_id + 1, serv.stat()[0] + 1):
resp, msg, octet = serv.top(msgid, 20) #20 Lines from the content
mail = email.message_from_string(string.join(msg, "\n"))
if self.save_header(cr, uid, mail, id, msgid):#If saved succedfully then increment last mail recd
self.write(cr, uid, id, {'last_mail_id':msgid}, context)
else:#Receive Full Mail first time itself
#Download Full RF822 Mails
for msgid in range(rec.last_mail_id + 1, serv.stat()[0] + 1):
resp, msg, octet = serv.retr(msgid) #Full Mail
mail = email.message_from_string(string.join(msg, "\n"))
if self.save_header(cr, uid, mail, id, msgid):#If saved succedfully then increment last mail recd
self.write(cr, uid, id, {'last_mail_id':msgid}, context)
else:
logger.notifyChannel(_("Power Email"), netsvc.LOG_ERROR, _("Incoming server login attempt dropped Account: %s Check if Incoming server attributes are complete.") % (id))
def get_fullmail(self, cr, uid, mailid, context):
#The function downloads the full mail for which only header was downloaded
#ID:of poeremail core account
#context: should have mailboxref, the ID of mailbox record
server_ref = self.pool.get(
'poweremail.mailbox'
).read(cr, uid, mailid,
['server_ref'],
context)['server_ref']
id = self.pool.get(
'poweremail.mailbox'
).read(cr, uid, mailid,
['pem_account_id'],
context)['pem_account_id'][0]
logger = netsvc.Logger()
#The Main reception function starts here
logger.notifyChannel(
_("Power Email"),
netsvc.LOG_INFO,
_("Starting Full mail reception for mail: %s.") % (id))
rec = self.browse(cr, uid, id, context)
if rec:
if rec.iserver and rec.isport and rec.isuser and rec.ispass :
if rec.iserver_type == 'imap' and rec.isfolder:
#Try Connecting to Server
try:
if rec.isssl:
serv = imaplib.IMAP4_SSL(
rec.iserver,
rec.isport
)
else:
serv = imaplib.IMAP4(
rec.iserver,
rec.isport
)
except imaplib.IMAP4.error, error:
logger.notifyChannel(
_("Power Email"),
netsvc.LOG_ERROR,
_(
"IMAP Server Error Account: %s Error: %s."
) % (id, error))
#Try logging in to server
try:
serv.login(rec.isuser, rec.ispass)
except imaplib.IMAP4.error, error:
logger.notifyChannel(
_("Power Email"),
netsvc.LOG_ERROR,
_(
"IMAP Server Login Error Account:%s Error: %s."
) % (id, error))
logger.notifyChannel(
_("Power Email"),
netsvc.LOG_INFO,
_(
"IMAP Server Connected & logged in successfully Account: %s."
) % (id))
#Select IMAP folder
try:
typ, msg_count = serv.select('"%s"' % rec.isfolder)#typ,msg_count: practically not used here
except imaplib.IMAP4.error, error:
logger.notifyChannel(
_("Power Email"),
netsvc.LOG_ERROR,
_(
"IMAP Server Folder Selection Error. Account: %s Error: %s."
) % (id, error))
logger.notifyChannel(
_("Power Email"),
netsvc.LOG_INFO,
_(
"IMAP Folder selected successfully Account: %s."
) % (id))
logger.notifyChannel(
_("Power Email"),
netsvc.LOG_INFO,
_(
"IMAP Folder Statistics for Account: %s: %s"
) % (
id,
serv.status(
'"%s"' % rec.isfolder,
'(MESSAGES RECENT UIDNEXT UIDVALIDITY UNSEEN)'
)[1][0])
)
#If there are newer mails than the ones in mailbox
typ, msg = serv.fetch(str(server_ref), '(FLAGS RFC822)')
for i in range(0, len(msg) / 2):
mails = msg[i * 2]
flags = msg[(i * 2) + 1]
if type(mails) == type(('tuple', 'type')):
if '\Seen' in flags:
context['state'] = 'read'
mail = email.message_from_string(mails[1])
self.complete_mail(cr, uid, mail, id,
server_ref, mailid, context)
serv.close()
serv.logout()
elif rec.iserver_type == 'pop3':