[IMP] ir_mail_server.py: corrected argument of send_method and did related changes and also removed unused imports

bzr revid: rha@tinyerp.com-20110329115309-q7q02pto691a9nxp
This commit is contained in:
Rifakat Haradwala (Open ERP) 2011-03-29 17:23:09 +05:30
parent e3c85bedf0
commit 573431a8ba
6 changed files with 88 additions and 83 deletions

View File

@ -2014,7 +2014,5 @@
<field name="search_view_id" ref="view_ir_mail_server_search"/> <field name="search_view_id" ref="view_ir_mail_server_search"/>
</record> </record>
<menuitem name="Email Accounts" id="menu_email_smtp_server_all" parent="base.menu_config" action="action_ir_mail_server_tree_all" sequence="15"/>
</data> </data>
</openerp> </openerp>

View File

@ -162,7 +162,7 @@ class act_window(osv.osv):
def _invalid_model_msg(self, cr, uid, ids, context=None): def _invalid_model_msg(self, cr, uid, ids, context=None):
return _('Invalid model name in the action definition.') return _('Invalid model name in the action definition.')
_constraints = [ _constraints = [
(_check_model, _invalid_model_msg, ['res_model','src_model']) (_check_model, _invalid_model_msg, ['res_model','src_model'])
] ]
@ -195,7 +195,7 @@ class act_window(osv.osv):
if act.search_view_id: if act.search_view_id:
search_view_id = act.search_view_id.id search_view_id = act.search_view_id.id
else: else:
res_view = self.pool.get('ir.ui.view').search(cr, uid, res_view = self.pool.get('ir.ui.view').search(cr, uid,
[('model','=',act.res_model),('type','=','search'), [('model','=',act.res_model),('type','=','search'),
('inherit_id','=',False)], context=context) ('inherit_id','=',False)], context=context)
if res_view: if res_view:
@ -631,7 +631,8 @@ class actions_server(osv.osv):
subject = self.merge_message(cr, uid, action.subject, action, context) subject = self.merge_message(cr, uid, action.subject, action, context)
body = self.merge_message(cr, uid, action.message, action, context) body = self.merge_message(cr, uid, action.message, action, context)
if tools.email_send(user, [address], subject, body, debug=False, subtype='html') == True: smtp_server_obj = self.pool.get('ir.mail_server')
if smtp_server_obj.send_email(uid, user, [address], subject, body, debug=False, subtype='html', cr=cr) == True:
logger.info('Email successfully sent to: %s', address) logger.info('Email successfully sent to: %s', address)
else: else:
logger.warning('Failed to send email to: %s', address) logger.warning('Failed to send email to: %s', address)

View File

@ -28,19 +28,12 @@ from tools import config
import netsvc import netsvc
import base64 import base64
import inspect
import subprocess import subprocess
import logging import logging
import os
import re
import smtplib import smtplib
import socket import socket
import sys import sys
import threading
import time import time
import warnings
import zipfile
from datetime import datetime
from email.MIMEText import MIMEText from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase from email.MIMEBase import MIMEBase
from email.MIMEMultipart import MIMEMultipart from email.MIMEMultipart import MIMEMultipart
@ -48,12 +41,6 @@ from email.Header import Header
from email.Utils import formatdate, COMMASPACE from email.Utils import formatdate, COMMASPACE
from email import Utils from email import Utils
from email import Encoders from email import Encoders
from itertools import islice, izip
from lxml import etree
if sys.version_info[:2] < (2, 4):
from threadinglocal import local
else:
from threading import local
try: try:
from html2text import html2text from html2text import html2text
except ImportError: except ImportError:
@ -63,17 +50,19 @@ import openerp.loglevels as loglevels
from tools import config from tools import config
from email.generator import Generator from email.generator import Generator
# get_encodings, ustr and exception_to_unicode were originally from tools.misc. # get_encodings, ustr and exception_to_unicode were originally from tools.misc.
# There are moved to loglevels until we refactor tools. # There are moved to loglevels until we refactor tools.
from openerp.loglevels import get_encodings, ustr, exception_to_unicode from openerp.loglevels import get_encodings, ustr, exception_to_unicode
_logger = logging.getLogger('tools') _logger = logging.getLogger('tools')
# List of etree._Element subclasses that we choose to ignore when parsing XML. priorities = {
# We include the *Base ones just in case, currently they seem to be subclasses of the _* ones. '1': '1 (Highest)',
SKIPPED_ELEMENT_TYPES = (etree._Comment, etree._ProcessingInstruction, etree.CommentBase, etree.PIBase) '2': '2 (High)',
'3': '3 (Normal)',
'4': '4 (Low)',
'5': '5 (Lowest)',
}
class ir_mail_server(osv.osv): class ir_mail_server(osv.osv):
""" """
@ -103,7 +92,8 @@ unless it is already specified in the From Email, e.g: John Doe <john@doe.com>",
required=False), required=False),
'smtp_tls':fields.boolean('TLS'), 'smtp_tls':fields.boolean('TLS'),
'smtp_ssl':fields.boolean('SSL/TLS'), 'smtp_ssl':fields.boolean('SSL/TLS'),
'priority': fields.integer('Priority', help="If no specific server is requested for a mail then the highest priority one is used"), 'priority': fields.integer('Priority', help="If no specific server is \
requested for a mail then the highest priority one is used"),
} }
_defaults = { _defaults = {
@ -124,8 +114,10 @@ unless it is already specified in the From Email, e.g: John Doe <john@doe.com>",
""" """
try: try:
for smtp_server in self.browse(cr, uid, ids, context=context): for smtp_server in self.browse(cr, uid, ids, context=context):
smtp = self.connect_smtp_server(cr, uid, smtp_server.smtp_host, smtp_server.smtp_port, user_name=smtp_server.smtp_user, smtp = self.connect_smtp_server(cr, uid, smtp_server.smtp_host,
user_password=smtp_server.smtp_pass, ssl=smtp_server.smtp_ssl, tls=smtp_server.smtp_tls, debug=False) smtp_server.smtp_port, user_name=smtp_server.smtp_user,
user_password=smtp_server.smtp_pass, ssl=smtp_server.smtp_ssl,
tls=smtp_server.smtp_tls, debug=False)
try: try:
smtp.quit() smtp.quit()
except Exception: except Exception:
@ -139,7 +131,8 @@ unless it is already specified in the From Email, e.g: John Doe <john@doe.com>",
raise osv.except_osv(_("SMTP Connection: Test Successfully!"), '') raise osv.except_osv(_("SMTP Connection: Test Successfully!"), '')
def connect_smtp_server(self, cr, uid, server_host, server_port, user_name=None, user_password=None, ssl=False, tls=False, debug=False): def connect_smtp_server(self, cr, uid, server_host, server_port, user_name=None,
user_password=None, ssl=False, tls=False, debug=False):
""" """
Connect SMTP Server and returned the (SMTP) object Connect SMTP Server and returned the (SMTP) object
""" """
@ -170,8 +163,8 @@ unless it is already specified in the From Email, e.g: John Doe <john@doe.com>",
raise error raise error
return smtp_server return smtp_server
def _email_send(self, cr, uid, smtp_from, smtp_to_list, message, ssl=False, debug=False, def _email_send(self, cr, uid, smtp_from, smtp_to_list, message, ssl=False,
smtp_server=None, smtp_port=None, smtp_user=None, smtp_password=None): debug=False, smtp_server=None, smtp_port=None, smtp_user=None, smtp_password=None):
"""Low-level method to send directly a Message through the configured smtp server. """Low-level method to send directly a Message through the configured smtp server.
:param smtp_from: RFC-822 envelope FROM (not displayed to recipient) :param smtp_from: RFC-822 envelope FROM (not displayed to recipient)
:param smtp_to_list: RFC-822 envelope RCPT_TOs (not displayed to recipient) :param smtp_to_list: RFC-822 envelope RCPT_TOs (not displayed to recipient)
@ -205,7 +198,8 @@ unless it is already specified in the From Email, e.g: John Doe <john@doe.com>",
if not ssl: if not ssl:
ssl = config.get('smtp_ssl', False) 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) 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: try:
smtp.sendmail(smtp_from, smtp_to_list, message.as_string()) smtp.sendmail(smtp_from, smtp_to_list, message.as_string())
except Exception: except Exception:
@ -233,11 +227,16 @@ 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, smtp_to_list, message, id=None, subject=None, ssl=False, def send_email(self, cr, uid, smtp_from, email_to, subject, body, email_cc=None,
debug=False, smtp_server=None, smtp_port=None, smtp_user=None, smtp_password=None): email_bcc=None, reply_to=False, attach=None, message_id=None,
references=None, openobject_id=False, debug=False, subtype='plain',
x_headers=None, priority='3', smtp_server=None, smtp_port=None,
ssl=False, smtp_user=None, smtp_password=None, id=None):
"""Send an email. """Send an email.
""" """
if x_headers is None:
x_headers = {}
if not (smtp_from or config['email_from']): if not (smtp_from or config['email_from']):
raise ValueError("Sending an email requires either providing a sender " raise ValueError("Sending an email requires either providing a sender "
@ -246,48 +245,65 @@ unless it is already specified in the From Email, e.g: John Doe <john@doe.com>",
smtp_from = ustr(smtp_from).encode('utf-8') smtp_from = ustr(smtp_from).encode('utf-8')
if id: if id:
smtp_server = self.browse(cr, uid, id) server = self.browse(cr, uid, id)
if not (id and smtp_server): smtp_server = server.smtp_host
server = self.search(cr, uid, [], order='priority', limit=1) smtp_user = server.smtp_user
smtp_server = self.browse(cr, uid, server[0]) smtp_password = server.smtp_pass
if not id and smtp_server: smtp_port = server.smtp_port
ssl = server.smtp_ssl
elif not (id and smtp_server):
server_ids = self.search(cr, uid, [], order='priority', limit=1)
server = self.browse(cr, uid, server_ids[0])
smtp_server = server.smtp_host
smtp_user = server.smtp_user
smtp_password = server.smtp_pass
smtp_port = server.smtp_port
ssl = server.smtp_ssl
elif not id and smtp_server:
smtp_server = smtp_server smtp_server = smtp_server
smtp_user = smtp_user
smtp_password = smtp_password
smtp_port = smtp_port
ssl = ssl
email_body = ustr(message.body or '').encode('utf-8') if not email_cc: email_cc = []
email_text = MIMEText(email_body or '',_charset='utf-8') if not email_bcc: email_bcc = []
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() msg = MIMEMultipart()
openobject_id = message.res_id if not message_id and openobject_id:
if not message.message_id and openobject_id:
message_id = self.generate_tracking_message_id(openobject_id) message_id = self.generate_tracking_message_id(openobject_id)
else: else:
message_id = Utils.make_msgid() message_id = Utils.make_msgid()
msg['Message-Id'] = message_id msg['Message-Id'] = message_id
if references:
if message.references: msg['references'] = references
msg['references'] = message.references msg['Subject'] = Header(ustr(subject), 'utf-8')
if subject:
msg['Subject'] = Header(ustr(subject), 'utf-8')
msg['From'] = smtp_from msg['From'] = smtp_from
msg['To'] = smtp_to_list
del msg['Reply-To'] del msg['Reply-To']
if message.reply_to: if reply_to:
msg['Reply-To'] = message.reply_to msg['Reply-To'] = reply_to
else: else:
msg['Reply-To'] = msg['From'] msg['Reply-To'] = msg['From']
msg['Cc'] = message.email_cc or []
msg['Bcc'] = message.email_bcc or [] msg['To'] = COMMASPACE.join(email_to)
#msg['X-Priority'] = message.priority
if email_cc:
msg['Cc'] = COMMASPACE.join(email_cc)
if email_bcc:
msg['Bcc'] = COMMASPACE.join(email_bcc)
msg['X-Priority'] = priorities.get(priority, '3 (Normal)')
msg['Date'] = formatdate(localtime=True) msg['Date'] = formatdate(localtime=True)
# Add dynamic X Header # Add dynamic X Header
if message.headers: for key, value in x_headers.iteritems():
x_headers = message.headers msg['%s' % key] = str(value)
for key, value in x_headers.iteritems(): if html2text and sub_type == 'html':
msg['%s' % key] = str(value)
if html2text and message.sub_type == 'html':
text = html2text(email_body.decode('utf-8')).encode('utf-8') text = html2text(email_body.decode('utf-8')).encode('utf-8')
alternative_part = MIMEMultipart(_subtype="alternative") alternative_part = MIMEMultipart(_subtype="alternative")
alternative_part.attach(MIMEText(text, _charset='utf-8', _subtype='plain')) alternative_part.attach(MIMEText(text, _charset='utf-8', _subtype='plain'))
@ -296,19 +312,17 @@ unless it is already specified in the From Email, e.g: John Doe <john@doe.com>",
else: else:
msg.attach(email_text) msg.attach(email_text)
attachments = [] if attach:
for attach in message.attachment_ids: for (fname, fcontent) in attach:
attachments.append((attach.datas_fname, base64.b64decode(attach.datas)))
if attachments:
for (fname,fcontent) in attachments:
part = MIMEBase('application', "octet-stream") part = MIMEBase('application', "octet-stream")
part.set_payload( fcontent ) part.set_payload( fcontent )
Encoders.encode_base64(part) Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % (fname,)) part.add_header('Content-Disposition', 'attachment; filename="%s"' % (fname,))
msg.attach(part) msg.attach(part)
res = self._email_send(cr, uid, smtp_from, smtp_to_list, msg, smtp_server=smtp_server.smtp_host, res = self._email_send(cr, uid, smtp_from, tools.flatten([email_to, email_cc, email_bcc]),
smtp_user=smtp_server.smtp_user, smtp_password=smtp_server.smtp_pass, smtp_port=smtp_server.smtp_port, debug=message.debug) msg, ssl=ssl, debug=debug, smtp_server=smtp_server, smtp_user=smtp_user,
smtp_password=smtp_password, smtp_port=smtp_port)
if res: if res:
return message_id return message_id
return False return False
@ -317,13 +331,13 @@ unless it is already specified in the From Email, e.g: John Doe <john@doe.com>",
smtp_port = 0 smtp_port = 0
if smtp_ssl: if smtp_ssl:
smtp_port = 465 smtp_port = 465
return {'value':{'smtp_ssl':smtp_ssl,'smtp_tls':False,'smtp_port':smtp_port}} return {'value': {'smtp_ssl':smtp_ssl, 'smtp_tls':False, 'smtp_port':smtp_port}}
def on_change_tls(self, cr, uid, ids, smtp_tls): def on_change_tls(self, cr, uid, ids, smtp_tls):
smtp_port = 0 smtp_port = 0
if smtp_tls: if smtp_tls:
smtp_port = 0 smtp_port = 0
return {'value':{'smtp_tls':smtp_tls,'smtp_ssl':False,'smtp_port':smtp_port}} return {'value': {'smtp_tls':smtp_tls, 'smtp_ssl':False, 'smtp_port':smtp_port}}
ir_mail_server() ir_mail_server()

View File

@ -74,5 +74,6 @@
</record> </record>
<menuitem id="next_id_15" name="Parameters" parent="base.menu_config" groups="base.group_extended" /> <menuitem id="next_id_15" name="Parameters" parent="base.menu_config" groups="base.group_extended" />
<menuitem action="ir_property_form" id="menu_ir_property_form_all" parent="base.next_id_15"/> <menuitem action="ir_property_form" id="menu_ir_property_form_all" parent="base.next_id_15"/>
<menuitem name="Email Accounts" id="menu_email_smtp_server_all" parent="base.next_id_15" action="base.action_ir_mail_server_tree_all" sequence="15"/>
</data> </data>
</openerp> </openerp>

View File

@ -62,12 +62,11 @@ class partner_wizard_spam(osv.osv_memory):
to = '"%s" <%s>' % (name, adr.email) to = '"%s" <%s>' % (name, adr.email)
#TODO: add some tests to check for invalid email addresses #TODO: add some tests to check for invalid email addresses
#CHECKME: maybe we should use res.partner/email_send #CHECKME: maybe we should use res.partner/email_send
tools.email_send(data.email_from, smtp_server_obj = self.pool.get('ir.mail_server')
[to], smtp_server_obj.send_email(uid, data.email_from,
data.subject, [to], data.subject,
data.text, data.text, subtype=type_,
subtype=type_, cr=cr)
openobject_id="res.partner-%s"%partner.id)
nbr += 1 nbr += 1
event_pool.create(cr, uid, event_pool.create(cr, uid,
{'name': 'Email(s) sent through mass mailing', {'name': 'Email(s) sent through mass mailing',

View File

@ -347,14 +347,6 @@ res_re = re.compile(r"\[([0-9]+)\]", re.UNICODE)
command_re = re.compile("^Set-([a-z]+) *: *(.+)$", re.I + re.UNICODE) command_re = re.compile("^Set-([a-z]+) *: *(.+)$", re.I + re.UNICODE)
reference_re = re.compile("<.*-openobject-(\\d+)@(.*)>", re.UNICODE) reference_re = re.compile("<.*-openobject-(\\d+)@(.*)>", re.UNICODE)
priorities = {
'1': '1 (Highest)',
'2': '2 (High)',
'3': '3 (Normal)',
'4': '4 (Low)',
'5': '5 (Lowest)',
}
def html2plaintext(html, body_id=None, encoding='utf-8'): def html2plaintext(html, body_id=None, encoding='utf-8'):
## (c) Fry-IT, www.fry-it.com, 2007 ## (c) Fry-IT, www.fry-it.com, 2007
## <peter@fry-it.com> ## <peter@fry-it.com>
@ -421,7 +413,7 @@ def html2plaintext(html, body_id=None, encoding='utf-8'):
return html return html
def email_send(smtp_from, smtp_to_list, message, ssl=False, debug=False, smtp_server=None, smtp_port=None, def email_send(uid, 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):
if not cr: if not cr:
db_name = getattr(threading.currentThread(), 'dbname', None) db_name = getattr(threading.currentThread(), 'dbname', None)