def default_get(self, cr, uid, fields, context=None): res = {} if context is None: context = {} res = super(create_voucher, self).default_get(cr, uid, fields, context=context) if not context.get('active_ids', []): return res partner_list, amount = [], 0.0 invoice_obj = self.pool.get('account.invoice') for invoice_brw in invoice_obj.browse(cr, uid, context.get('active_ids', [])): partner_list.append(invoice_brw.partner_id.id) if invoice_brw.type == 'in_invoice': raise osv.except_osv( _('Payment Warning!!'), _('You can only generate Payment for the Customer Invoices!' )) if invoice_brw.state != 'open': raise osv.except_osv( _('Payment Warning!!'), _('You can only generate Payment for open invoices only!')) amount += invoice_brw.residual or 0.0 if 'amount' in fields: res.update(amount=amount) partner_list = list(set(flatten(partner_list))) if len(partner_list) > 1: raise osv.except_osv( _('Payment Warning!!'), _('You can only generate Payment for one Customer at one time!' )) return res
def to_sql(self): stack = [] params = [] # Process the domain from right to left, using a stack, to generate a SQL expression. for i, e in reverse_enumerate(self.__exp): if is_leaf(e, internal=True): table = self.__field_tables.get(i, self.__main_table) q, p = self.__leaf_to_sql(e, table) params.insert(0, p) stack.append(q) elif e == NOT_OPERATOR: stack.append('(NOT (%s))' % (stack.pop(), )) else: ops = {AND_OPERATOR: ' AND ', OR_OPERATOR: ' OR '} q1 = stack.pop() q2 = stack.pop() stack.append('(%s %s %s)' % ( q1, ops[e], q2, )) assert len(stack) == 1 query = stack[0] joins = ' AND '.join(self.__joins) if joins: query = '(%s) AND %s' % (joins, query) return (query, flatten(params))
def create_time_slots(day): src_slots = dcal.get_working_times(day) slots = [0, src_slots, 24 * 60] slots = tuple(tools.flatten(slots)) slots = zip(slots[:-1], slots[1:]) #balance non working slots work_time = slot_sum(src_slots) non_work_time = sum_time - work_time non_slots = filter(lambda s: s not in src_slots, slots) non_slots = map(lambda s: (s[1] - s[0], s), non_slots) non_slots.sort() slots = [] i = 0 for l, s in non_slots: delta = non_work_time / (len(non_slots) - i) delta = min(l, delta) non_work_time -= delta slots.append((s[0], s[0] + delta)) i += 1 slots.extend(src_slots) slots.sort() return slots
def create_time_slots(day): src_slots = dcal.get_working_times(day) slots = [0, src_slots, 24*60] slots = tuple(tools.flatten(slots)) slots = zip(slots[:-1], slots[1:]) #balance non working slots work_time = slot_sum(src_slots) non_work_time = sum_time - work_time non_slots = filter(lambda s: s not in src_slots, slots) non_slots = map(lambda s: (s[1] - s[0], s), non_slots) non_slots.sort() slots = [] i = 0 for l, s in non_slots: delta = non_work_time / (len(non_slots) - i) delta = min(l, delta) non_work_time -= delta slots.append((s[0], s[0] + delta)) i += 1 slots.extend(src_slots) slots.sort() return slots
def to_sql(self): stack = [] params = [] # Process the domain from right to left, using a stack, to generate a # SQL expression. self.result.reverse() for leaf in self.result: if leaf.is_leaf(internal=True): q, p = self.__leaf_to_sql(leaf) params.insert(0, p) stack.append(q) elif leaf.leaf == NOT_OPERATOR: stack.append('(NOT (%s))' % (stack.pop(),)) else: ops = {AND_OPERATOR: ' AND ', OR_OPERATOR: ' OR '} q1 = stack.pop() if len(stack) == 0: print "--------------------------" for leaf in self.result: print leaf.leaf q2 = stack.pop() stack.append('(%s %s %s)' % (q1, ops[leaf.leaf], q2,)) if len(stack) != 1: print "--------------------------" for leaf in self.result: print leaf.leaf, leaf.model assert len(stack) == 1 query = stack[0] joins = ' AND '.join(self.joins) if joins: query = '(%s) AND %s' % (joins, query) return query, tools.flatten(params)
def to_ids(value, field_obj): """Normalize a single id or name, or a list of those, into a list of ids""" names = [] if isinstance(value, basestring): names = [value] if value and isinstance(value, (tuple, list)) and isinstance(value[0], basestring): names = value if names: return flatten([[x[0] for x in field_obj.name_search(cr, uid, n, [], 'ilike', context=context, limit=None)] \ for n in names]) elif isinstance(value, (int, long)): return [value] return list(value)
def _procure_orderpoint_confirm(self, use_new_cursor=False, company_id=False): """ Create procurement based on Orderpoint :param bool use_new_cursor: if set, use a dedicated cursor and auto-commit after processing each procurement. This is appropriate for batch jobs only. """ orderpoint_env = self.env['stock.warehouse.orderpoint'] dom = company_id and [('company_id', '=', company_id)] or [] if self.env.context.get('compute_product_ids') and not self.env.context.get('compute_all_products'): dom += [('product_id', 'in', self.env.context.get('compute_product_ids'))] if self.env.context.get('compute_supplier_ids') and not self.env.context.get('compute_all_products'): supplierinfo_ids = self.env['product.supplierinfo']. \ search([('name', 'in', self.env.context['compute_supplier_ids'])]) read_supplierinfos = supplierinfo_ids.read(['id', 'product_tmpl_id'], load=False) dom += [('product_id.product_tmpl_id', 'in', [item['product_tmpl_id'] for item in read_supplierinfos])] orderpoint_ids = orderpoint_env.search(dom) op_ids = orderpoint_ids.read(['id', 'product_id'], load=False) result = dict() for row in op_ids: if row['product_id'] not in result: result[row['product_id']] = list() result[row['product_id']].append(row['id']) product_ids = result.values() while product_ids: products = product_ids[:ORDERPOINT_CHUNK] product_ids = product_ids[ORDERPOINT_CHUNK:] orderpoints = flatten(products) if self.env.context.get('without_job'): for op in self.env['stock.warehouse.orderpoint'].browse(orderpoints): op.process() else: process_orderpoints.delay(ConnectorSession.from_env(self.env), 'stock.warehouse.orderpoint', orderpoints, self.env.context, description="Computing orderpoints %s" % orderpoints) return {}
def to_sql(self): stack = [] params = [] for i, e in reverse_enumerate(self.__exp): if self._is_leaf(e, internal=True): table = self.__field_tables.get(i, self.__main_table) q, p = self.__leaf_to_sql(e, table) params.insert(0, p) stack.append(q) else: if e == NOT_OPERATOR: stack.append('(NOT (%s))' % (stack.pop(),)) else: ops = {AND_OPERATOR: ' AND ', OR_OPERATOR: ' OR '} q1 = stack.pop() q2 = stack.pop() stack.append('(%s %s %s)' % (q1, ops[e], q2,)) query = ' AND '.join(reversed(stack)) joins = ' AND '.join(self.__joins) if joins: query = '(%s) AND (%s)' % (joins, query) return (query, flatten(params))
def to_sql(self): stack = [] params = [] # Process the domain from right to left, using a stack, to generate a SQL expression. for i, e in reverse_enumerate(self.__exp): if is_leaf(e, internal=True): table = self.__field_tables.get(i, self.__main_table) q, p = self.__leaf_to_sql(e, table) params.insert(0, p) stack.append(q) elif e == NOT_OPERATOR: stack.append('(NOT (%s))' % (stack.pop(),)) else: ops = {AND_OPERATOR: ' AND ', OR_OPERATOR: ' OR '} q1 = stack.pop() q2 = stack.pop() stack.append('(%s %s %s)' % (q1, ops[e], q2,)) assert len(stack) == 1 query = stack[0] joins = ' AND '.join(self.__joins) if joins: query = '(%s) AND %s' % (joins, query) return (query, flatten(params))
def create_invoice_voucher(self, cr, uid, ids, context=None): ''' Function to create vouchers for selected customer Invoices ''' if context is None: context = {} cust_inv, voucher_ids, check_count = {}, [], 0 # wf_service = netsvc.LocalService("workflow") invoice_obj = self.pool.get('account.invoice') account_voucher = self.pool.get('account.voucher') move_obj = self.pool.get('account.move.line') customer_grouped, customer_invoice_grouped = [], [] for payment_obj in self.browse(cr, uid, ids): journal = payment_obj.journal_id company_id = payment_obj.company_id.id or false context.update({'company_id': company_id}) for invoice in invoice_obj.browse(cr, uid, context.get('active_ids', [])): partner_id = self.pool.get( 'res.partner')._find_accounting_partner( invoice.partner_id).id if invoice.partner_id.id not in customer_grouped: customer_grouped.append(invoice.partner_id.id) customer_invoice_grouped.append(invoice.id) if not cust_inv.get(invoice.partner_id.id): partner_list = [] partner_list.append(invoice.id) cust_inv[invoice.partner_id.id] = partner_list else: cust_inv[invoice.partner_id.id].append(invoice.id) voucher_values = { 'close_after_process': True, 'invoice_type': 'in_invoice', 'type': 'payment', } for cust, invoices in cust_inv.iteritems(): move_lines = [] part = self.pool.get('res.partner').browse(cr, uid, cust) if invoices: invoice_browse = invoice_obj.browse(cr, uid, invoices[0]) voucher_values = { 'payment_expected_currency': invoice_browse.currency_id.id, 'default_reference': invoice_browse.name, 'invoice_id': invoice_browse.id, } amount, voucher_values, move_lines, context[ 'move_line_ids'] = 0.0, {}, [], [] for inv in invoice_obj.browse(cr, uid, invoices): voucher_wizard_values = invoice_obj.invoice_pay_customer( cr, uid, [inv.id], context) # print "voucher_wizard_values.......",voucher_wizard_values if voucher_wizard_values and voucher_wizard_values.get( 'context'): voucher_values = voucher_wizard_values.get('context') amount += inv.residual or 0.0 if inv.move_id: for line in inv.move_id.line_id: move_lines.append(line.id) if round(amount, 6) != round(payment_obj.amount, 6): raise osv.except_osv( _('Mismatch Amount!!'), _('The amount pending for selected invoices and entered amount is mismatching!' )) context['move_line_ids'] = move_lines if voucher_values.get('type') and voucher_values.get( 'default_amount'): onchange_voucher_values = account_voucher.onchange_journal( cr, uid, [], journal.id, [], [], cust, payment_obj.date_checkprint, amount, voucher_values.get('type'), company_id, context=context) if onchange_voucher_values and onchange_voucher_values.get( 'value'): new_voucher_values = onchange_voucher_values.get( 'value') if new_voucher_values and new_voucher_values.get( 'account_id'): dr_lines, cr_lines = [], [] # if new_voucher_values.get('line_dr_ids'): # line_dr_ids = new_voucher_values.get('line_dr_ids') # for line_dr_id in line_dr_ids: # # print "line_dr_id........",line_dr_id # if line_dr_id.get('move_line_id', False) and line_dr_id.get('move_line_id') in move_lines: ## line_dr_id['reconcile'] = True # line_dr_id['amount'] = line_dr_id.get('amount_unreconciled',0.0) # dr_lines.append([0, False, line_dr_id]) # For using getting move lines of Selected invoices only # if inv.move_id: # for move_line in inv.move_id.line_id: # print "move_lines............",move_lines # context['move_line_ids'] = move_lines if new_voucher_values.get('line_cr_ids'): line_cr_ids = new_voucher_values.get( 'line_cr_ids') for line_cr_id in line_cr_ids: if line_cr_id.get('move_line_id'): move_line = move_obj.browse( cr, uid, line_cr_id.get('move_line_id')) if move_line.invoice: # print "invoice......",move_line.invoice line_cr_id[ 'amount'] = line_cr_id.get( 'amount_unreconciled', 0.0) # print "line_cr_id['amount']........",line_cr_id['amount'] cr_lines.append([0, False, line_cr_id]) partner_id = self.pool.get( 'res.partner')._find_accounting_partner( part).id account_data = invoice_obj.get_accounts( cr, uid, partner_id, journal.id) # date_today = fields.date.context_today(self, cr, uid, context=context) period_ids = self.pool.get('account.period').find( cr, uid, payment_obj.date_checkprint, context=context) period_id = period_ids and period_ids[0] or False vals = { 'company_id': company_id, 'journal_id': journal.id, 'reference': '', 'partner_id': partner_id, 'amount': payment_obj.amount or 0.0, 'type': voucher_values.get('type'), 'account_id': account_data['value']['account_id'], 'date': payment_obj.date_checkprint, 'line_cr_ids': cr_lines, 'line_dr_ids': dr_lines, 'payment_rate': new_voucher_values.get('payment_rate'), 'pre_line': new_voucher_values.get('pre_line'), 'currency_id': new_voucher_values.get('currency_id'), 'currency_help_label': new_voucher_values.get('currency_help_label'), 'paid_amount_in_company_currency': new_voucher_values.get( 'paid_amount_in_company_currency'), # 'is_check':True, 'period_id': period_id, } # if payment_obj.check_number: # if check_count == 0: # vals['check_number'] = payment_obj.check_number or '' # else: # vals['check_number'] = str(payment_obj.check_number) + '_' + str(check_count) or '' account_voucher_id = account_voucher.create( cr, uid, vals) voucher_ids.append(account_voucher_id) # account_voucher.button_proforma_voucher(cr, uid, [account_voucher_id], context) # wf_service.trg_validate(uid, 'account.invoice', invoice_brw.id, 'confirm_paid', cr) # check_count += 1 voucher_ids = list(set(flatten(voucher_ids))) print "voucher_ids print......", len(voucher_ids) res = self.pool.get('ir.model.data').get_object_reference( cr, uid, 'account_voucher', 'view_vendor_receipt_form') res_id = res and res[1] or False, return { # 'domain': str([('id','in',voucher_ids)]), 'name': 'Customer Payment', 'view_type': 'form', 'view_mode': 'form', 'res_model': 'account.voucher', 'view_id': [res_id[0]], 'target': 'current', 'type': 'ir.actions.act_window', 'res_id': voucher_ids and voucher_ids[0] or False, }
def send_email( self, cr, uid, message, mail_server_id=None, smtp_server=None, smtp_port=None, smtp_user=None, smtp_password=None, smtp_encryption=None, smtp_debug=False, context=None, ): """Sends an email directly (no queuing). No retries are done, the caller should handle MailDeliveryException in order to ensure that the mail is never lost. If the mail_server_id is provided, sends using this mail server, ignoring other smtp_* arguments. If mail_server_id is None and smtp_server is None, use the default mail server (highest priority). If mail_server_id is None and smtp_server is not None, use the provided smtp_* arguments. If both mail_server_id and smtp_server are None, look for an 'smtp_server' value in server config, and fails if not found. :param message: the email.message.Message to send. The envelope sender will be extracted from the ``Return-Path`` (if present), or will be set to the default bounce address. The envelope recipients will be extracted from the combined list of ``To``, ``CC`` and ``BCC`` headers. :param mail_server_id: optional id of ir.mail_server to use for sending. overrides other smtp_* arguments. :param smtp_server: optional hostname of SMTP server to use :param smtp_encryption: optional TLS mode, one of 'none', 'starttls' or 'ssl' (see ir.mail_server fields for explanation) :param smtp_port: optional SMTP port, if mail_server_id is not passed :param smtp_user: optional SMTP user, if mail_server_id is not passed :param smtp_password: optional SMTP password to use, if mail_server_id is not passed :param smtp_debug: optional SMTP debug flag, if mail_server_id is not passed :return: the Message-ID of the message that was just sent, if successfully sent, otherwise raises MailDeliveryException and logs root cause. """ # Use the default bounce address **only if** no Return-Path was # provided by caller. Caller may be using Variable Envelope Return # Path (VERP) to detect no-longer valid email addresses. smtp_from = message["Return-Path"] if not smtp_from: smtp_from = self._get_default_bounce_address(cr, uid, context=context) if not smtp_from: smtp_from = message["From"] assert smtp_from, "The Return-Path or From header is required for any outbound email" # The email's "Envelope From" (Return-Path), and all recipient addresses must only contain ASCII characters. from_rfc2822 = extract_rfc2822_addresses(smtp_from) assert from_rfc2822, ( "Malformed 'Return-Path' or 'From' address: %r - " "It should contain one valid plain ASCII email" ) % smtp_from # use last extracted email, to support rarities like 'Support@MyComp <*****@*****.**>' smtp_from = from_rfc2822[-1] email_to = message["To"] email_cc = message["Cc"] email_bcc = message["Bcc"] smtp_to_list = filter(None, tools.flatten(map(extract_rfc2822_addresses, [email_to, email_cc, email_bcc]))) assert smtp_to_list, self.NO_VALID_RECIPIENT x_forge_to = message["X-Forge-To"] if x_forge_to: # `To:` header forged, e.g. for posting on mail.groups, to avoid confusion del message["X-Forge-To"] del message["To"] # avoid multiple To: headers! message["To"] = x_forge_to # Do not actually send emails in testing mode! if getattr(threading.currentThread(), "testing", False): _test_logger.info("skip sending email in test mode") return message["Message-Id"] # Get SMTP Server Details from Mail Server mail_server = None if mail_server_id: mail_server = self.browse(cr, SUPERUSER_ID, mail_server_id) elif not smtp_server: mail_server_ids = self.search(cr, SUPERUSER_ID, [], order="sequence", limit=1) if mail_server_ids: mail_server = self.browse(cr, SUPERUSER_ID, mail_server_ids[0]) if mail_server: smtp_server = mail_server.smtp_host smtp_user = mail_server.smtp_user smtp_password = mail_server.smtp_pass smtp_port = mail_server.smtp_port smtp_encryption = mail_server.smtp_encryption smtp_debug = smtp_debug or mail_server.smtp_debug else: # we were passed an explicit smtp_server or nothing at all smtp_server = smtp_server or tools.config.get("smtp_server") smtp_port = tools.config.get("smtp_port", 25) if smtp_port is None else smtp_port smtp_user = smtp_user or tools.config.get("smtp_user") smtp_password = smtp_password or tools.config.get("smtp_password") if smtp_encryption is None and tools.config.get("smtp_ssl"): smtp_encryption = "starttls" # STARTTLS is the new meaning of the smtp_ssl flag as of v7.0 if not smtp_server: raise UserError( _("Missing SMTP Server") + "\n" + _("Please define at least one SMTP server, or provide the SMTP parameters explicitly.") ) try: message_id = message["Message-Id"] # Add email in Maildir if smtp_server contains maildir. 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 message_id smtp = None try: smtp = self.connect( smtp_server, smtp_port, smtp_user, smtp_password, smtp_encryption or False, smtp_debug ) smtp.sendmail(smtp_from, smtp_to_list, message.as_string()) finally: if smtp is not None: smtp.quit() except Exception, e: msg = _("Mail delivery failed via SMTP server '%s'.\n%s: %s") % ( tools.ustr(smtp_server), e.__class__.__name__, tools.ustr(e), ) _logger.info(msg) raise MailDeliveryException(_("Mail Delivery Failed"), msg)
def send_email(self, cr, uid, message, mail_server_id=None, smtp_server=None, smtp_port=None, smtp_user=None, smtp_password=None, smtp_encryption=None, smtp_debug=False, context=None): """Sends an email directly (no queuing). No retries are done, the caller should handle MailDeliveryException in order to ensure that the mail is never lost. If the mail_server_id is provided, sends using this mail server, ignoring other smtp_* arguments. If mail_server_id is None and smtp_server is None, use the default mail server (highest priority). If mail_server_id is None and smtp_server is not None, use the provided smtp_* arguments. If both mail_server_id and smtp_server are None, look for an 'smtp_server' value in server config, and fails if not found. :param message: the email.message.Message to send. The envelope sender will be extracted from the ``Return-Path`` (if present), or will be set to the default bounce address. The envelope recipients will be extracted from the combined list of ``To``, ``CC`` and ``BCC`` headers. :param mail_server_id: optional id of ir.mail_server to use for sending. overrides other smtp_* arguments. :param smtp_server: optional hostname of SMTP server to use :param smtp_encryption: optional TLS mode, one of 'none', 'starttls' or 'ssl' (see ir.mail_server fields for explanation) :param smtp_port: optional SMTP port, if mail_server_id is not passed :param smtp_user: optional SMTP user, if mail_server_id is not passed :param smtp_password: optional SMTP password to use, if mail_server_id is not passed :param smtp_debug: optional SMTP debug flag, if mail_server_id is not passed :return: the Message-ID of the message that was just sent, if successfully sent, otherwise raises MailDeliveryException and logs root cause. """ # Use the default bounce address **only if** no Return-Path was # provided by caller. Caller may be using Variable Envelope Return # Path (VERP) to detect no-longer valid email addresses. smtp_from = message['Return-Path'] if not smtp_from: smtp_from = self._get_default_bounce_address(cr, uid, context=context) if not smtp_from: smtp_from = message['From'] assert smtp_from, "The Return-Path or From header is required for any outbound email" # The email's "Envelope From" (Return-Path), and all recipient addresses must only contain ASCII characters. from_rfc2822 = extract_rfc2822_addresses(smtp_from) assert from_rfc2822, ("Malformed 'Return-Path' or 'From' address: %r - " "It should contain one valid plain ASCII email") % smtp_from # use last extracted email, to support rarities like 'Support@MyComp <*****@*****.**>' smtp_from = from_rfc2822[-1] email_to = message['To'] email_cc = message['Cc'] email_bcc = message['Bcc'] smtp_to_list = filter(None, tools.flatten(map(extract_rfc2822_addresses,[email_to, email_cc, email_bcc]))) assert smtp_to_list, self.NO_VALID_RECIPIENT x_forge_to = message['X-Forge-To'] if x_forge_to: # `To:` header forged, e.g. for posting on mail.channels, to avoid confusion del message['X-Forge-To'] del message['To'] # avoid multiple To: headers! message['To'] = x_forge_to # Do not actually send emails in testing mode! if getattr(threading.currentThread(), 'testing', False): _test_logger.info("skip sending email in test mode") return message['Message-Id'] # Get SMTP Server Details from Mail Server mail_server = None if mail_server_id: mail_server = self.browse(cr, SUPERUSER_ID, mail_server_id) elif not smtp_server: mail_server_ids = self.search(cr, SUPERUSER_ID, [], order='sequence', limit=1) if mail_server_ids: mail_server = self.browse(cr, SUPERUSER_ID, mail_server_ids[0]) if mail_server: smtp_server = mail_server.smtp_host smtp_user = mail_server.smtp_user smtp_password = mail_server.smtp_pass smtp_port = mail_server.smtp_port smtp_encryption = mail_server.smtp_encryption smtp_debug = smtp_debug or mail_server.smtp_debug else: # we were passed an explicit smtp_server or nothing at all smtp_server = smtp_server or tools.config.get('smtp_server') smtp_port = tools.config.get('smtp_port', 25) if smtp_port is None else smtp_port smtp_user = smtp_user or tools.config.get('smtp_user') smtp_password = smtp_password or tools.config.get('smtp_password') if smtp_encryption is None and tools.config.get('smtp_ssl'): smtp_encryption = 'starttls' # STARTTLS is the new meaning of the smtp_ssl flag as of v7.0 if not smtp_server: raise UserError(_("Missing SMTP Server")+ "\n" + _("Please define at least one SMTP server, or provide the SMTP parameters explicitly.")) try: message_id = message['Message-Id'] # Add email in Maildir if smtp_server contains maildir. 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 message_id smtp = None try: smtp = self.connect(smtp_server, smtp_port, smtp_user, smtp_password, smtp_encryption or False, smtp_debug) smtp.sendmail(smtp_from, smtp_to_list, message.as_string()) finally: if smtp is not None: smtp.quit() except Exception, e: msg = _("Mail delivery failed via SMTP server '%s'.\n%s: %s") % (tools.ustr(smtp_server), e.__class__.__name__, tools.ustr(e)) _logger.info(msg) raise MailDeliveryException(_("Mail Delivery Failed"), msg)
def send_email( self, cr, uid, message, mail_server_id=None, smtp_server=None, smtp_port=None, smtp_user=None, smtp_password=None, smtp_encryption=None, smtp_debug=False, context=None, ): """Sends an email directly (no queuing). No retries are done, the caller should handle MailDeliveryException in order to ensure that the mail is never lost. If the mail_server_id is provided, sends using this mail server, ignoring other smtp_* arguments. If mail_server_id is None and smtp_server is None, use the default mail server (highest priority). If mail_server_id is None and smtp_server is not None, use the provided smtp_* arguments. If both mail_server_id and smtp_server are None, look for an 'smtp_server' value in server config, and fails if not found. :param message: the email.message.Message to send. The envelope sender will be extracted from the ``Return-Path`` or ``From`` headers. The envelope recipients will be extracted from the combined list of ``To``, ``CC`` and ``BCC`` headers. :param mail_server_id: optional id of ir.mail_server to use for sending. overrides other smtp_* arguments. :param smtp_server: optional hostname of SMTP server to use :param smtp_encryption: optional TLS mode, one of 'none', 'starttls' or 'ssl' (see ir.mail_server fields for explanation) :param smtp_port: optional SMTP port, if mail_server_id is not passed :param smtp_user: optional SMTP user, if mail_server_id is not passed :param smtp_password: optional SMTP password to use, if mail_server_id is not passed :param smtp_debug: optional SMTP debug flag, if mail_server_id is not passed :return: the Message-ID of the message that was just sent, if successfully sent, otherwise raises MailDeliveryException and logs root cause. """ smtp_from = message["Return-Path"] or message["From"] assert smtp_from, "The Return-Path or From header is required for any outbound email" # The email's "Envelope From" (Return-Path), and all recipient addresses must only contain ASCII characters. from_rfc2822 = extract_rfc2822_addresses(smtp_from) assert from_rfc2822, ( "Malformed 'Return-Path' or 'From' address: %r - " "It should contain one valid plain ASCII email" ) % smtp_from # use last extracted email, to support rarities like 'Support@MyComp <*****@*****.**>' smtp_from = from_rfc2822[-1] email_to = message["To"] email_cc = message["Cc"] email_bcc = message["Bcc"] smtp_to_list = filter(None, tools.flatten(map(extract_rfc2822_addresses, [email_to, email_cc, email_bcc]))) assert smtp_to_list, self.NO_VALID_RECIPIENT # Do not actually send emails in testing mode! if getattr(threading.currentThread(), "testing", False): _logger.log(logging.INFO, "skip sending email in test mode") return message["Message-Id"] # Get SMTP Server Details from Mail Server mail_server = None if mail_server_id: mail_server = self.browse(cr, SUPERUSER_ID, mail_server_id) elif not smtp_server: mail_server_ids = self.search(cr, SUPERUSER_ID, [], order="sequence", limit=1) if mail_server_ids: mail_server = self.browse(cr, SUPERUSER_ID, mail_server_ids[0]) if mail_server: smtp_server = mail_server.smtp_host smtp_user = mail_server.smtp_user smtp_password = mail_server.smtp_pass smtp_port = mail_server.smtp_port smtp_encryption = mail_server.smtp_encryption smtp_debug = smtp_debug or mail_server.smtp_debug else: # we were passed an explicit smtp_server or nothing at all smtp_server = smtp_server or tools.config.get("smtp_server") smtp_port = tools.config.get("smtp_port", 25) if smtp_port is None else smtp_port smtp_user = smtp_user or tools.config.get("smtp_user") smtp_password = smtp_password or tools.config.get("smtp_password") if smtp_encryption is None and tools.config.get("smtp_ssl"): smtp_encryption = "starttls" # STARTTLS is the new meaning of the smtp_ssl flag as of v7.0 if not smtp_server: raise osv.except_osv( _("Missing SMTP Server"), _("Please define at least one SMTP server, or provide the SMTP parameters explicitly."), ) try: message_id = message["Message-Id"] # Add email in Maildir if smtp_server contains maildir. 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 message_id try: smtp = self.connect(smtp_server, smtp_port, smtp_user, smtp_password, smtp_encryption or False, smtp_debug) # smtp.sendmail(smtp_from, smtp_to_list, message.as_string()) """ johnw 02/18/2014 enhance the mail sending logic to handle the "login and from address not mathcing" issue, for example, 163.com will raise exception under this case if from and login user is different, then to try to send using smtp_user again """ try: smtp.sendmail(smtp_from, smtp_to_list, message.as_string()) except Exception, e: if smtp_from != smtp_user: smtp.sendmail(smtp_user, smtp_to_list, message.as_string()) else: raise e finally: try: # Close Connection of SMTP Server smtp.quit() except Exception: # ignored, just a consequence of the previous exception pass except Exception, e: msg = _("Mail delivery failed via SMTP server '%s'.\n%s: %s") % ( tools.ustr(smtp_server), e.__class__.__name__, tools.ustr(e), ) _logger.exception(msg) raise MailDeliveryException(_("Mail delivery failed"), msg)
def send_email(self, cr, uid, message, mail_server_id=None, smtp_server=None, smtp_port=None, smtp_user=None, smtp_password=None, smtp_encryption=None, smtp_debug=False, context=None): """Sends an email directly (no queuing). No retries are done, the caller should handle MailDeliveryException in order to ensure that the mail is never lost. If the mail_server_id is provided, sends using this mail server, ignoring other smtp_* arguments. If mail_server_id is None and smtp_server is None, use the default mail server (highest priority). If mail_server_id is None and smtp_server is not None, use the provided smtp_* arguments. If both mail_server_id and smtp_server are None, look for an 'smtp_server' value in server config, and fails if not found. :param message: the email.message.Message to send. The envelope sender will be extracted from the ``Return-Path`` or ``From`` headers. The envelope recipients will be extracted from the combined list of ``To``, ``CC`` and ``BCC`` headers. :param mail_server_id: optional id of ir.mail_server to use for sending. overrides other smtp_* arguments. :param smtp_server: optional hostname of SMTP server to use :param smtp_encryption: optional TLS mode, one of 'none', 'starttls' or 'ssl' (see ir.mail_server fields for explanation) :param smtp_port: optional SMTP port, if mail_server_id is not passed :param smtp_user: optional SMTP user, if mail_server_id is not passed :param smtp_password: optional SMTP password to use, if mail_server_id is not passed :param smtp_debug: optional SMTP debug flag, if mail_server_id is not passed :return: the Message-ID of the message that was just sent, if successfully sent, otherwise raises MailDeliveryException and logs root cause. """ smtp_from = message['Return-Path'] or message['From'] assert smtp_from, "The Return-Path or From header is required for any outbound email" # The email's "Envelope From" (Return-Path), and all recipient addresses must only contain ASCII characters. from_rfc2822 = extract_rfc2822_addresses(smtp_from) assert len(from_rfc2822) == 1, "Malformed 'Return-Path' or 'From' address - it may only contain plain ASCII characters" smtp_from = from_rfc2822[0] email_to = message['To'] email_cc = message['Cc'] email_bcc = message['Bcc'] smtp_to_list = filter(None, tools.flatten(map(extract_rfc2822_addresses,[email_to, email_cc, email_bcc]))) assert smtp_to_list, "At least one valid recipient address should be specified for outgoing emails (To/Cc/Bcc)" # Do not actually send emails in testing mode! if getattr(threading.currentThread(), 'testing', False): _logger.log(logging.TEST, "skip sending email in test mode") return message['Message-Id'] # Get SMTP Server Details from Mail Server mail_server = None if mail_server_id: mail_server = self.browse(cr, SUPERUSER_ID, mail_server_id) elif not smtp_server: mail_server_ids = self.search(cr, SUPERUSER_ID, [], order='sequence', limit=1) if mail_server_ids: mail_server = self.browse(cr, SUPERUSER_ID, mail_server_ids[0]) if mail_server: smtp_server = mail_server.smtp_host smtp_user = mail_server.smtp_user smtp_password = mail_server.smtp_pass smtp_port = mail_server.smtp_port smtp_encryption = mail_server.smtp_encryption smtp_debug = smtp_debug or mail_server.smtp_debug else: # we were passed an explicit smtp_server or nothing at all smtp_server = smtp_server or tools.config.get('smtp_server') smtp_port = tools.config.get('smtp_port', 25) if smtp_port is None else smtp_port smtp_user = smtp_user or tools.config.get('smtp_user') smtp_password = smtp_password or tools.config.get('smtp_password') if smtp_encryption is None and tools.config.get('smtp_ssl'): smtp_encryption = 'starttls' # STARTTLS is the new meaning of the smtp_ssl flag as of v7.0 if not smtp_server: raise osv.except_osv( _("Missing SMTP Server"), _("Please define at least one SMTP server, or provide the SMTP parameters explicitly.")) try: message_id = message['Message-Id'] # Add email in Maildir if smtp_server contains maildir. 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 message_id try: smtp = self.connect(smtp_server, smtp_port, smtp_user, smtp_password, smtp_encryption or False, smtp_debug) smtp.sendmail(smtp_from, smtp_to_list, message.as_string()) finally: try: # Close Connection of SMTP Server smtp.quit() except Exception: # ignored, just a consequence of the previous exception pass except Exception, e: msg = _("Mail delivery failed via SMTP server '%s'.\n%s: %s") % (tools.ustr(smtp_server), e.__class__.__name__, tools.ustr(e)) _logger.exception(msg) raise MailDeliveryException(_("Mail delivery failed"), msg)
def send_email(self, message, mail_server_id=None, smtp_server=None, smtp_port=None, smtp_user=None, smtp_password=None, smtp_encryption=None, smtp_debug=False, context=None): from_rfc2822 = extract_rfc2822_addresses(message['From'])[-1] server_id = self.env['ir.mail_server'].search([ '|', ('id', '=', self.env.user.send_mail_server_id.id), ('id', '=', self.env.user.company_id.send_mail_server_id.id) ], order='sequence', limit=1) #.search( [('smtp_user', '=', from_rfc2822)],) if server_id and server_id[0]: message['Return-Path'] = from_rfc2822 smtp_from = message['Return-Path'] if not smtp_from: smtp_from = self._get_default_bounce_address(context=context) if not smtp_from: smtp_from = message['From'] assert smtp_from, "The Return-Path or From header is required for any outbound email" # The email's "Envelope From" (Return-Path), and all recipient addresses must only contain ASCII characters. from_rfc2822 = extract_rfc2822_addresses(smtp_from) assert from_rfc2822, ( "Malformed 'Return-Path' or 'From' address: %r - " "It should contain one valid plain ASCII email") % smtp_from # use last extracted email, to support rarities like 'Support@MyComp <*****@*****.**>' smtp_from = from_rfc2822[-1] email_to = message['To'] email_cc = message['Cc'] email_bcc = message['Bcc'] smtp_to_list = filter( None, tools.flatten( map(extract_rfc2822_addresses, [email_to, email_cc, email_bcc]))) assert smtp_to_list, self.NO_VALID_RECIPIENT x_forge_to = message['X-Forge-To'] if x_forge_to: # `To:` header forged, e.g. for posting on mail.groups, to avoid confusion del message['X-Forge-To'] del message['To'] # avoid multiple To: headers! message['To'] = x_forge_to # Do not actually send emails in testing mode! if getattr(threading.currentThread(), 'testing', False): _test_logger.info("skip sending email in test mode") return message['Message-Id'] # Get SMTP Server Details from Mail Server mail_server = None if mail_server_id: mail_server = self.browse(mail_server_id) elif not smtp_server: mail_server_ids = self.search([], order='sequence', limit=1) if mail_server_ids: mail_server = self.browse(mail_server_ids[0]) if mail_server: smtp_server = mail_server.smtp_host smtp_user = mail_server.smtp_user smtp_password = mail_server.smtp_pass smtp_port = mail_server.smtp_port smtp_encryption = mail_server.smtp_encryption smtp_debug = smtp_debug or mail_server.smtp_debug else: # we were passed an explicit smtp_server or nothing at all smtp_server = smtp_server or tools.config.get('smtp_server') smtp_port = tools.config.get( 'smtp_port', 25) if smtp_port is None else smtp_port smtp_user = smtp_user or tools.config.get('smtp_user') smtp_password = smtp_password or tools.config.get('smtp_password') if smtp_encryption is None and tools.config.get('smtp_ssl'): smtp_encryption = 'starttls' # STARTTLS is the new meaning of the smtp_ssl flag as of v7.0 if not smtp_server: raise osv.except_osv( _("Missing SMTP Server"), _("Please define at least one SMTP server, or provide the SMTP parameters explicitly." )) try: message_id = message['Message-Id'] # Add email in Maildir if smtp_server contains maildir. 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 message_id smtp = None try: smtp = self.connect(smtp_server, smtp_port, smtp_user, smtp_password, smtp_encryption or False, smtp_debug) smtp.sendmail(smtp_from, smtp_to_list, message.as_string()) finally: if smtp is not None: smtp.quit() except Exception, e: msg = _( "Mail delivery failed via SMTP server '%s'.\n%s: %s, Please check your mail setting" ) % (tools.ustr(smtp_server), e.__class__.__name__, tools.ustr(e)) raise osv.except_osv(_("Mail Delivery Failed"), msg)
def mail_queue(self, cr, uid, ids, context=None): mail = self.browse(cr, uid, ids[0]) template_obj = self.pool.get('email.template') dev_obj = self.pool.get('jkp.devotees') sender = mail.mail_server_id.smtp_user if mail.schedule_mail: mail_type='Scheduled' else: mail_type='Non' sch_date = mail.schedule_date subject = mail.subject mail_body = mail.body or '\n' signature='' if mail.template_id and template_obj.browse(cr, uid,mail.template_id).email_sign: signature= template_obj.browse(cr, uid,mail.template_id).email_sign if not sch_date: sch_date = datetime.now() server_id = mail.mail_server_id.id queue_obj =self.pool.get('mail.logs') devotee_ids = [] mail_list = [] category_ids = [] dtm = datetime.now() if context: devotee_ids = context.get('active_ids',[]) print "devotee ids.........................",devotee_ids if mail.all: devotee_ids.append(dev_obj.search(cr, uid, [('dormant','=',False),('email','!=',False)])) if mail.category_ids: for categ in mail.category_ids: category_ids.append(categ.id) devotee_ids.append(dev_obj.search(cr, uid, [('dormant','=',False),('category_ids','in',category_ids),('email','!=',False)])) devotee_ids = list(set(flatten(devotee_ids))) if len(devotee_ids) == 1: devotee_ids.append(devotee_ids[0]) send_to_ids = tuple(devotee_ids) if mail.additional_contacts: mail_list=mail.additional_contacts.split(',') print "send to ids....................",send_to_ids if send_to_ids: cr.execute("select distinct email from jkp_devotees where email is not null and id in "+str(send_to_ids)) temp = cr.fetchall() for val1 in temp: mail_list.append(val1[0]) mail_list = list(set(flatten(mail_list))) for val in mail_list: receiver=val devotee_id='' if val: searchMail_ids = dev_obj.search(cr, uid, [('email','=',val),('state','=','Draft')]) if searchMail_ids: devotee_id=searchMail_ids[0] dtm= datetime.now() vals = { 'log_id':devotee_id, 'user_id':uid, 'date':dtm, 'subject':subject or 'No Subject', 'email_from':sender, 'email_to':receiver, 'mail_body':mail_body, 'server_id':server_id, 'state':'outgoing', 'status':'Email', 'schedule_date':sch_date, 'data_ids':[(6,0,[att.id for att in mail.attachment_ids])], 'type':mail_type, 'sign':signature, } queue_obj.create(cr, uid, vals) return True
def file_upload(self,cr,uid,ids,context=None): res={} incmp=[] file=self.browse(cr,uid,ids)[0].file string=base64.decodestring(file) fp=open("/tmp/jkp.xls",'wb') fp.write(string) fp.close() regs_no= 0 first_name = 1 last_name = 2 f_name = 3 dob = 4 gender = 5 profession=6 qualification_ids=7 mother_tongue=8 work_detail=9 lang_known=10 street1=11 country=12 state=13 district=14 tahsil=15 post_office=16 pin=17 land_code=18 land_std=19 landline=20 mobile1_code=21 mobile1=22 mobile2_code=23 mobile2=24 email=25 email2=26 eme_name=27 eme_rel=28 eme_street1=29 eme_country=30 eme_state=31 eme_district=32 eme_tahsil=33 eme_post_office=34 eme_pin=35 eme_land_code=36 eme_land_std=37 eme_landline=38 eme_mobile1_code=39 eme_mobile1=40 eme_mobile2_code=41 eme_mobile2=42 eme_email=43 jkp_year=44 asso_through=45 spacify_name=46 contact_mode=47 permission=48 rmrk=49 categories=50 accommodation=51 acc_mangarh=52 acc_barsana=53 acc_vrindavan=54 acc_other=55 marital_status=56 place = 57 pan = 58 db_name =cr.dbname user_id =self.pool.get('res.users').search(cr,uid, [('login','=','admin')])[0] pwd =self.pool.get('res.users').browse(cr ,uid, user_id).password conn=openerplib.get_connection(hostname='localhost', database=db_name, login='******', password=pwd) jkp_model=conn.get_model("jkp.devotees") prof_model=conn.get_model("profession.profession") quali_model=conn.get_model("qualification") lang_model=conn.get_model("lang.known") count_model=conn.get_model("res.country") stat_model=conn.get_model("res.country.state") distc_model=conn.get_model("res.district") tahsil_model=conn.get_model("res.tahsil") post_model= conn.get_model("post.office") year_model=conn.get_model('year.jkp') family_model=conn.get_model('devotee.family') pchrk_model=conn.get_model('jkp.pracharak') categ_model=conn.get_model('jkp.category') place_obj =conn.get_model('res.city') relation_obj= conn.get_model('jkp.relation') try: revert_prof=[] book=xlrd.open_workbook("/tmp/jkp.xls") sh=book.sheet_by_index(0) for row in range (1,sh.nrows): try: rowValues = sh.row_values(row) serial = rowValues[dob] seconds = (serial - 25569) * 86400.0 dt=datetime.datetime.utcfromtimestamp(seconds).strftime('%Y-%m-%d') #Place place_ids=[] try: place_ids=place_obj.search([ ('name','=',rowValues[place].title() ) ]) if rowValues[place] and not place_ids: place_id=place_obj.create({'name':rowValues[place] }) place_ids=[place_id] except: pass #PROFESSION prof_ids=[] try: prof_ids=prof_model.search([('name','=',rowValues[profession].title() )]) if rowValues[profession] and not prof_ids: prof_id=prof_model.create({'name':rowValues[profession]}) prof_ids=[prof_id] except: pass #QUALIFICATION quali_ids=[] if rowValues[qualification_ids]: qualifications= rowValues[qualification_ids].split(',') lan=[] for val in qualifications: val=val.strip() lan_id1=[] lan_id2=[] try: lan_id1=quali_model.search([('name','=',val )]) if len(lan_id1)>0: lan.append(lan_id1) if not lan_id1: lan_id2=quali_model.create({'name':val}) lan.append(lan_id2) quali_ids=flatten(lan) except: pass #MOTHER TONGUE lang_ids=[] try: lang_ids=lang_model.search([ ('name','=',rowValues[mother_tongue].title() ) ]) if rowValues[mother_tongue] and not lang_ids: lang_id=lang_model.create({'name':rowValues[mother_tongue] }) lang_ids=[lang_id] except: pass #COUNTRY USING SQL QUERY ========= count_ids=[] try: if rowValues[country]: cr.execute(" select id from res_country where LOWER(name)='"+rowValues[country].lower()+"'") count_ids=cr.fetchone() except: pass #STATE state_ids=[] try: state_ids=stat_model.search([ ('name','=',rowValues[state].title() )]) if rowValues[state] and not state_ids: state_id=stat_model.create({ 'name':rowValues[state],'country_id':count_ids[0] }) state_ids=[state_id] except: pass #DISTRICT distc_ids=[] try: distc_ids=distc_model.search([ ('name','=',rowValues[district].title() )]) if rowValues[district] and not distc_ids: distc_id=distc_model.create({ 'name':rowValues[district],'state_id':state_ids[0] }) print "...............district",distc_id distc_ids=[distc_id] except: pass #TAHSIL tahsil_ids=[] try: tahsil_ids=tahsil_model.search([ ('name','=',rowValues[tahsil].title() )]) if rowValues[tahsil] and not tahsil_ids: tahsil_id=tahsil_model.create({ 'name':rowValues[tahsil],'dist_id':distc_ids[0] }) tahsil_ids=[tahsil_id] except: pass #POST OFFICE pin1=str(rowValues[pin]).split('.')[0] post_ids=[] try: post_ids=post_model.search([ ('name','=',rowValues[post_office].title() ),('distt_id','=',distc_ids[0])]) if rowValues[post_office] and not post_ids: post_id=post_model.create({ 'name':rowValues[post_office],'code':pin1,'distt_id':distc_ids[0] }) post_ids=[post_id] except: pass regs=str(rowValues[regs_no]).split('.')[0] code=str(rowValues[land_code]).split('.')[0] std=str(rowValues[land_std]).split('.')[0] landline_no=str(rowValues[landline]).split('.')[0] mob1_code=str(rowValues[mobile1_code]).split('.')[0] mobile1_no=str(rowValues[mobile1]).split('.')[0] mobile2_no=str(rowValues[mobile2]).split('.')[0] mob2_code=str(rowValues[mobile2_code]).split('.')[0] # Address Format add1='' if rowValues[street1]: add1=rowValues[street1] #EMERGENCY COUNTRY USING SQL QUERY ========= eme_count_ids=[] try: if rowValues[eme_country]: cr.execute(" select id from res_country where LOWER(name)='"+rowValues[eme_country].lower()+"'") eme_count_ids=cr.fetchone() or [] eme_count_ids and eme_count_ids[0] except: pass #EMERGENCY STATE eme_state_ids=[] try: eme_state_ids=stat_model.search([ ('name','=',rowValues[eme_state].title() )]) if rowValues[eme_state] and not eme_state_ids: eme_state_id=stat_model.create({ 'name':rowValues[eme_state],'country_id':eme_count_ids and eme_count_ids[0] }) eme_state_ids=[eme_state_id] except: pass #EMERGENCY DISTRICT eme_distc_ids=[] try: eme_distc_ids=distc_model.search([ ('name','=',rowValues[eme_district].title() )]) if rowValues[eme_district] and not eme_distc_ids: eme_distc_id=distc_model.create({ 'name':rowValues[eme_district],'state_id':eme_state_ids and eme_state_ids[0] }) eme_distc_ids=[eme_distc_id] except: pass #EMERGENCY TAHSIL eme_tahsil_ids=[] try: eme_tahsil_ids=tahsil_model.search([ ('name','=',rowValues[eme_tahsil].title() )]) if rowValues[eme_tahsil] and not eme_tahsil_ids: eme_tahsil_id=tahsil_model.create({ 'name':rowValues[eme_tahsil],'dist_id':eme_distc_ids and eme_distc_ids[0] }) eme_tahsil_ids=[eme_tahsil_id] except: pass #EMERGENCY POST OFFICE eme_pin1=str(rowValues[eme_pin]).split('.')[0] eme_post_ids=[] try: eme_post_ids=post_model.search([ ('name','=',rowValues[eme_post_office].title() ),('distt_id','=',eme_distc_ids[0])]) if rowValues[eme_post_office] and not eme_post_ids: eme_post_id=post_model.create({ 'name':rowValues[eme_post_office],'code':eme_pin1,'distt_id':eme_distc_ids[0] }) eme_post_ids=[eme_post_id] except: pass try: devotee_pan='' if len(str(rowValues[pan]).split('.')[0])==10: devotee_pan =str(rowValues[pan]).split('.')[0] except: pass eme_code=str(rowValues[eme_land_code]).split('.')[0] eme_std=str(rowValues[eme_land_std]).split('.')[0] eme_landline_no=str(rowValues[eme_landline]).split('.')[0] eme_mob1_code=str(rowValues[eme_mobile1_code]).split('.')[0] eme_mobile1_no=str(rowValues[eme_mobile1]).split('.')[0] eme_mobile2_no=str(rowValues[eme_mobile2]).split('.')[0] eme_mob2_code=str(rowValues[eme_mobile2_code]).split('.')[0] eme_add1='' try: if rowValues[eme_street1]: eme_add1=rowValues[eme_street1] except: pass #JKP YEAR year=str(rowValues[jkp_year]).split('.')[0] print "year is ...................",rowValues[jkp_year],year try: jkp_year_ids=year_model.search([('name','=',year)]) print "year found..........*******************",jkp_year_ids except: pass #EME Relation relation_ids=[] try: relation_ids=relation_obj.search([('name','=',rowValues[eme_rel].title())]) if rowValues[eme_rel] and not relation_ids: relation_id = relation_obj.create({'name':rowValues[eme_rel]}) relation_ids = relation_id except: pass #Language Known list1=[] if rowValues[lang_known]: langs= rowValues[lang_known].split(',') lan=[] for val in langs: print "language is ..:",val m=val.split(' ') val=m[-1] lan_id1=[] lan_id2=[] lan_id1=lang_model.search([('name','=',val.title() )]) print "lan id ......",lan_id1 if len(lan_id1)>0: lan.append(lan_id1) if not lan_id1: lan_id2=lang_model.create({'name':val}) lan.append(lan_id2) list1=flatten(lan) # Associate with pracharak asso_name=rowValues[spacify_name] pracharak_ids=[] if rowValues[asso_through]=='Pracharak': asso_name='' try: pracharak_ids=pchrk_model.search([ ('name','=',rowValues[spacify_name].title() )]) if rowValues[asso_through] and not pracharak_ids: pracharak_id=pchrk_model.create({ 'name':rowValues[spacify_name] }) pracharak_ids=[pracharak_id] except: pass # Associate with Other options elif rowValues[asso_through] in ['Others','Satsangee','TV Channel']: asso_name = rowValues[spacify_name] # Preferred way of contact mode = rowValues[contact_mode] mode_list = mode.split(',') jkp_sms = False jkp_letter = False jkp_mail = False for val in mode_list: if val.lower().strip() == 'sms': jkp_sms = True if val.lower().strip() == 'email': jkp_mail = True if val.lower().strip() == 'letter': jkp_letter = True # Updated on # update= rowValues[update_date] # accommodation accom = rowValues[accommodation].title() # Categories categ1=[] if rowValues[categories]: categs = rowValues[categories].split(',') cat=[] for val in categs: cat1 = [] cat2 = [] cat_id1 = categ_model.search([('name','=',val.title().strip() )]) print "val...............................",val if len(cat_id1)>0: cat.append(cat_id1) if not cat_id1: cat_id2=categ_model.create({'name':val}) cat.append(cat_id2) categ1=flatten(cat) #Language Known if rowValues[lang_known]: langs= rowValues[lang_known].split(',') lan=[] for val in langs: lan_id1=[] lan_id2=[] lan_id1=lang_model.search([('name','=',val.title().strip() )]) print "lan id ......",lan_id1 if len(lan_id1)>0: lan.append(lan_id1) if not lan_id1: lan_id2=lang_model.create({'name':val}) lan.append(lan_id2) list1=flatten(lan) print "PAN===============",pan print "place ...............",place_ids devotee={ 'reg_no':regs, 'first_name':rowValues[first_name], 'last_name':rowValues[last_name], 'f_name':rowValues[f_name], 'dob':dt, 'gender':rowValues[gender], 'profession':prof_ids and prof_ids[0] , 'qualification_ids':[(6,0,quali_ids)], 'mother_tongue':lang_ids and lang_ids[0], 'prof_detail':rowValues[work_detail], 'street1':add1, 'country_id':count_ids and count_ids[0] or False, 'state_id':state_ids and state_ids[0] or False, 'dist_id':distc_ids and distc_ids[0] or False, 'tahsil':tahsil_ids and tahsil_ids[0] or False, 'post_id':post_ids and post_ids[0], 'pin':pin1, 'land_code':code, 'land_std':std, 'landline':landline_no, 'm1_code':mob1_code, 'mobile1':mobile1_no or False, 'm2_code':mob2_code, 'mobile2':mobile2_no, 'email':rowValues[email], 'email2':rowValues[email2], 'eme_name':rowValues[eme_name], 'eme_rel':rowValues[eme_rel], 'eme_street1':eme_add1, 'eme_country_id':eme_count_ids and eme_count_ids[0] or False, 'eme_state_id':eme_state_ids and eme_state_ids[0] or False, 'eme_dist_id':eme_distc_ids and eme_distc_ids[0] or False, 'eme_tahsil':eme_tahsil_ids and eme_tahsil_ids[0] or False, 'eme_post_id':eme_post_ids and eme_post_ids[0] or False, 'eme_pin':eme_pin1, 'eme_land_code':eme_code, 'eme_land_std':eme_std, 'eme_landline':eme_landline_no, 'eme_m1_code':eme_mob1_code, 'eme_mobile1':eme_mobile1_no or False, 'eme_m2_code':eme_mob2_code, 'eme_mobile2':eme_mobile2_no, 'eme_email':rowValues[eme_email], 'jkp_year':jkp_year_ids and jkp_year_ids[0] or False, 'through':rowValues[asso_through], 'through_name':asso_name, 'pracharak_name':pracharak_ids and pracharak_ids[0], 'contact_via':rowValues[contact_mode], 'letter':jkp_letter, 'sms':jkp_sms, 'mail':jkp_mail, 'lang_known':[(6,0,list1)], 'family_permission':rowValues[permission], 'remark':rowValues[rmrk], 'category_ids':[(6,0,categ1)], 'accommodation':accom, 'mangarh':rowValues[acc_mangarh], 'vrindavan':rowValues[acc_vrindavan], 'barsana':rowValues[acc_barsana], 'other':rowValues[acc_other], 'marital':rowValues[marital_status].title(), 'city_id':place_ids and place_ids[0], 'pan_no':devotee_pan, 'eme_rel_id':relation_ids and relation_ids[0], } devotee_id = jkp_model.create(devotee) print "created devotee is ..:",devotee print "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%.un_uploaded devotees ",incmp except Exception,e: print "&&&&&&&&&&&&&&&&================$$$$$$$$$$$$$$4", e.args incmp.append(row+1) print "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%.un_uploaded devotees ",incmp pass except: raise osv.except_osv(('Unsupported File'),('Please upload (.xls) file or Microsoft Excel 2003 ')) return res
def send_email(self, cr, uid, message, mail_server_id=None, smtp_server=None, smtp_port=None, smtp_user=None, smtp_password=None, smtp_encryption=None, smtp_debug=False, context=None): """Sends an email directly (no queuing). No retries are done, the caller should handle MailDeliveryException in order to ensure that the mail is never lost. If the mail_server_id is provided, sends using this mail server, ignoring other smtp_* arguments. If mail_server_id is None and smtp_server is None, use the default mail server (highest priority). If mail_server_id is None and smtp_server is not None, use the provided smtp_* arguments. If both mail_server_id and smtp_server are None, look for an 'smtp_server' value in server config, and fails if not found. :param message: the email.message.Message to send. The envelope sender will be extracted from the ``Return-Path`` or ``From`` headers. The envelope recipients will be extracted from the combined list of ``To``, ``CC`` and ``BCC`` headers. :param mail_server_id: optional id of ir.mail_server to use for sending. overrides other smtp_* arguments. :param smtp_server: optional hostname of SMTP server to use :param smtp_encryption: optional TLS mode, one of 'none', 'starttls' or 'ssl' (see ir.mail_server fields for explanation) :param smtp_port: optional SMTP port, if mail_server_id is not passed :param smtp_user: optional SMTP user, if mail_server_id is not passed :param smtp_password: optional SMTP password to use, if mail_server_id is not passed :param smtp_debug: optional SMTP debug flag, if mail_server_id is not passed :return: the Message-ID of the message that was just sent, if successfully sent, otherwise raises MailDeliveryException and logs root cause. """ smtp_from = message['Return-Path'] or message['From'] assert smtp_from, "The Return-Path or From header is required for any outbound email" # The email's "Envelope From" (Return-Path), and all recipient addresses must only contain ASCII characters. from_rfc2822 = extract_rfc2822_addresses(smtp_from) assert len(from_rfc2822) == 1, "Malformed 'Return-Path' or 'From' address - it may only contain plain ASCII characters" smtp_from = from_rfc2822[0] email_to = message['To'] email_cc = message['Cc'] email_bcc = message['Bcc'] smtp_to_list = filter(None, tools.flatten(map(extract_rfc2822_addresses,[email_to, email_cc, email_bcc]))) assert smtp_to_list, "At least one valid recipient address should be specified for outgoing emails (To/Cc/Bcc)" # Do not actually send emails in testing mode! if getattr(threading.currentThread(), 'testing', False): _logger.log(logging.TEST, "skip sending email in test mode") return message['Message-Id'] # Get SMTP Server Details from Mail Server mail_server = None if mail_server_id: mail_server = self.browse(cr, SUPERUSER_ID, mail_server_id) elif not smtp_server: mail_server_ids = self.search(cr, SUPERUSER_ID, [], order='sequence', limit=1) if mail_server_ids: mail_server = self.browse(cr, SUPERUSER_ID, mail_server_ids[0]) if mail_server: smtp_server = mail_server.smtp_host smtp_user = mail_server.smtp_user smtp_password = mail_server.smtp_pass smtp_port = mail_server.smtp_port smtp_encryption = mail_server.smtp_encryption smtp_debug = smtp_debug or mail_server.smtp_debug else: # we were passed an explicit smtp_server or nothing at all smtp_server = smtp_server or tools.config.get('smtp_server') smtp_port = tools.config.get('smtp_port', 25) if smtp_port is None else smtp_port smtp_user = smtp_user or tools.config.get('smtp_user') smtp_password = smtp_password or tools.config.get('smtp_password') if smtp_encryption is None and tools.config.get('smtp_ssl'): smtp_encryption = 'starttls' # STARTTLS is the new meaning of the smtp_ssl flag as of v7.0 #update by frank #smtp_user = smtp_from pid = self.pool.get('res.users').browse(cr, uid, uid, context=context).partner_id._id smtp_user = self.pool.get('res.partner').browse(cr, uid, pid, context=context).email smtp_password = self.pool.get('res.users').browse(cr, uid, uid, context=context).x_mailpass #/update if not smtp_server: raise osv.except_osv( _("Missing SMTP Server"), _("Please define at least one SMTP server, or provide the SMTP parameters explicitly.")) try: message_id = message['Message-Id'] # Add email in Maildir if smtp_server contains maildir. 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 message_id try: smtp = self.connect(smtp_server, smtp_port, smtp_user, smtp_password, smtp_encryption or False, smtp_debug) #smtp = self.connect(smtp_server, smtp_port, smtp_from, smtp_password, smtp_encryption or False, smtp_debug) smtp.sendmail(smtp_from, smtp_to_list, message.as_string()) finally: try: # Close Connection of SMTP Server smtp.quit() except Exception: # ignored, just a consequence of the previous exception pass except Exception, e: msg = _("Mail delivery failed via SMTP server '%s'.\n%s: %s") % (tools.ustr(smtp_server), e.__class__.__name__, tools.ustr(e)) _logger.exception(msg) raise MailDeliveryException(_("Mail delivery failed"), msg)
def send_email(self, cr, uid, message, mail_server_id=None, smtp_server=None, smtp_port=None, smtp_user=None, smtp_password=None, smtp_encryption=None, smtp_debug=False, context=None): """Override the standard method to fix the issue of using a mail client where relaying is disallowed.""" # Use the default bounce address **only if** no Return-Path was # provided by caller. Caller may be using Variable Envelope Return # Path (VERP) to detect no-longer valid email addresses. smtp_from = message['Return-Path'] if not smtp_from: smtp_from = self._get_default_bounce_address(cr, uid, context=context) if not smtp_from: smtp_from = message['From'] assert smtp_from, ( "The Return-Path or From header is required for any outbound email" ) # The email's "Envelope From" (Return-Path), and all recipient # addresses must only contain ASCII characters. from_rfc2822 = extract_rfc2822_addresses(smtp_from) assert from_rfc2822, ( "Malformed 'Return-Path' or 'From' address: %r - " "It should contain one valid plain ASCII email") % smtp_from # use last extracted email, to support rarities like # 'Support@MyComp <*****@*****.**>' smtp_from = from_rfc2822[-1] email_to = message['To'] email_cc = message['Cc'] email_bcc = message['Bcc'] smtp_to_list = filter( None, tools.flatten( map(extract_rfc2822_addresses, [email_to, email_cc, email_bcc]))) assert smtp_to_list, self.NO_VALID_RECIPIENT x_forge_to = message['X-Forge-To'] if x_forge_to: # `To:` header forged, e.g. for posting on mail.groups, # to avoid confusion del message['X-Forge-To'] del message['To'] # avoid multiple To: headers! message['To'] = x_forge_to # Do not actually send emails in testing mode! if getattr(threading.currentThread(), 'testing', False): _test_logger.info("skip sending email in test mode") return message['Message-Id'] # Get SMTP Server Details from Mail Server mail_server = None if mail_server_id: mail_server = self.browse(cr, SUPERUSER_ID, mail_server_id) elif not smtp_server: mail_server_ids = self.search(cr, SUPERUSER_ID, [], order='sequence', limit=1) if mail_server_ids: mail_server = self.browse(cr, SUPERUSER_ID, mail_server_ids[0]) if mail_server: smtp_server = mail_server.smtp_host smtp_user = mail_server.smtp_user smtp_password = mail_server.smtp_pass smtp_port = mail_server.smtp_port smtp_encryption = mail_server.smtp_encryption smtp_debug = smtp_debug or mail_server.smtp_debug else: # we were passed an explicit smtp_server or nothing at all smtp_server = smtp_server or tools.config.get('smtp_server') smtp_port = tools.config.get( 'smtp_port', 25) if smtp_port is None else smtp_port smtp_user = smtp_user or tools.config.get('smtp_user') smtp_password = smtp_password or tools.config.get('smtp_password') if smtp_encryption is None and tools.config.get('smtp_ssl'): smtp_encryption = 'starttls' # STARTTLS is the new meaning of the smtp_ssl flag as of v7.0 if not smtp_server: raise osv.except_osv( _("Missing SMTP Server"), _("Please define at least one SMTP server, or " "provide the SMTP parameters explicitly.")) try: message_id = message['Message-Id'] # Add email in Maildir if smtp_server contains maildir. 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 message_id smtp = None try: # START OF CODE ADDED smtp = self.connect(smtp_server, smtp_port, smtp_user, smtp_password, smtp_encryption or False, smtp_debug) # smtp.sendmail(smtp_from, smtp_to_list, message.as_string()) from email.utils import parseaddr, formataddr # exact name and address (oldname, oldemail) = parseaddr(message['From']) # use original name with new address newfrom = formataddr((oldname, smtp_user)) # need to use replace_header instead '=' to prevent # double field message.replace_header('From', newfrom) smtp.sendmail(smtp_user, smtp_to_list, message.as_string()) # END OF CODE ADDED finally: if smtp is not None: smtp.quit() except Exception, e: msg = _("Mail delivery failed via SMTP server '%s'.\n%s: %s") % ( tools.ustr(smtp_server), e.__class__.__name__, tools.ustr(e)) _logger.error(msg) raise MailDeliveryException(_("Mail Delivery Failed"), msg)