def _email_send(self, cr, uid, ids, email_from, subject, body, on_error=None): partners = self.browse(cr, uid, ids) for partner in partners: if len(partner.address): if partner.address[0].email: tools.email_send(email_from, [partner.address[0].email], subject, body, on_error) return True
def _send_email(self, cr, uid, sender, recipient, subject, body): self._log('Tentative d\'envoi du mail') self._log('Envoi d\'un e-mail a ' + recipient + '. Sujet: ' + subject) tools.email_send(email_from=sender, email_to=[recipient] , \ subject=subject, body=body, cr=cr) self._debug("Sending email to " + recipient + ". " + \ "Subject: \"" + subject + "\"")
def run_auto_import(self, cr, uid, automatic=False, use_new_cursor=False, context=None): pool = pooler.get_pool(cr.dbname) #import pdb;pdb.set_trace() testo_log = """Inizio procedura di aggiornamento/inserimento articoli """+time.ctime()+'\n' percorso='/home/openerp/filecsv' partner_obj = pool.get('res.partner') if use_new_cursor: cr = pooler.get_db(use_new_cursor).cursor() elenco_csv = os.listdir(percorso) for filecsv in elenco_csv: codfor=filecsv.split(".") testo_log = testo_log + " analizzo file "+codfor[0]+".csv \n" fornitore_ids = partner_obj.search(cr,uid,[('ref', '=',codfor[0])]) if fornitore_ids: fornitore_id = fornitore_ids[0] lines = csv.reader(open(percorso+'/'+filecsv,'rb'),delimiter=";") #import pdb;pdb.set_trace() res = self._import_product_func(cr, uid, lines, fornitore_id, context) testo_log = testo_log + " Inseriti "+str(res[0])+" Aggiornati "+str(res[1]) +" Articoli \n" else: testo_log = testo_log + " fornitore "+codfor[0]+" non trovato \n" os.remove(percorso+'/'+filecsv) testo_log = testo_log + " Operazione Teminata alle "+time.ctime()+"\n" #invia e-mail type_ = 'plain' tools.email_send('*****@*****.**', ['*****@*****.**'], 'Import Automatico Articoli', testo_log, subtype=type_, ) return
def cron_account_analytic_account(self, cr, uid, context=None): domain = [ ('name', 'not ilike', 'maintenance'), ('partner_id', '!=', False), ('user_id', '!=', False), ('user_id.user_email', '!=', False), ('state', 'in', ('draft', 'open')), '|', ('date', '<', time.strftime('%Y-%m-%d')), ('date', '=', False), ] account_ids = self.search(cr, uid, domain, context=context, order='name asc') accounts = self.browse(cr, uid, account_ids, context=context) users = dict() for account in accounts: users.setdefault(account.user_id, dict()).setdefault(account.partner_id, []).append(account) account.write({'state' : 'pending'}, context=context) for user, data in users.iteritems(): subject = '[OPENERP] Reporting: Analytic Accounts' body = Template(MAKO_TEMPLATE).render_unicode(user=user, partners=data) tools.email_send('*****@*****.**', [user.user_email, ], subject, body) return True
def run(self, cr, uid): """ find the reminder recipients and send them an email """ #get all companies companies = self.pool.get('res.company').browse( cr, uid, self.pool.get('res.company').search(cr, uid, [])) #for each company, get all recipients recipients = [] for c in companies: recipients += self.get_recipients(cr, uid, {}, c) #get the message to send message_id = self.get_message_id(cr, uid, {}) message_data = self.browse(cr, uid, message_id) #send them email if they have an email defined emails = [] for r in recipients: if r.work_email: emails.append(r.work_email) if emails: tools.email_send(message_data.reply_to, [], message_data.subject, message_data.message, email_bcc=emails)
def mail_user(self, cr, uid, ids, confirm=False, context=None): """ Send email to user """ for regestration in self.browse(cr, uid, ids, context=context): src = regestration.event_id.reply_to or False email_to = [] email_cc = [] if regestration.email_from: email_to = regestration.email_from if regestration.email_cc: email_cc += [regestration.email_cc] if not (email_to or email_cc): continue subject = "" body = "" if confirm: subject = _('Auto Confirmation: [%s] %s') %(regestration.id, regestration.name) body = regestration.event_id.mail_confirm elif regestration.event_id.mail_auto_confirm or regestration.event_id.mail_auto_registr: if regestration.event_id.state in ['draft', 'fixed', 'open', 'confirm', 'running'] and regestration.event_id.mail_auto_registr: subject = _('Auto Registration: [%s] %s') %(regestration.id, regestration.name) body = regestration.event_id.mail_registr if (regestration.event_id.state in ['confirm', 'running']) and regestration.event_id.mail_auto_confirm: subject = _('Auto Confirmation: [%s] %s') %(regestration.id, regestration.name) body = regestration.event_id.mail_confirm if subject or body: tools.email_send(src, email_to, subject, body, email_cc=email_cc, openobject_id=regestration.id) self.history(cr, uid, [regestration], subject, history = True, \ email=email_to, details=body, \ subject=subject, email_from=src, \ email_cc=', '.join(email_cc)) return True
def check_not_sync(self, cr, uid, context=None): entity_obj = self.pool.get('sync.server.entity') entity_activity_obj = self.pool.get('sync.server.entity.activity') date_tools = self.pool.get('date.tools') ids = self.search(cr, uid, [('name', '!=', False)]) if not ids: return False template = self.browse(cr, uid, ids[0]) thresold_date = (datetime.now() + timedelta(days=-template.nb_days)).strftime('%Y-%m-%d %H:%M:%S') entity_to_check_ids = entity_obj.search(cr, uid, [('state', 'in', ['validated', 'updated'])]) if not entity_to_check_ids: return False activity_ids = entity_activity_obj.search(cr, uid, [('entity_id', 'in', entity_to_check_ids), ('datetime', '<=', thresold_date)]) if not activity_ids: return False warn_ids = [] for act in entity_activity_obj.read(cr, uid, activity_ids, ['entity_id']): warn_ids.append(act['entity_id']) emails = template.name.split(',') subject = _('SYNC_SERVER: instances did not perform any sync') body = _('''Hello, The sync server detected that the following instances did not perform any sync since %d days: ''') % template.nb_days for entity in entity_obj.browse(cr, uid, warn_ids): body += _(" - %s last sync: %s\n") % (entity.name, entity.last_dateactivity and date_tools.get_date_formatted(cr, uid, 'datetime', entity.last_dateactivity) or _('never')) body += _("\n\nThis is an automatically generated email, please do not reply.\n") tools.email_send(False, emails, subject, body) return True
def request_send(self, cr, uid, ids, context={}): res = super( res_request, self ).request_send( cr, uid, ids, context ) eagle_param = self.__get_eagle_parameters( cr, uid, context=context ) if not eagle_param or not eagle_param.send_mail_with_request: netsvc.Logger().notifyChannel( 'addons.'+self._name, netsvc.LOG_DEBUG, "The request won't send any email because it's parameterized as is." ) return res if not tools.config.get('smtp_server'): netsvc.Logger().notifyChannel( 'addons.'+self._name, netsvc.LOG_DEBUG, "The request can't send any email because there's no stmp server defined..." ) return res for request in self.browse( cr, uid, ids ): if not request.send_mail: continue if not request.act_from.user_email: netsvc.Logger().notifyChannel( 'addons.'+self._name, netsvc.LOG_DEBUG, "The request '%s' can't send any email because there's no email defined for the sender..." % request.name ) continue if not request.act_to.user_email: netsvc.Logger().notifyChannel( 'addons.'+self._name, netsvc.LOG_DEBUG, "The request '%s' can't send any email because there's no email defined for the recipient..." % request.name ) continue netsvc.Logger().notifyChannel( 'addons.'+self._name, netsvc.LOG_DEBUG, "About to send an email to %s from %s with the following subject: %s" % (request.act_to.user_email,request.act_from.user_email,request.name) ) level = {'0': _('Low'),'1': _('Normal'),'2': _('High')}[request.priority] tools.email_send( email_from=request.act_from.user_email, email_to=[request.act_to.user_email], subject='['+level+'] '+request.name, body=request.body ) return res
def _check(self, cr, uid, context={}): req = cr.execute("SELECT DISTINCT email_alert FROM hr_employee WHERE email_alert is not null") mails = cr.dictfetchall(req) emails=[] for mail in mails: req = cr.execute("SELECT name, medic_exam, last_medic_exam, medic_exam_alert FROM hr_employee WHERE medic_exam_alert < NOW() and email_alert=%s",(mail['email_alert'],)) res = cr.dictfetchall(req) email=[] if res : email.append(mail['email_alert']) body="liste des visites médicales à passer\n" body+="-----------------------------------------------------------\n" body+="| date alerte | date visite | Nom\n" for line in res: body+="| "+line['medic_exam_alert']+" | "+line['medic_exam']+" | "+line['name']+"\n" body+="-----------------------------------------------------------\n" body+="Cette email a été envoyé par tinyerp sur :"+mail['email_alert']+"\n" email_from = "*****@*****.**" subject = "Alerte Visite Médicale" #print body email_cc= False email_bcc=False on_error=False reply_to=False attach=None tinycrm=False """Send an email.""" #print "Run medical exam Cron" tools.email_send(email_from, email, subject, body, email_cc=None, email_bcc=None, on_error=False, reply_to=False, tinycrm=False) return True
def _send_reminder(self, cr, uid, data, context): partner = data['form']['partner_id'][0][2] if partner: res = pooler.get_pool(cr.dbname).get('ecommerce.partner').browse(cr, uid, partner) for partner in res: if partner.address_ids and not partner.address_ids[0].email: not_sent.append(partner.name) for adr in partner.address_ids: if adr.email: sent_dict[partner.name] = adr.email name = adr.username or partner.name to = '%s <%s>' % (name, adr.email) mail_from = '*****@*****.**' attach_ids = pooler.get_pool(cr.dbname).get('ir.attachment').search(cr, uid, [('res_model', '=', 'ecommerce.shop'), ('res_id', '=', data['ids'][0])]) res_atc = pooler.get_pool(cr.dbname).get('ir.attachment').read(cr, uid, attach_ids, ['datas_fname', 'datas']) res_atc = map(lambda x: (x['datas_fname'], base64.decodestring(x['datas'])), res_atc) tools.email_send(mail_from, [to], data['form']['subject'], data['form']['message'], attach=res_atc) return 'finished'
def _mass_mail_send(self, cr, uid, data, context): nbr = 0 partners = pooler.get_pool(cr.dbname).get('res.partner').browse( cr, uid, data['ids'], context) for partner in partners: for adr in partner.address: if adr.email: name = adr.name or partner.name to = '%s <%s>' % (name, adr.email) #TODO: add some tests to check for invalid email addresses #CHECKME: maybe we should use res.partner/email_send tools.email_send(data['form']['from'], [to], data['form']['subject'], data['form']['text'], subtype='html') nbr += 1 pooler.get_pool(cr.dbname).get('res.partner.event').create( cr, uid, { 'name': 'Email sent through mass mailing', 'partner_id': partner.id, 'description': data['form']['text'], }) #TODO: log number of message sent return {'email_sent': nbr}
def _mass_mail_send(self, cr, uid, data, context): nbr = 0 partners = [] jobs = pooler.get_pool(cr.dbname).get('res.partner.job').browse(cr, uid, data['ids'], context) for job in jobs: if job.email: name = job.address_id.name or job.name.name to = '%s <%s>' % (name, job.email) #TODO: add some tests to check for invalid email addresses #CHECKME: maybe we should use res.partner/email_send res = tools.email_send(data['form']['from'], [to], data['form']['subject'], data['form']['text'], subtype='html') nbr += 1 elif job.address_id.email: name = job.address_id.name or job.name.name to = '%s <%s>' % (name, job.address_id.email) res = tools.email_send(data['form']['from'], [to], data['form']['subject'], data['form']['text'], subtype='html') nbr += 1 pooler.get_pool(cr.dbname).get('res.partner.event').create(cr, uid, {'name': 'Email sent through mass mailing from Job', 'partner_id': job.name and job.name.id or job.address_id.partner_id.id, 'description': data['form']['text'], }) partners.append(job.name and job.name.id or job.address_id.partner_id.id) data['form']['nbr'] = nbr data['form']['partners'] = partners if data['form']['event']: return 'open' return 'ok'
def _mass_mail_send(self, cr, uid, data, context): nbr = 0 partners = [] contacts = pooler.get_pool(cr.dbname).get('res.partner.contact').browse(cr, uid, data['ids'], context) for contact in contacts: # for adr in partner.address: if contact.email: name = contact.name or contact.partner_id.name to = '%s <%s>' % (name, contact.email) #TODO: add some tests to check for invalid email addresses #CHECKME: maybe we should use res.partner/email_send res = tools.email_send(data['form']['from'], [to], data['form']['subject'], data['form']['text'], subtype='html') nbr += 1 else: for adr in contact.partner_id.address: if adr.email: name = adr.name or partner.name to = '%s <%s>' % (name, adr.email) #TODO: add some tests to check for invalid email addresses #CHECKME: maybe we should use res.partner/email_send res = tools.email_send(data['form']['from'], [to], data['form']['subject'], data['form']['text'], subtype='html') nbr += 1 pooler.get_pool(cr.dbname).get('res.partner.event').create(cr, uid, {'name': 'Email sent through mass mailing From Contact', 'partner_id': contact.partner_id.id, 'description': data['form']['text'], }) partners.append(contact.partner_id.id) data['form']['partners'] = partners data['form']['nbr'] = nbr if data['form']['event']: return 'open' return 'ok'
def remind_user(self, cr, uid, ids, context=None, attach=False, destination=True): """ @param self: The object pointer @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param ids: List of case's IDs to remind @param context: A standard dictionary for contextual values """ for case in self.browse(cr, uid, ids, context=context): if not destination and not case.email_from: return False if not case.user_id.user_email: return False if destination and case.section_id.user_id: case_email = case.section_id.user_id.user_email else: case_email = case.user_id.user_email src = case_email dest = case.user_id body = case.description or "" if case.message_ids: body = case.message_ids[0].description or "" if not destination: src, dest = dest, case.email_from if body and case.user_id.signature: if body: body += "\n\n%s" % (case.user_id.signature) else: body = "\n\n%s" % (case.user_id.signature) body = self.format_body(body) attach_to_send = None if attach: attach_ids = self.pool.get("ir.attachment").search( cr, uid, [("res_model", "=", self._name), ("res_id", "=", case.id)] ) attach_to_send = self.pool.get("ir.attachment").read(cr, uid, attach_ids, ["datas_fname", "datas"]) attach_to_send = map(lambda x: (x["datas_fname"], base64.decodestring(x["datas"])), attach_to_send) # Send an email subject = "Reminder: [%s] %s" % (str(case.id), case.name) tools.email_send( src, [dest], subject, body, reply_to=case.section_id.reply_to or "", openobject_id=str(case.id), attach=attach_to_send, ) self._history( cr, uid, [case], _("Send"), history=True, subject=subject, email=dest, details=body, email_from=src ) return True
def _action(self, cr, uid, cases, state_to, scrit=None, context={}): super(crm_case, self)._action(cr, uid, cases, state_to, scrit=None, context={}) if not scrit: scrit = [] action_obj = self.pool.get('crm.case.rule') action_ids= action_obj.search(cr, uid, scrit) actions = self.pool.get('crm.case.rule').browse(cr, uid, action_ids, context) category={} cat_obj = self.pool.get('crm.bayes.categories') cat_rec = cat_obj.read(cr, uid, cat_obj.search(cr, uid, []),['name']) for cat in cat_rec: category[cat['name']] = cat['id'] for case in cases: for action in actions: if action.category_id == case.category_id: if action.action == "don't perform statistic test": break result_perform = self.guess_message(cr, uid, case.id, context) if action.action == "perform action only": if result_perform: res = max(result_perform, key=lambda k: k[1]) if res[1] >= action.main_category_rate: self.write(cr, uid, case.id, {'category_id':category[res[0]]}) elif action.sec_category_rate : sec_result = copy.deepcopy(result_perform) sec_result.pop(sec_result.index (max (result_perform, key=lambda k: k[1]))) if sec_result: re = max(sec_result, key=lambda k: k[1]) if re[1] <= action.main_category_rate and re[1] >= action.sec_category_rate: self.write(cr, uid, case.id, {'category_id':category[re[0]]}) elif action.action == "perform action and assign category" : if result_perform : max_list = max(result_perform, key=lambda k: k[1]) self.write(cr, uid, case.id, {'category_id':category[max_list[0]]}) cate = self.read(cr, uid, case.id, ['category_id']) if cate['category_id'] : a_ids = action_obj.search(cr, uid,[('category_id','=',cate['category_id'][0])]) action_rec = action_obj.browse(cr,uid,a_ids[0]) if action_rec: if action_rec.category_id.name == cate['category_id'][1] and case.email_from : emails = [] emails.append(case.email_from) if len(emails) and action_rec.act_mail_body: body = action_rec.act_mail_body if case.user_id and case.user_id.address_id and case.user_id.address_id.email: emailfrom = case.user_id.address_id.email else: emailfrom = case.section_id.reply_to name = '[%d] %s' % (case.id, case.name.encode('utf8')) reply_to = case.section_id.reply_to or False if reply_to: reply_to = reply_to.encode('utf8') if emailfrom: tools.email_send(emailfrom, emails, name, body, reply_to=reply_to, tinycrm=str(case.id)) break return True
def _create_user(self, cr, uid, data, context): pool = pooler.get_pool(cr.dbname) portal = pool.get("portal.portal").browse(cr, uid, data["form"]["portal_id"]) user_ref = pool.get("res.users") out = "login,password\n" skipped = 0 existing = "" created = "" for partner in pool.get("res.partner").browse(cr, uid, data["ids"]): for addr in partner.address: if not addr.email: skipped += 1 continue user = user_ref.search(cr, uid, [("login", "=", addr.email)]) if user: user = user_ref.browse(cr, uid, user[0]) existing += "- %s (Login: %s, Password: %s)\n" % (user.name, addr.email, user.password) mail = data["form"]["mail"] % {"login": addr.email, "passwd": user.password} if data["form"]["send_mail_existing"]: if not data["form"]["mail_from"]: raise wizard.except_wizard("Error !", 'Please provide a "from" email address.') tools.email_send( data["form"]["mail_from"], [addr.email], data["form"]["mail_subject_existing"], mail ) continue passwd = genpasswd() out += addr.email + "," + passwd + "\n" user_ref.create( cr, uid, { "name": addr.name or "Unknown", "login": addr.email, "password": passwd, "address_id": addr.id, "action_id": portal.home_action_id and portal.home_action_id.id or portal.menu_action_id.id, "menu_id": portal.menu_action_id.id, "groups_id": [(4, portal.group_id.id)], "company_id": portal.company_id.id, }, ) mail = data["form"]["mail"] % {"login": addr.email, "passwd": passwd} if data["form"]["send_mail"]: if not data["form"]["mail_from"]: raise wizard.except_wizard("Error !", 'Please provide a "from" email address.') tools.email_send(data["form"]["mail_from"], [addr.email], data["form"]["mail_subject"], mail) created += "- %s (Login: %s, Password: %s)\n" % (addr.name or "Unknown", addr.email, passwd) note = "" if created: note += "Created users:\n%s\n" % (created) if existing: note += "Already existing users:\n%s\n" % (existing) if skipped: note += "%d contacts where ignored (an email address is missing).\n" % (skipped) return {"note": note}
def button_done(self, cr, uid, ids, context): evaluation_obj = self.pool.get('hr.evaluation') setting_obj = self.pool.get('hr.evaluation.setting') answ_obj = pooler.get_pool(cr.dbname).get('hr.evaluation.values') eval_form_obj = self.pool.get('hr.evaluation.form') users_obj = self.pool.get('res.users') criteria_obj = self.pool.get('hr.evaluation.criteria') curr_employee = evaluation_obj.browse(cr, uid, ids)[0].employee_id setting_id = [] employee_obj = self.pool.get('hr.employee') employee_ids = employee_obj.search(cr, uid, [('parent_id', '=', curr_employee.id)]) mail_send = users_obj.browse(cr, uid, uid).address_id email_from = mail_send and mail_send.email or None subject = 'Notification for Evaluation' body = 'Please fill forms of evaluation!' employee_ids.append(curr_employee.id) if curr_employee.parent_id: employee_ids.append(curr_employee.parent_id.id) for evaluation in evaluation_obj.browse(cr, uid, ids): for employee in employee_obj.browse(cr, uid, employee_ids): ## ADdd criteria basing on products new_criteria_ids = [] prdct_id = employee.product_id.id if prdct_id: setting_id = setting_obj.search(cr, uid, [('product_id', '=', prdct_id)]) if setting_id: setting_ids = setting_obj.browse(cr, uid, setting_id) for set_id in setting_ids: for crit in set_id.criteria_ids: # new_criteria_ids.append(criteria_obj.copy(cr, uid, crit.id,{})) new_criteria_ids.append(crit.id) # for crit in curr_employee.grid_id.criteria_ids: # new_criteria_ids.append(criteria_obj.copy(cr, uid, crit.id,{'grid_id':False})) if not setting_id: raise osv.except_osv(_('Error'), _('Please set a job that defines setting to your employee "%s"!') % (employee.name or '')) mail_emp = self.browse(cr, uid, employee).user_id email_to = mail_emp and mail_emp.address_id and mail_emp.address_id.email or None if email_to: tools.email_send(email_from, email_to, subject, body, None) eval_id = eval_form_obj.create(cr, uid, { 'name': evaluation.name + ((evaluation.next_eval and'/' + evaluation.next_eval) or ''), 'employee_id': evaluation.employee_id.id, 'employee_id2': employee.id, 'eval_id': evaluation.id, 'state': 'draft', 'setting_id': setting_id and setting_id[0] or None, # 'criteria_ids':[(6,0, new_criteria_ids)] }, context) item = eval_form_obj.browse(cr, uid, eval_id) for crit in new_criteria_ids: answ_obj.create(cr, uid, {'employee_id': item.employee_id.id, 'criteria_id': crit, 'form_id': eval_id, }) self.write(cr, uid, ids, {'state': 'pending'}) return True
def send_mail(self, cr, uid, ids, context={}): hr_evaluation_obj = self.pool.get('hr_evaluation.evaluation') evaluation_data = self.read(cr, uid, ids, context=context)[0] for waiting_id in hr_evaluation_obj.browse(cr, uid, evaluation_data['evaluation_id'], context=context).survey_request_ids: if waiting_id.state == "waiting_answer" and waiting_id.user_to_review_id.work_email : msg = " Hello %s, \n\n Kindly post your response for %s survey. \n\n Thanks," %(waiting_id.user_to_review_id.name, waiting_id.survey_id.title) tools.email_send(tools.config['email_from'], [waiting_id.user_to_review_id.work_email],\ 'Reminder to fill up Survey', msg) return {'type': 'ir.actions.act_window_close'}
def send_mail(self, cr, uid, ids, context=None): hr_evaluation_interview_obj = self.pool.get('hr.evaluation.interview') evaluation_data = self.read(cr, uid, ids, context=context)[0] current_interview = hr_evaluation_interview_obj.browse(cr, uid, evaluation_data.get('evaluation_id')) if current_interview.state == "waiting_answer" and current_interview.user_to_review_id.work_email : msg = " Hello %s, \n\n Kindly post your response for '%s' survey interview. \n\n Thanks," %(current_interview.user_to_review_id.name, current_interview.survey_id.title) tools.email_send(tools.config['email_from'], [current_interview.user_to_review_id.work_email],\ 'Reminder to fill up Survey', msg) return {'type': 'ir.actions.act_window_close'}
def button_plan_in_progress(self, cr, uid, ids, context={}): apprai_id = [] for evaluation in self.browse(cr, uid, ids, context): wait = False for phase in evaluation.plan_id.phase_ids: childs = [] if phase.action == "bottom-up": childs = evaluation.employee_id.child_ids elif phase.action in ("top-down", "final"): if evaluation.employee_id.parent_id: childs = [evaluation.employee_id.parent_id] elif phase.action == "self": childs = [evaluation.employee_id] for child in childs: if not child.user_id: continue hr_eval_inter_obj = self.pool.get( 'hr.evaluation.interview') int_id = hr_eval_inter_obj.create( cr, uid, { 'evaluation_id': evaluation.id, 'survey_id': phase.survey_id.id, 'date_deadline': (dt.ISO.ParseAny(dt.now().strftime('%Y-%m-%d')) + dt.RelativeDateTime(months=+1) ).strftime('%Y-%m-%d'), 'user_id': child.user_id.id, 'user_to_review_id': evaluation.employee_id.id }, context=context) if phase.wait: wait = True if not wait: hr_eval_inter_obj.survey_req_waiting_answer( cr, uid, [int_id], context=context) if (not wait) and phase.mail_feature: body = phase.mail_body % { 'employee_name': child.name, 'user_signature': user.signature, 'eval_name': phase.survey_id.title, 'date': time.strftime('%Y-%m-%d'), 'time': time } sub = phase.email_subject dest = [child.work_email] if dest: tools.email_send(src, dest, sub, body) self.write(cr, uid, ids, {'state': 'wait'}, context=context) return True
def _send_notification_email(self, result): if not self.email: return tools.email_send( '*****@*****.**', self.email, self.get_email_subject(result), self.get_email_body(result), ) logger = logging.getLogger('import_sugarcam') logger.info("Import finished, notification email sended")
def button_plan_in_progress(self, cr, uid, ids, context=None): hr_eval_inter_obj = self.pool.get("hr.evaluation.interview") if context is None: context = {} for evaluation in self.browse(cr, uid, ids, context=context): wait = False for phase in evaluation.plan_id.phase_ids: children = [] if phase.action == "bottom-up": children = evaluation.employee_id.child_ids elif phase.action in ("top-down", "final"): if evaluation.employee_id.parent_id: children = [evaluation.employee_id.parent_id] elif phase.action == "self": children = [evaluation.employee_id] for child in children: # if not child.user_id: # continue int_id = hr_eval_inter_obj.create( cr, uid, { "evaluation_id": evaluation.id, "survey_id": phase.survey_id.id, "date_deadline": ( parser.parse(datetime.now().strftime("%Y-%m-%d")) + relativedelta(months=+1) ).strftime("%Y-%m-%d"), "user_id": child.user_id.id, "user_to_review_id": evaluation.employee_id.id, }, context=context, ) if phase.wait: wait = True if not wait: hr_eval_inter_obj.survey_req_waiting_answer(cr, uid, [int_id], context=context) if (not wait) and phase.mail_feature: body = phase.mail_body % { "employee_name": child.name, "user_signature": child.user_id.signature, "eval_name": phase.survey_id.title, "date": time.strftime("%Y-%m-%d"), "time": time, } sub = phase.email_subject dest = [child.work_email] if dest: tools.email_send(evaluation.employee_id.work_email, dest, sub, body) self.write(cr, uid, ids, {"state": "wait"}, context=context) return True
def send_mail_to_salesman(self, lead): email_to = lead.user_id and lead.user_id.user_email if not email_to: return email_from = lead.section_id and lead.section_id.user_id and lead.section_id.user_id.user_email or email_to partner = lead.partner_id and lead.partner_id.name or lead.partner_name subject = "lead %s converted into opportunity" % lead.name body = "Info \n Id : %s \n Subject: %s \n Partner: %s \n Description : %s " % (lead.id, lead.name, lead.partner_id.name, lead.description) try : tools.email_send(email_from, [email_to], subject, body) except: pass
def _send_mail(self, cr, uid, data, context): # Check of the first email address given by the user ptrn = re.compile('(\w+@\w+(?:\.\w+)+)') result=ptrn.search(data['form']['email_to']) if result==None: raise wizard.except_wizard('Error !', 'Enter Valid Destination E-Mail Address.') # Check of the first second email address given by the user ptrn = re.compile('(\w+@\w+(?:\.\w+)+)') result=ptrn.search(data['form']['email_rcp']) if result==None: raise wizard.except_wizard('Error !', 'Enter Valid Reception E-Mail Address.') # Determine the first and last date to select month=data['form']['month'] year=int(data['form']['year']) self.first_day=datetime.date(year,int(month),1) self.last_day=datetime.date(year,int(month),lengthmonth(year, int(month))) period="to_date('" + self.first_day.strftime('%Y-%m-%d') + "','yyyy-mm-dd') and to_date('" + self.last_day.strftime('%Y-%m-%d') +"','yyyy-mm-dd')" #determine the type of certificates to send certificate_type = data['form']['cert_type'] cancel_clause = not(data['form']['canceled']) and " and b.state not in ('cancel_customer','cancel_cci')" or '' query = 'select a.id from cci_missions_certificate as a, cci_missions_dossier as b where ( a.dossier_id = b.id ) and ( a.sending_spf is null ) and ( b.type_id = %s ) and ( b.date between %s )' + cancel_clause #Extraction of corresponding certificates cr.execute(query % (certificate_type,period)) res_file1=cr.fetchall() #If no records, cancel of the flow if res_file1==[]: raise wizard.except_wizard('Notification !', 'No Records Found to be sended. Check your criteria.') lines=[] root_path=tools.config.options['root_path'] if res_file1: lines=self.make_lines(cr, uid, res_file1, data ) self.write_txt(root_path+'/certificates.txt',lines) # Sending of the file as attachment files_attached=[] file1=tools.file_open(root_path+'/certificates.txt','rb',subdir=None) files_attached=[('certificates.txt',file1.read())] src = tools.config.options['smtp_user'] # parametre quand on lance le server ou dans bin\tools\config.py dest = [data['form']['email_to']] body = "Hello,\nHere are the certificates files for Federation.\nThink Big Use Tiny." tools.email_send(src,dest,"Federation Sending Files From TinyERP",body,attach=files_attached) pool = pooler.get_pool(cr.dbname) certificates_ids = [x[0] for x in res_file1] obj_certificate = pool.get('cci_missions.certificate') obj_certificate.write(cr, uid, certificates_ids,{'sending_spf':time.strftime('%Y-%m-%d')}) return {}
def send_mail(self, cr, uid, ids, context={}): hr_evaluation_obj = self.pool.get('hr_evaluation.evaluation') evaluation_data = self.read(cr, uid, ids, context=context)[0] for waiting_id in hr_evaluation_obj.browse( cr, uid, evaluation_data['evaluation_id'], context=context).survey_request_ids: if waiting_id.state == "waiting_answer" and waiting_id.user_to_review_id.work_email: msg = " Hello %s, \n\n Kindly post your response for %s survey. \n\n Thanks," % ( waiting_id.user_to_review_id.name, waiting_id.survey_id.title) tools.email_send(tools.config['email_from'], [waiting_id.user_to_review_id.work_email],\ 'Reminder to fill up Survey', msg) return {'type': 'ir.actions.act_window_close'}
def run_auto_import_temp_buste(self, cr, uid, automatic=False, use_new_cursor=False, context=None): pool = pooler.get_pool(cr.dbname) # import pdb;pdb.set_trace() testo_log = ( """Inizio procedura di Aggiornamento/Inserimento Varianti e Materie Prime su Template Buste """ + time.ctime() + "\n" ) percorso = "/home/openerp/filecsv" partner_obj = pool.get("buste.template.head") if use_new_cursor: cr = pooler.get_db(use_new_cursor).cursor() elenco_csv = os.listdir(percorso) for filecsv in elenco_csv: codfor = filecsv.split(".") testo_log = testo_log + " analizzo file " + codfor[0] + ".csv \n" lines = csv.reader(open(percorso + "/" + filecsv, "rb"), delimiter=";") if codfor[0].lower() == "varianti_buste_pz": # carica le varianti con i prezzi # import pdb;pdb.set_trace() res = self._import_dist_mat_prime(cr, uid, lines, "V", context) if codfor[0].lower() == "disbas_buste_pz": # lancia il metodo per le categorie indicate # import pdb;pdb.set_trace() res = self._import_dist_mat_prime(cr, uid, lines, "D", context) if res: testo_log = ( testo_log + " Inseriti " + str(res[0]) + " Aggiornati " + str(res[1]) + " MATERIE PRIME / VARIANTI \n" ) # import pdb;pdb.set_trace() testo_log = testo_log + str(res[2]) else: testo_log = testo_log + " File non riconosciuto " + codfor[0] + " non trovato \n" os.remove(percorso + "/" + filecsv) testo_log = testo_log + " Operazione Teminata alle " + time.ctime() + "\n" # invia e-mail type_ = "plain" tools.email_send( "*****@*****.**", ["*****@*****.**", "*****@*****.**"], "Import Automatico Varianti e o Materie Prime Buste", testo_log, subtype=type_, ) return True
def mail_user_confirm(self,cr,uid,ids): reg_ids=self.browse(cr,uid,ids) for reg_id in reg_ids: src = reg_id.event_id.reply_to or False if not reg_id.email_from: raise osv.except_osv(_('Warning!'), _('You should specify Partner Email for registration "%s" !')%(reg_id.name,)) dest = [reg_id.email_from] if reg_id.email_cc: dest += [reg_id.email_cc] if dest and src: tools.email_send(src, dest,'Auto Confirmation: '+'['+str(reg_id.id)+']'+' '+reg_id.name, reg_id.event_id.mail_confirm, tinycrm = str(reg_id.case_id.id)) if not src: raise osv.except_osv(_('Error!'), _('You must define a reply-to address in order to mail the participant. You can do this in the Mailing tab of your event. Note that this is also the place where you can configure your event to not send emails automaticly while registering')) return False
def running_expired_dates(self, cr, uid, *args): ref_case = pooler.get_pool(cr.dbname).get('crm.case') section_id=pooler.get_pool(cr.dbname).get('crm.case.section').search(cr, uid,[('code', '=', 'equip'),]) mail_admin='[email protected] ' cr.execute("""select distinct tool_id,tool_name,check_type,pdate,check_date,uid from ( select labo_tool.id as tool_id,labo_tool.name as tool_name, labo_intervention.id,check_in as check_type ,intervention_date as pdate, (case check_in when 'year' then intervention_date - interval '11 month' when 'month_6' then intervention_date - interval '5 month' when 'month_3' then intervention_date - interval '10 week' when 'month_2' then intervention_date - interval '6 week' when 'month_1' then intervention_date - interval '3 week' when 'weekly' then intervention_date - interval '6 day' else intervention_date End) as check_date, user_id as uid ,'Intervention' as cType from labo_intervention inner join labo_tool on labo_tool.id = labo_intervention.intervention_id union all select labo_tool.id as tool_id,labo_tool.name as tool_name, labo_log.id,check_in as check_type ,planified_date as pdate, (case check_in when 'year' then planified_date - interval '11 month' when 'month_6' then planified_date - interval '5 month' when 'month_3' then planified_date - interval '3 month' when 'month_2' then planified_date - interval '2 month' when 'month_1' then planified_date - interval '1 month' when 'weekly' then planified_date - interval '6 day' else null End) as check_date, user_id as uid,'Maintenance' as cType from labo_log inner join labo_tool on labo_tool.id = labo_log.log_id ) as tmpTable where tmpTable.check_date = current_date """) res = cr.dictfetchall() for r in res: partner_id= pooler.get_pool(cr.dbname).get('res.users').browse(cr, uid, [r['uid']]) new_id=ref_case.create(cr,uid,{ 'name': "Equipment to review", 'section_id':section_id[0], 'state': 'open', 'active':True, 'partner_id':partner_id[0].company_id.partner_id.id, 'description': "Please check your reagents: " +" "+ r['tool_name'] + " for the next intervention or calibrating on " + r['check_date'][:10], 'user_id':partner_id[0].id, }) if partner_id[0].address_id and partner_id[0].address_id.email: tools.email_send('*****@*****.**',partner_id[0].address_id.email ,'Checking equipments', " for the next intervention or calibrating on " + r['check_date'], '*****@*****.**', mail_admin, tinycrm=new_id) return True
def remind_user(self, cr, uid, ids, context=None, attach=False, destination=True): """ @param self: The object pointer @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param ids: List of Remind user's IDs @param context: A standard dictionary for contextual values """ for case in self.browse(cr, uid, ids, context=context): if not case.section_id.reply_to: raise osv.except_osv(_('Error!'), ("Reply To is not specified in the sales team")) if not case.email_from: raise osv.except_osv(_('Error!'), ("Partner Email is not specified in Case")) if case.section_id.reply_to and case.email_from: src = case.email_from dest = case.section_id.reply_to body = case.description or "" if case.message_ids: body = case.message_ids[0].description or "" if not destination: src, dest = dest, src if body and case.user_id.signature: if body: body += '\n\n%s' % (case.user_id.signature) else: body = '\n\n%s' % (case.user_id.signature) body = self.format_body(body) attach_to_send = None if attach: attach_ids = self.pool.get('ir.attachment').search(cr, uid, [('res_model', '=', self._name), ('res_id', '=', case.id)]) attach_to_send = self.pool.get('ir.attachment').read(cr, uid, attach_ids, ['datas_fname','datas']) attach_to_send = map(lambda x: (x['datas_fname'], base64.decodestring(x['datas'])), attach_to_send) # Send an email subject = "Reminder: [%s] %s" % (str(case.id), case.name, ) tools.email_send( src, [dest], subject, body, reply_to=case.section_id.reply_to, openobject_id=str(case.id), attach=attach_to_send ) self._history(cr, uid, [case], _('Send'), history=True, subject=subject, email=dest, details=body, email_from=src) return True
def email_send(self, cr, uid, case, emails, body, context={}): body = self.format_mail(case, body) if case.user_id and case.user_id.email: emailfrom = case.user_id.email else: emailfrom = case.section_id.reply_to name = '[%d] %s' % (case.id, case.name.encode('utf8')) reply_to = case.section_id.reply_to or False if reply_to: reply_to = reply_to.encode('utf8') if not emailfrom: raise osv.except_osv(_('Error!'), _("No E-Mail ID Found for your Company address or missing reply address in section!")) tools.email_send(emailfrom, emails, name, body, reply_to=reply_to, tinycrm=str(case.id)) return True
def button_send_scrum_email(self, cr, uid, ids, context=None): if context is None: context = {} active_id = context.get('active_id', False) scrum_meeting_pool = self.pool.get('project.scrum.meeting') user_pool = self.pool.get('res.users') meeting = scrum_meeting_pool.browse(cr, uid, active_id, context=context) # wizard data data_id = ids and ids[0] or False if not data_id or not active_id: return False data = self.browse(cr, uid, data_id, context=context) email_from = tools.config.get('email_from', False) user = user_pool.browse(cr, uid, uid, context=context) #BUG in v7 address_id does not exit, today its alias_id but we don't find address in the db user_email = email_from or user.alias_id.email body = "%s\n" % (data.message) body += "\n%s\n" % _('Tasks since yesterday') body += "_______________________\n" body += "\n%s\n" % (meeting.question_yesterday or _('None')) body += "\n%s\n" % _("Task for Today") body += "_______________________ \n" body += "\n%s\n" % (meeting.question_today or _('None')) body += "\n%s\n" % _('Blocking points encountered:') body += "_______________________ \n" body += "\n%s\n" % (meeting.question_blocks or _('None')) body += "\n%s\n%s" % (_('Thank you,'), user.name) if user.signature: body += "\n%s" % (user.signature) if data.scrum_master_email == data.product_owner_email: data.product_owner_email = False if data.scrum_master_email: tools.email_send(user_email, [data.scrum_master_email], data.subject, body, reply_to=user_email) if data.product_owner_email: tools.email_send(user_email, [data.product_owner_email], data.subject, body, reply_to=user_email) return {'type': 'ir.actions.act_window_close'}
def cont_effetti(self,cr,uid,ids,context): # Contabilizza effetti ancora contabilizzati #import pdb;pdb.set_trace() if ids: param = self.browse(cr,uid,ids)[0] cerca = [ ('data_documento','<=',param.to_date_doc), ('registrazione','=',None), ] ids_docs = self.pool.get('effetti.scadenze').search(cr,uid,cerca,order='name,data_documento,numero_doc') testo_log = """Inizio procedura Contabilizzazione Effetti """ + time.ctime() + '\n' if ids_docs: testo_log = """Inizio procedura Contabilizzazione Effetti """ + time.ctime() + '\n' ids_eff=[] for rsca in self.pool.get('effetti.scadenze').browse(cr,uid,ids_docs): if rsca.name.id in ids_eff: pass else: ids_eff.append(rsca.name.id) if not ids_eff: raise osv.except_osv(_('ERRORE !'), _('NON CI SONO DOCUMENTI PER I PARAMETRI INDICATI ')) # testo_log += """Causale Documento """ +doc.tipo_doc.name +" SENZA CAUSALE CONTABILE " + '\n' + " Documento "+ doc.name + " NON CONTABILIZZATO "+ '\n' else: for doc in self.pool.get('effetti').browse(cr,uid,ids_eff): scritto = self.scrive_reg(cr, uid, doc,param,context) testo_log += scritto[0] # TO DO INCASSO CONTESTUALE PER IMPORTO ACCONTO MOVIMENTATO else: #testo_log = """NON CI SONO DICUMENTI PER I PARAMETRI INDICATI """ + time.ctime() + '\n' raise osv.except_osv(_('ERRORE !'), _('NON CI SONO DOCUMENTI PER I PARAMETRI INDICATI ')) testo_log = testo_log + " Operazione Teminata alle " + time.ctime() + "\n" #invia e-mail user = self.pool.get('res.users').browse(cr,uid,uid) #import pdb;pdb.set_trace() if user.user_email: type_ = 'plain' tools.email_send('*****@*****.**', [user.user_email], # QUA DEVE ESSERCI L'EMAIL DEL CODICE UTENTE DEVI ANCHE ATTIVARE LA MESSAGGISTICA INTERNA DEGLI ESITI 'Esito Contabilizzazione Effetti', testo_log, subtype=type_, ) return {'type': 'ir.actions.act_window_close'}
def email_send(self, cr, uid, obj, emails, body, emailfrom=None, context=None): """ send email @param self: The object pointer @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param email: pass the emails @param emailfrom: Pass name the email From else False @param context: A standard dictionary for contextual values """ if not emailfrom: emailfrom = tools.config.get('email_from', False) if context is None: context = {} body = self.format_mail(obj, body) if not emailfrom: if hasattr(obj, 'user_id') and obj.user_id and obj.user_id.address_id and\ obj.user_id.address_id.email: emailfrom = obj.user_id.address_id.email name = '[%d] %s' % (obj.id, tools.ustr(obj.name)) emailfrom = tools.ustr(emailfrom) reply_to = emailfrom if not emailfrom: raise osv.except_osv(_('Error!'), _("No E-Mail ID Found for your Company address!")) return tools.email_send(emailfrom, emails, name, body, reply_to=reply_to, openobject_id=str(obj.id))
def send_mail(self, to_address, subject, body, attach=None): sent = tools.email_send(config['email_from'], to_address, subject, body, attach=attach, ssl=True) logger = netsvc.Logger() if not sent: logger.notifyChannel('email', netsvc.LOG_ERROR, 'Failed to send email to : %s' % (to_address)) else: logger.notifyChannel('email', netsvc.LOG_INFO, 'Email successfully send to : %s' % (to_address))
def email_send(self, cr, uid, ids, email, context=None): email_from = tools.config.get('email_from', False) meeting_id = self.browse(cr, uid, ids, context=context)[0] user = self.pool.get('res.users').browse(cr, uid, uid, context=context) user_email = email_from or user.address_id.email or email_from body = _( 'Hello ' ) + meeting_id.sprint_id.scrum_master_id.name + ",\n" + " \n" + _( 'I am sending you Daily Meeting Details of date') + ' %s ' % ( meeting_id.date) + _( 'for the Sprint') + ' %s\n' % (meeting_id.sprint_id.name) body += "\n" + _( '*Tasks since yesterday:') + '\n_______________________%s' % ( meeting_id.question_yesterday) + '\n' + _( "*Task for Today:") + '\n_______________________ %s\n' % ( meeting_id.question_today) + '\n' + _( '*Blocks encountered:' ) + '\n_______________________ %s' % ( meeting_id.question_blocks or _('No Blocks')) body += "\n\n" + _('Thank you') + ",\n" + user.name sub_name = meeting_id.name or _( 'Scrum Meeting of %s') % meeting_id.date flag = tools.email_send(user_email, [email], sub_name, body, reply_to=None, openobject_id=str(meeting_id.id)) if not flag: return False return True
def send_emails(self, cr, uid, ids, context=None): user = self.pool.get('res.users').browse(cr, uid, uid, context=context) if not user.user_email: raise osv.except_osv(_('Email required'), _('The current user must have an email address configured in User Preferences to be able to send outgoing emails.')) for wizard_data in self.browse(cr, uid, ids, context=context): for result_line in wizard_data.result_line_ids: email_to = result_line.login subject = _('%s has shared OpenERP %s information with you') % (user.name, wizard_data.action_id.name) body = _("Dear,\n\n") + subject + "\n\n" body += _("To access it, you can go to the following URL:\n %s") % result_line.share_url body += "\n\n" if result_line.newly_created: body += _("You may use the following login and password to get access to this protected area:") + "\n" body += "%s: %s" % (_("Username"), result_line.login) + "\n" body += "%s: %s" % (_("Password"), result_line.password) + "\n" body += "%s: %s" % (_("Database"), cr.dbname) + "\n" else: body += _("This additional data has been automatically added to your current access.\n") body += _("You may use your existing login and password to view it. As a reminder, your login is %s.\n") % result_line.login if not tools.email_send( user.user_email, [email_to], subject, body): self.__logger.warning('Failed to send sharing email from %s to %s', user.user_email, email_to) return {'type': 'ir.actions.act_window_close'}
def _sendemail(self, cr, uid, data, context): pool = pooler.get_pool(cr.dbname) mail_from = data['form']['email_from'] or False if not mail_from: mail_from = pool.get('res.users').browse(cr, uid, [uid], context)[0].address_id.email count_reg = 0 message = '' for reg in pool.get('event.registration').browse(cr, uid, data['ids'], context): to = reg.email_from or reg.contact_id.email or False if to: res = tools.email_send(mail_from, [to], data['form']['subject'], data['form']['body']) if res: count_reg += 1 else: message += '''Error: Mail not sent, Partner %s does not have a valid address mail on Registration ID: %s \n''' % ( reg.partner_id.name, reg.id) else: message += '''Error: Mail not sent, Partner %s does not have a email available on Registration ID: %s \n''' % ( reg.partner_id.name, reg.id) count_msg = '''%s mails have been successfully sent\n''' % (count_reg) message = count_msg + message return {'message': message}
def _sms_send(cr, uid, data, context, adr): import re # change the [[field]] tags with the partner address values pattern = re.compile('\[\[\S+\]\]') fields = pattern.findall(data['form']['text']) texts = [] for field in fields: text = getattr(adr, field[2:-2]) if text and field[-5:-2] == '_id': # State or country text = text.name texts.append(text or '') sms = pattern.sub('%s', data['form']['text']) sms = sms % tuple(texts) #print sms to = adr.mobile to = to.replace(' ', '') if adr.country_id and adr.country_id.code in ( 'ES', 'CT') and to[:1] == '6': # Spain mobiles begin with 6 to = '34' + to sms = ' '.join(sms.split('\n')) # Conversion of '\n' to ' ' is necessary sms_sent = unicode(sms, 'utf-8').encode('latin1') if data['form']['email_http']: # Connection by Email text = 'user:'******'form']['user'] + '\npassword:'******'form'][ 'password'] + '\napi_id:' + data['form'][ 'app_id'] + '\nto:' + to + '\ntext:' + sms_sent #print text tools.email_send(data['form']['email'], ['*****@*****.**'], '', text) else: # Connection by http tools.sms_send(data['form']['user'], data['form']['password'], data['form']['app_id'], sms_sent, to) # Add a partner event c_id = pooler.get_pool(cr.dbname).get('res.partner.canal').search( cr, uid, [('name', 'ilike', 'SMS'), ('active', '=', True)]) c_id = c_id and c_id[0] or False pooler.get_pool(cr.dbname).get('res.partner.event').create( cr, uid, { 'name': 'SMS sent to ' + adr.mobile, 'partner_id': adr.partner_id.id, 'description': sms, 'canal_id': c_id, 'user_id': uid, })
def mail_user(self, cr, uid, ids, confirm=False, context=None): """ Send email to user """ for regestration in self.browse(cr, uid, ids, context=context): src = regestration.event_id.reply_to or False email_to = [] email_cc = [] if regestration.email_from: email_to = regestration.email_from if regestration.email_cc: email_cc += [regestration.email_cc] if not (email_to or email_cc): continue subject = "" body = "" if confirm: subject = _('Auto Confirmation: [%s] %s') % (regestration.id, regestration.name) body = regestration.event_id.mail_confirm elif regestration.event_id.mail_auto_confirm or regestration.event_id.mail_auto_registr: if regestration.event_id.state in [ 'draft', 'fixed', 'open', 'confirm', 'running' ] and regestration.event_id.mail_auto_registr: subject = _('Auto Registration: [%s] %s') % ( regestration.id, regestration.name) body = regestration.event_id.mail_registr if (regestration.event_id.state in [ 'confirm', 'running' ]) and regestration.event_id.mail_auto_confirm: subject = _('Auto Confirmation: [%s] %s') % ( regestration.id, regestration.name) body = regestration.event_id.mail_confirm if subject or body: tools.email_send(src, email_to, subject, body, email_cc=email_cc, openobject_id=regestration.id) self.history(cr, uid, [regestration], subject, history = True, \ email=email_to, details=body, \ subject=subject, email_from=src, \ email_cc=', '.join(email_cc)) return True
def _check(self, cr, uid, context={}): req = cr.execute( "SELECT DISTINCT email_alert FROM hr_employee WHERE email_alert is not null" ) mails = cr.dictfetchall(req) emails = [] for mail in mails: req = cr.execute( "SELECT name, medic_exam, last_medic_exam, medic_exam_alert FROM hr_employee WHERE medic_exam_alert < NOW() and email_alert=%s", (mail['email_alert'], )) res = cr.dictfetchall(req) email = [] if res: email.append(mail['email_alert']) body = "liste des visites médicales à passer\n" body += "-----------------------------------------------------------\n" body += "| date alerte | date visite | Nom\n" for line in res: body += "| " + line['medic_exam_alert'] + " | " + line[ 'medic_exam'] + " | " + line['name'] + "\n" body += "-----------------------------------------------------------\n" body += "Cette email a été envoyé par tinyerp sur :" + mail[ 'email_alert'] + "\n" email_from = "*****@*****.**" subject = "Alerte Visite Médicale" #print body email_cc = False email_bcc = False on_error = False reply_to = False attach = None tinycrm = False """Send an email.""" #print "Run medical exam Cron" tools.email_send(email_from, email, subject, body, email_cc=None, email_bcc=None, on_error=False, reply_to=False, tinycrm=False) return True
def mass_mail_send(self, cr, uid, ids, context): """ Send Email @param cr: the current row, from the database cursor. @param uid: the current user’s ID for security checks. @param ids: the ID or list of IDs @param context: A standard dictionary """ nbr = 0 partner_pool = self.pool.get('res.partner') data = self.browse(cr, uid, ids[0], context=context) event_pool = self.pool.get('res.partner.event') active_ids = context and context.get('active_ids', []) partners = partner_pool.browse(cr, uid, active_ids, context) type_ = 'plain' if re.search('(<(pre)|[pubi].*>)', data.text): type_ = 'html' for partner in partners: for adr in partner.address: if adr.email: name = adr.name or partner.name to = '"%s" <%s>' % (name, adr.email) #TODO: add some tests to check for invalid email addresses #CHECKME: maybe we should use res.partner/email_send tools.email_send(data.email_from, [to], data.subject, data.text, subtype=type_, openobject_id="res.partner-%s" % partner.id) nbr += 1 event_pool.create( cr, uid, { 'name': 'Email(s) sent through mass mailing', 'partner_id': partner.id, 'description': data.text }) #TODO: log number of message sent return {'email_sent': nbr}
def _mass_mail_send(self, cr, uid, data, context): nbr = 0 partners = [] contacts = pooler.get_pool(cr.dbname).get('res.partner.contact').browse( cr, uid, data['ids'], context) for contact in contacts: # for adr in partner.address: if contact.email: name = contact.name or contact.partner_id.name to = '%s <%s>' % (name, contact.email) #TODO: add some tests to check for invalid email addresses #CHECKME: maybe we should use res.partner/email_send res = tools.email_send(data['form']['from'], [to], data['form']['subject'], data['form']['text'], subtype='html') nbr += 1 else: for adr in contact.partner_id.address: if adr.email: name = adr.name or partner.name to = '%s <%s>' % (name, adr.email) #TODO: add some tests to check for invalid email addresses #CHECKME: maybe we should use res.partner/email_send res = tools.email_send(data['form']['from'], [to], data['form']['subject'], data['form']['text'], subtype='html') nbr += 1 pooler.get_pool(cr.dbname).get('res.partner.event').create( cr, uid, { 'name': 'Email sent through mass mailing From Contact', 'partner_id': contact.partner_id.id, 'description': data['form']['text'], }) partners.append(contact.partner_id.id) data['form']['partners'] = partners data['form']['nbr'] = nbr if data['form']['event']: return 'open' return 'ok'
def _mass_mail_send(self, cr, uid, data, context): nbr = 0 partners = [] jobs = pooler.get_pool(cr.dbname).get('res.partner.job').browse( cr, uid, data['ids'], context) for job in jobs: if job.email: name = job.address_id.name or job.name.name to = '%s <%s>' % (name, job.email) #TODO: add some tests to check for invalid email addresses #CHECKME: maybe we should use res.partner/email_send res = tools.email_send(data['form']['from'], [to], data['form']['subject'], data['form']['text'], subtype='html') nbr += 1 elif job.address_id.email: name = job.address_id.name or job.name.name to = '%s <%s>' % (name, job.address_id.email) res = tools.email_send(data['form']['from'], [to], data['form']['subject'], data['form']['text'], subtype='html') nbr += 1 pooler.get_pool(cr.dbname).get('res.partner.event').create( cr, uid, { 'name': 'Email sent through mass mailing from Job', 'partner_id': job.name and job.name.id or job.address_id.partner_id.id, 'description': data['form']['text'], }) partners.append(job.name and job.name.id or job.address_id.partner_id.id) data['form']['nbr'] = nbr data['form']['partners'] = partners if data['form']['event']: return 'open' return 'ok'
def send_mail(self, to_address, subject, body, attach=None): sent = tools.email_send(config['email_from'], to_address, subject, body, attach=attach, ssl=True) logger = netsvc.Logger() if not sent: logger.notifyChannel('email', netsvc.LOG_ERROR, 'Failed to send email to : %s' % (to_address)) else: logger.notifyChannel( 'email', netsvc.LOG_INFO, 'Email successfully send to : %s' % (to_address))
def email_send(self, cr, uid, obj, emails, body, emailfrom=tools.config.get('email_from', False), context=None): body = self.format_mail(obj, body) if not emailfrom: if hasattr(obj, 'user_id') and obj.user_id and obj.user_id.address_id and obj.user_id.address_id.email: emailfrom = obj.user_id.address_id.email name = '[%d] %s' % (obj.id, tools.ustr(obj.name)) emailfrom = tools.ustr(emailfrom) if hasattr(obj, 'section_id') and obj.section_id and obj.section_id.reply_to: reply_to = obj.section_id.reply_to else: reply_to = emailfrom if not emailfrom: raise osv.except_osv(_('Error!'), _("No E-Mail ID Found for your Company address!")) return tools.email_send(emailfrom, emails, name, body, reply_to=reply_to, openobject_id=str(obj.id))
def action_open(self, cr, uid, ids, context={}): self.write(cr, uid, ids, {'state': 'open'}) # TODO create a link to feedback to send it in the body of the mail to the user feedback_lines = self.browse(cr, uid, ids) # send mail to the user for feedback for feedback_line in feedback_lines: subject = feedback_line['name'] user = tools.config['email_from'] if not user: raise osv.except_osv( _('Error'), _("Please specify server option --smtp-from !")) if feedback_line.user_to.address_id and feedback_line.user_to.address_id.email: open_feedback_user_action_id = self.pool.get( 'ir.model.data').search( cr, uid, [('name', '=', 'action_view_open_related_user_ctg_feedback')]) open_feedback_user_action_obj = self.pool.get( 'ir.model.data').browse(cr, uid, open_feedback_user_action_id, context)[0] self.pool.get('res.users').write( cr, uid, [feedback_line.user_to.id], {'action_id': open_feedback_user_action_obj.res_id}) mail_to = feedback_line.user_to.address_id.email body = 'Hello %s,\n %s %s.\n %s' % ( feedback_line.user_to.name, feedback_msg, feedback_line['name'], feedback_link) logger = netsvc.Logger() if tools.email_send(user, [mail_to], subject, body, debug=False, subtype='html') == True: logger.notifyChannel( 'email', netsvc.LOG_INFO, 'Email successfully send to : %s' % (mail_to)) date = feedback_line.date_feedback or datetime.date.today() usr_id = feedback_line.user_to.id feedback_id = feedback_line.id #self.pool.get('user.history').create(cr,uid,{'action':'feedback', 'description':subject, 'feedback_id':feedback_line.id,'date':date, 'user_id':usr_id}) else: logger.notifyChannel( 'email', netsvc.LOG_ERROR, 'Failed to send email to : %s' % (mail_to)) return True
def send_welcome_email(self, cr, uid, id, context=None): logger = logging.getLogger('mails') user = self.pool.get('res.users').read(cr, uid, id, context=context) if not tools.config.get('smtp_server'): logger.warning(_('"smtp_server" needs to be set to send mails to users')) return False if not tools.config.get('email_from'): logger.warning(_('"email_from" needs to be set to send welcome mails ' 'to users')) return False if not user.get('email'): return False return tools.email_send(email_from=None, email_to=[user['email']], subject=self.get_welcome_mail_subject( cr, uid, context=context), body=self.get_welcome_mail_body( cr, uid, context=context) % user)
def _send_by_email(self, cr, uid, export_file, localdict): email_to = _render_unicode(export_file.email_to, localdict) email_subject = _render_unicode(export_file.email_subject, localdict) email_body = _render_unicode(export_file.email_body, localdict) email_cc = _render_unicode(export_file.email_cc, localdict) attachments = [] context = localdict.get('localcontext', {}) export = self.pool.get('ir.model.export').browse( cr, uid, context.get('attach_export_id', 0), context) if export_file.email_attach_export_file: attachments.append((localdict['filename'], localdict['file'])) if export_file.exception_logging == 'file' and export_file.email_attach_exceptions_file: attachments.append( (export.exceptions_filename, export.exceptions_file)) return tools.email_send(False, email_to, email_subject, email_body, email_cc, attach=attachments)
def send_emails(self, cr, uid, ids, context=None): user = self.pool.get('res.users').browse(cr, uid, uid, context=context) if not user.user_email: raise osv.except_osv( _('Email required'), _('The current user must have an email address configured in User Preferences to be able to send outgoing emails.' )) for wizard_data in self.browse(cr, uid, ids, context=context): for result_line in wizard_data.result_line_ids: email_to = result_line.login subject = _('%s has shared OpenERP %s information with you' ) % (user.name, wizard_data.action_id.name) body = _("Dear,\n\n") + subject + "\n\n" body += _( "To access it, you can go to the following URL:\n %s" ) % result_line.share_url body += "\n\n" if result_line.newly_created: body += _( "You may use the following login and password to get access to this protected area:" ) + "\n" body += "%s: %s" % (_("Username"), result_line.login) + "\n" body += "%s: %s" % (_("Password"), result_line.password) + "\n" body += "%s: %s" % (_("Database"), cr.dbname) + "\n" else: body += _( "This additional data has been automatically added to your current access.\n" ) body += _( "You may use your existing login and password to view it. As a reminder, your login is %s.\n" ) % result_line.login if not tools.email_send(user.user_email, [email_to], subject, body): self.__logger.warning( 'Failed to send sharing email from %s to %s', user.user_email, email_to) return {'type': 'ir.actions.act_window_close'}
def send_welcome_email(self, cr, uid, id, context=None): logger = netsvc.Logger() user = self.pool.get('res.users').read(cr, uid, id, context=context) if not tools.config.get('smtp_server'): logger.notifyChannel( 'mails', netsvc.LOG_WARNING, _('"smtp_server" needs to be set to send mails to users')) return False if not tools.config.get('email_from'): logger.notifyChannel( "mails", netsvc.LOG_WARNING, _('"email_from" needs to be set to send welcome mails ' 'to users')) return False if not user.get('email'): return False return tools.email_send( email_from=None, email_to=[user['email']], subject=self.get_welcome_mail_subject(cr, uid, context=context), body=self.get_welcome_mail_body(cr, uid, context=context) % user)