[IMP]: refactored send_email() of ir.mail_server

bzr revid: rha@tinyerp.com-20110330100050-aiuhkmb8je2w1p5b
This commit is contained in:
Rifakat Haradwala (Open ERP) 2011-03-30 15:30:50 +05:30
parent edd149d32d
commit 899815c3cd
2 changed files with 96 additions and 53 deletions

View File

@ -227,7 +227,7 @@ unless it is already specified in the From Email, e.g: John Doe <john@doe.com>",
""" """
return "<%s-openobject-%s@%s>" % (time.time(), openobject_id, socket.gethostname()) return "<%s-openobject-%s@%s>" % (time.time(), openobject_id, socket.gethostname())
def send_email(self, cr, uid, smtp_from, email_to, subject, body, email_cc=None, def send_email(self, cr, uid, smtp_from, email_to, message=None, subject=None, body=None, email_cc=None,
email_bcc=None, reply_to=False, attach=None, message_id=None, email_bcc=None, reply_to=False, attach=None, message_id=None,
references=None, openobject_id=False, debug=False, subtype='plain', references=None, openobject_id=False, debug=False, subtype='plain',
x_headers=None, priority='3', smtp_server=None, smtp_port=None, x_headers=None, priority='3', smtp_server=None, smtp_port=None,
@ -266,66 +266,107 @@ unless it is already specified in the From Email, e.g: John Doe <john@doe.com>",
smtp_port = smtp_port smtp_port = smtp_port
ssl = ssl ssl = ssl
if not email_cc: email_cc = [] class WriteToLogger(object):
if not email_bcc: email_bcc = [] def __init__(self):
if not body: body = u'' self.logger = loglevels.Logger()
email_body = ustr(body).encode('utf-8')
email_text = MIMEText(email_body or '', _subtype=subtype, _charset='utf-8')
msg = MIMEMultipart()
if not message_id and openobject_id: def write(self, s):
message_id = self.generate_tracking_message_id(openobject_id) self.logger.notifyChannel('email_send', loglevels.LOG_DEBUG, s)
else:
message_id = Utils.make_msgid()
msg['Message-Id'] = message_id #preparing the message
if references: if not message:
msg['references'] = references if not email_cc: email_cc = []
msg['Subject'] = Header(ustr(subject), 'utf-8') if not email_bcc: email_bcc = []
msg['From'] = smtp_from if not body: body = u''
email_body = ustr(body).encode('utf-8')
email_text = MIMEText(email_body or '', _subtype=subtype, _charset='utf-8')
msg = MIMEMultipart()
del msg['Reply-To'] if not message_id and openobject_id:
if reply_to: message_id = self.generate_tracking_message_id(openobject_id)
msg['Reply-To'] = reply_to else:
else: message_id = Utils.make_msgid()
msg['Reply-To'] = msg['From']
msg['To'] = COMMASPACE.join(email_to) msg['Message-Id'] = message_id
if references:
msg['references'] = references
msg['Subject'] = Header(ustr(subject), 'utf-8')
msg['From'] = smtp_from
if email_cc: del msg['Reply-To']
msg['Cc'] = COMMASPACE.join(email_cc) if reply_to:
if email_bcc: msg['Reply-To'] = reply_to
msg['Bcc'] = COMMASPACE.join(email_bcc) else:
msg['Reply-To'] = msg['From']
msg['X-Priority'] = priorities.get(priority, '3 (Normal)') msg['To'] = COMMASPACE.join(email_to)
msg['Date'] = formatdate(localtime=True)
# Add dynamic X Header if email_cc:
for key, value in x_headers.iteritems(): msg['Cc'] = COMMASPACE.join(email_cc)
msg['%s' % key] = str(value) if email_bcc:
if html2text and sub_type == 'html': msg['Bcc'] = COMMASPACE.join(email_bcc)
text = html2text(email_body.decode('utf-8')).encode('utf-8')
alternative_part = MIMEMultipart(_subtype="alternative")
alternative_part.attach(MIMEText(text, _charset='utf-8', _subtype='plain'))
alternative_part.attach(email_text)
msg.attach(alternative_part)
else:
msg.attach(email_text)
if attach: msg['X-Priority'] = priorities.get(priority, '3 (Normal)')
for (fname, fcontent) in attach: msg['Date'] = formatdate(localtime=True)
part = MIMEBase('application', "octet-stream")
part.set_payload( fcontent ) # Add dynamic X Header
Encoders.encode_base64(part) for key, value in x_headers.iteritems():
part.add_header('Content-Disposition', 'attachment; filename="%s"' % (fname,)) msg['%s' % key] = str(value)
msg.attach(part) if html2text and sub_type == 'html':
text = html2text(email_body.decode('utf-8')).encode('utf-8')
alternative_part = MIMEMultipart(_subtype="alternative")
alternative_part.attach(MIMEText(text, _charset='utf-8', _subtype='plain'))
alternative_part.attach(email_text)
msg.attach(alternative_part)
else:
msg.attach(email_text)
if attach:
for (fname, fcontent) in attach:
part = MIMEBase('application', "octet-stream")
part.set_payload( fcontent )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % (fname,))
msg.attach(part)
message = msg
try:
smtp_server = smtp_server or config['smtp_server']
if smtp_server.startswith('maildir:/'):
from mailbox import Maildir
maildir_path = smtp_server[8:]
mdir = Maildir(maildir_path,factory=None, create = True)
mdir.add(message.as_string(True))
return True
if debug:
oldstderr = smtplib.stderr
smtplib.stderr = WriteToLogger()
if not ssl:
ssl = config.get('smtp_ssl', False)
smtp = self.connect_smtp_server(cr, uid, smtp_server, smtp_port,
user_name=smtp_user, user_password=smtp_password, ssl=ssl, tls=True, debug=debug)
try:
smtp.sendmail(smtp_from, smtp_to_list, message.as_string())
except Exception:
_logger.error('could not deliver Email(s)', exc_info=True)
return False
finally:
try:
smtp.quit()
except Exception:
# ignored, just a consequence of the previous exception
pass
if debug:
smtplib.stderr = oldstderr
except Exception:
_logger.error('Error on Send Emails Services', exc_info=True)
res = self._email_send(cr, uid, smtp_from, tools.flatten([email_to, email_cc, email_bcc]),
msg, ssl=ssl, debug=debug, smtp_server=smtp_server, smtp_user=smtp_user,
smtp_password=smtp_password, smtp_port=smtp_port)
if res:
return message_id return message_id
return False
def on_change_ssl(self, cr, uid, ids, smtp_ssl): def on_change_ssl(self, cr, uid, ids, smtp_ssl):
smtp_port = 0 smtp_port = 0

View File

@ -413,14 +413,16 @@ def html2plaintext(html, body_id=None, encoding='utf-8'):
return html return html
def email_send(uid, smtp_from, smtp_to_list, message, ssl=False, debug=False, smtp_server=None, smtp_port=None, def email_send(smtp_from, smtp_to_list, message, ssl=False, debug=False, smtp_server=None, smtp_port=None,
smtp_user=None, smtp_password=None, cr=None): smtp_user=None, smtp_password=None, cr=None, uid=None):
if not cr: if not cr:
db_name = getattr(threading.currentThread(), 'dbname', None) db_name = getattr(threading.currentThread(), 'dbname', None)
if db_name: if db_name:
cr = pooler.get_db_only(db_name).cursor() cr = pooler.get_db_only(db_name).cursor()
else: else:
raise Exception("No database cursor found!") raise Exception("No database cursor found!")
if not uid:
uid = 1
try: try:
server_pool = pooler.get_pool(cr.dbname).get('ir.mail_server') server_pool = pooler.get_pool(cr.dbname).get('ir.mail_server')
server_pool.send_email(cr, uid, smtp_from, smtp_to_list, message, server_pool.send_email(cr, uid, smtp_from, smtp_to_list, message,