Exemple #1
0
def send_email(share_info, profile_id, disease):
	from email.mime.audio import MIMEAudio
	from email.mime.base import MIMEBase
	from email.mime.image import MIMEImage
	from email.mime.text import MIMEText
	import mimetypes
	import datetime

	attachments = []
	file_name = disease + '.pdf'
	files = os.path.join(get_files_path(), profile_id, file_name)

	attachments.append({
			"fname": files,
			"fcontent": file(files).read()
		})

	if attachments:
		msg = """Disease Name is %(event)s <br>
				Provider Name is %(provider_name)s <br>
				<hr>
					%(event_body)s <br>
					Please see attachment <br>
			"""%{'event': disease, 'provider_name': share_info.get('doctor_name'), 
			'event_body': share_info.get('email_body')}
		
		from frappe.utils.email_lib import sendmail

		sendmail([share_info.get('email_id')], subject="PHR-Disease Monitoring Data", msg=cstr(msg),
				attachments=attachments)

		make_log(profile_id, "Disease Monitoring", "Shared Via Email to provider %s"% share_info.get('doctor_name') , "DM of <b style='color: #89c148;'>%s</b> Shared Via Email to provider %s"%(disease,share_info.get('doctor_name')))
		return {"returncode":1,"message_display":"Disease Monitoring records has been shared"}
Exemple #2
0
    def make_so(self, order_no):
        child_table = self.getchild_table()

        body = "<html><body><table wisth='100%''><tr><td>Customer Name</td><td>" + self.customer_name + "</td><td>Contact </td><td>" + self.email_id + "</td></tr><tr><td>From Date</td><td>" + self.from_date + "</td><td>To Date </td><td>" + self.to_date + "</td></tr><tr><td>Currency</td><td>" + self.currency + "</td><td>Order No </td><td>" + order_no + "</td></tr></table><table style='100%'>" + child_table + "</table></body></html>"
        sendmail(self.email_id, subject='Sales Order', msg=body)
        frappe.msgprint("Send Successfully")
        return True
Exemple #3
0
	def make_so(self, order_no):
		child_table = self.getchild_table()

		body= "<html><body><table wisth='100%''><tr><td>Customer Name</td><td>"+self.customer_name+"</td><td>Contact </td><td>"+self.email_id+"</td></tr><tr><td>From Date</td><td>"+self.from_date+"</td><td>To Date </td><td>"+self.to_date+"</td></tr><tr><td>Currency</td><td>"+self.currency+"</td><td>Order No </td><td>"+order_no+"</td></tr></table><table style='100%'>"+child_table+"</table></body></html>"
		sendmail(self.email_id,subject='Sales Order',msg=body)
		frappe.msgprint("Send Successfully")
		return True
Exemple #4
0
    def send_email(self):
        """
			Sends the link to backup file located at erpnext/backups
		"""
        from frappe.utils.email_lib import sendmail, get_system_managers

        recipient_list = get_system_managers()
        db_backup_url = get_url(
            os.path.join('backups', os.path.basename(self.backup_path_db)))
        files_backup_url = get_url(
            os.path.join('backups', os.path.basename(self.backup_path_files)))

        msg = """Hello,

Your backups are ready to be downloaded.

1. [Click here to download the database backup](%(db_backup_url)s)
2. [Click here to download the files backup](%(files_backup_url)s)

This link will be valid for 24 hours. A new backup will be available for
download only after 24 hours.""" % {
            "db_backup_url": db_backup_url,
            "files_backup_url": files_backup_url
        }

        datetime_str = datetime.fromtimestamp(
            os.stat(self.backup_path_db).st_ctime)
        subject = datetime_str.strftime(
            "%d/%m/%Y %H:%M:%S") + """ - Backup ready to be downloaded"""

        sendmail(recipients=recipient_list, msg=msg, subject=subject)
        return recipient_list
Exemple #5
0
def share_via_email(data):
	attachments = []
	files = data.get('files')
	patient_name = frappe.db.get_value("User", {"profile_id":data.get('profile_id')}, 'concat(first_name, " ", last_name)') or  data.get('lphr_name')
	for fl in files:
		fname = os.path.join(get_files_path(), fl)
		attachments.append({
				"fname": fname.split('/')[-1:][0],
				"fcontent": file(fname).read()
			})

	if attachments:
		msg = """Event Name is %(event)s <br>
				Event Date is %(event_date)s <br>
				Provider Name is %(provider_name)s <br>
				Sharing reason is %(reason)s <br>
				<hr>
					%(event_body)s <br>
					Please find below attachment(s) <br>
			"""%{'event': data.get('event_title'), 'event_date': data.get('event_date') or data.get("str_visit_date"), 
				'provider_name': data.get('doctor_name'), 'event_body': data.get('email_body'), 'reason': data.get('reason')}
		
		from frappe.utils.email_lib import sendmail

		sendmail([data.get('email_id')], subject="PHR-Event Data", msg=cstr(msg),
				attachments=attachments)

		make_log(data.get('profile_id'),"Event","Shared Via Email","Event <b style='color: #89c148;'>%s</b> Shared Via Email %s"%(data.get('event_title'), data.get('email_id')))
		# args = {"patient":patient_name,"email":data.get('email_id')}
		# notify_provider(data.get('doctor_id'),data.get('profile_id'),"Event Share Email",args)
		return { "returncode":1,"message_summary":"Selected image(s) has been shared with %(provider_name)s for event %(event)s "%{'event': data.get('event_title'),'provider_name': data.get('doctor_name')}}
	else:
		return {"returncode":0,"message_summary":"Please select file(s) for sharing"}
Exemple #6
0
	def send_email(self):
		"""
			Sends the link to backup file located at erpnext/backups
		"""
		from frappe.utils.email_lib import sendmail, get_system_managers

		recipient_list = get_system_managers()
		db_backup_url = get_url(os.path.join('backups', os.path.basename(self.backup_path_db)))
		files_backup_url = get_url(os.path.join('backups', os.path.basename(self.backup_path_files)))

		msg = """<p>Hello,</p>
		<p>Your backups are ready to be downloaded.</p>
		<p>1. <a href="%(db_backup_url)s">Click here to download\
		 the database backup</a></p>
		<p>2. <a href="%(files_backup_url)s">Click here to download\
		the files backup</a></p>
		<p>This link will be valid for 24 hours. A new backup will be available
		for download only after 24 hours.</p>""" % {
			"db_backup_url": db_backup_url,
			"files_backup_url": files_backup_url
		}

		datetime_str = datetime.fromtimestamp(os.stat(self.backup_path_db).st_ctime)
		subject = datetime_str.strftime("%d/%m/%Y %H:%M:%S") + """ - Backup ready to be downloaded"""

		sendmail(recipients=recipient_list, msg=msg, subject=subject)
		return recipient_list
Exemple #7
0
def share_via_email(data):
	attachments = []
	files = data.get('files')
	for fl in files:
		fname = os.path.join(get_files_path(), fl)

		attachments.append({
				"fname": fname,
				"fcontent": file(fname).read()
			})

	if attachments:
		msg = """Event Name is %(event)s <br>
				Event Date is %(event_date)s <br>
				Provider Name is %(provider_name)s <br>
				Sharing reason is %(reason)s <br>
				<hr>
					%(event_body)s <br>
					Please find below attachment(s) <br>
			"""%{'event': data.get('event_title'), 'event_date': data.get('event_date'), 
				'provider_name': data.get('doctor_name'), 'event_body': data.get('email_body'), 'reason': data.get('reason')}
		
		from frappe.utils.email_lib import sendmail

		sendmail([data.get('email_id')], subject="PHR-Event Data", msg=cstr(msg),
				attachments=attachments)

		make_log(data.get('profile_id'),"Event","Shared Via Email","Event Shared Via Email to %s"%(data.get('email_id')))

		return """Selected image(s) has been shared with 
			%(provider_name)s for event %(event)s """%{
				'event': data.get('event_title'),
				'provider_name': data.get('doctor_name')}
	else:
		return 'Please select file(s) for sharing'
def send_email(PR, method, code):
    recipients = []
    expiry_date = ''
    cust = ''
    customer = frappe.db.sql(
        """select email_id ,customer from `tabBuy Back Requisition` where name='%s' """
        % (PR.buy_back_requisition_ref),
        as_list=1)
    if customer:
        recipients.append(cstr(customer[0][0]))
        cust = cstr(customer[0][1])
    no_of_days = frappe.db.sql(
        """select value from `tabSingles` where field='no_of_days'""",
        as_dict=1)
    if no_of_days:
        expiry_date = add_days(nowdate(), cint(no_of_days[0]['value']))
        if expiry_date:
            frappe.db.sql(
                "update `tabPurchase Receipt` set pin_expiry='%s' where name='%s'"
                % (expiry_date, PR.name))
    if recipients:
        subject = "Voucher Generation"
        message = """<h3>Dear   %s</h3><p>The  PIN  below  is  generated against your transaction   %s at    '%s' </p>
		<p>PIN:     %s</p>
		<p>PIN Expiry Date:    %s </p>
		<p>Kindly redeem the  voucher  before  the  expiry  date.</p>
		<p>Thank You,</p>
		""" % (cust, PR.buy_back_requisition_ref, PR.warehouse, code,
         formatdate(expiry_date))
        sendmail(recipients, subject=subject, msg=message)
def send_device_recv_email(BuyBackRequisition, method):
    recipients = []
    expiry_date = ''
    if BuyBackRequisition.email_id:
        recipients.append(BuyBackRequisition.email_id)
    recipient = frappe.db.sql("""select parent from `tabDefaultValue` where 
								defkey='Warehouse' and defvalue='%s' 
								and  parent in (select parent from `tabUserRole` 
								where role in('MPO','Collection Officer','Redemption Officer'))""" %
                              BuyBackRequisition.warehouse,
                              as_dict=1)
    if recipient:
        for resp in recipient:
            recipients.append(resp['parent'])
    if recipients:
        subject = "Device Received"
        message = """<h3>Dear  %s</h3><p> We received your device at    '%s', below are the details</p>
		<p>Transaction ID:   %s</p>
		<p>Device Received:   %s</p>
		<p>Received Date:     %s </p>
		<p>Offered Price:    %s</p>
		<p>Your voucher will be sent to you in a separate email & sms correspondence.</p>
		<p>Thank You,</p>
		""" % (BuyBackRequisition.customer, BuyBackRequisition.warehouse,
         BuyBackRequisition.name, BuyBackRequisition.item_name,
         formatdate(BuyBackRequisition.creation),
         fmt_money(flt(BuyBackRequisition.offered_price)))
        sendmail(recipients, subject=subject, msg=message)
Exemple #10
0
def send_event_digest():
    today = nowdate()
    for user in frappe.db.sql("""select name, email, language
		from tabUser where ifnull(enabled,0)=1
		and user_type='System User' and name not in ({})""".format(", ".join(
        ["%s"] * len(STANDARD_USERS))),
                              STANDARD_USERS,
                              as_dict=1):

        events = get_events(today, today, user.name, for_reminder=True)
        if events:
            text = ""
            frappe.set_user_lang(user.name, user.language)

            text = "<h3>" + frappe._("Events In Today's Calendar") + "</h3>"
            for e in events:
                if e.all_day:
                    e.starts_on = "All Day"
                text += "<h4>%(starts_on)s: %(subject)s</h4><p>%(description)s</p>" % e

            text += '<p style="color: #888; font-size: 80%; margin-top: 20px; padding-top: 10px; border-top: 1px solid #eee;">'\
             + frappe._("Daily Event Digest is sent for Calendar Events where reminders are set.")+'</p>'

            from frappe.utils.email_lib import sendmail
            sendmail(recipients=user.email,
                     subject=frappe._("Upcoming Events for Today"),
                     msg=text)
Exemple #11
0
def send_reedemed_email(Voucher, method):
    transaction_id = ''
    from frappe.utils.email_lib import sendmail
    recipients = []
    buy_back_requisition_ref = frappe.db.sql(
        """select buy_back_requisition_ref,creation from `tabPurchase Receipt` where pin='%s' """
        % (Voucher.enter_pin),
        as_dict=1)
    if buy_back_requisition_ref:
        transaction_id = buy_back_requisition_ref[0][
            'buy_back_requisition_ref']
    if Voucher.customer:
        customer = frappe.db.sql(
            """select email_id from `tabCustomer` where name='%s' """ %
            (Voucher.customer),
            as_list=1)
        if customer:
            recipients.append(customer[0][0])
    recipient = frappe.db.sql(
        """select parent from `tabUserRole` where role in('MPO','Collection Officer','Redemption Officer')""",
        as_dict=1)
    if recipient:
        for resp in recipient:
            recipients.append(resp['parent'])
    if recipients:
        subject = "Voucher Redemption"
        if Voucher.mark_voucher_as_redeemed == 1:
            message = """<h3>Dear %s </h3><p>Your Voucher for Transaction %s  at   '%s' has been successfully redeemed</p>
			<p>Value of the voucher :    %s</p>
			<p>Redemption Date:    %s </p>
			<p>Thank You,</p>
			""" % (Voucher.customer, transaction_id, Voucher.warehouse,
            fmt_money(flt(Voucher.discount_amount)), formatdate(
              Voucher.creation))
            sendmail(recipients, subject=subject, msg=message)
Exemple #12
0
def send_email(share_info, profile_id, disease):
    from email.mime.audio import MIMEAudio
    from email.mime.base import MIMEBase
    from email.mime.image import MIMEImage
    from email.mime.text import MIMEText
    import mimetypes
    import datetime

    attachments = []
    file_name = disease + '.pdf'
    files = os.path.join(get_files_path(), profile_id, file_name)

    attachments.append({"fname": files, "fcontent": file(files).read()})

    if attachments:
        msg = """Disease Name is %(event)s <br>
				Provider Name is %(provider_name)s <br>
				<hr>
					%(event_body)s <br>
					Please see attachment <br>
			""" % {
            'event': disease,
            'provider_name': share_info.get('doctor_name'),
            'event_body': share_info.get('email_body')
        }

        from frappe.utils.email_lib import sendmail

        sendmail([share_info.get('email_id')],
                 subject="PHR-Disease Monitoring Data",
                 msg=cstr(msg),
                 attachments=attachments)
Exemple #13
0
def send_message(subject="Website Query", message="", sender=""):
    if not message:
        frappe.response["message"] = 'Please write something'
        return

    if not sender:
        frappe.response["message"] = 'Email Id Required'
        return

    # guest method, cap max writes per hour
    if frappe.db.sql(
            """select count(*) from `tabCommunication`
		where `sent_or_received`="Received"
		and TIMEDIFF(%s, modified) < '01:00:00'""",
            now())[0][0] > max_communications_per_hour:
        frappe.response[
            "message"] = "Sorry: we believe we have received an unreasonably high number of requests of this kind. Please try later"
        return

    # send email
    forward_to_email = frappe.db.get_value("Contact Us Settings", None,
                                           "forward_to_email")
    if forward_to_email:
        from frappe.utils.email_lib import sendmail
        sendmail(forward_to_email, sender, message, subject)

    return "okay"
Exemple #14
0
def send_mail(recipient, message):
    import itertools
    from frappe.utils.email_lib import sendmail

    emails = [value for key, value in recipient.items()]
    sendmail(list(itertools.chain(*emails)),
             subject="Notification",
             msg=cstr(message))
def ticket_submission(doc,method):
    from frappe.utils.email_lib import sendmail
    frappe.errprint("ticket submission")
    etemp=frappe.db.sql("select subject,message from `tabTemplate Types` where name='Contact us, Feedback & Ticket submission'")
    #frappe.errprint(doc.name)
    #frappe.errprint(doc.customer)
    msg=etemp[0][1].replace('first_name',doc.customer).replace('ticket_number',doc.name)
    sendmail(doc.raised_by, subject=etemp[0][0], msg = msg)
def lead_sales_followup():
    from frappe.utils.email_lib import sendmail
    etemp=frappe.db.sql("select subject,message from `tabTemplate Types` where name='Sales follow up'")
    qry="select lead_name,email_id,date(creation) from `tabLead` where DATEDIFF(curdate(),creation) <=64 and WEEKDAY(curdate())=0 and customer is null"
    res = frappe.db.sql(qry)
    for r in res:
        #frappe.errprint(r)
        msg=etemp[0][1].replace('first_name',r[0]).replace('act_date',cstr(r[2]))
        sendmail(r[1], subject=etemp[0][0], msg = msg)
def feedback_submission(doc,method):
    from frappe.utils.email_lib import sendmail
    etemp=frappe.db.sql("select subject,message from `tabTemplate Types` where name='Contact us, Feedback & Ticket submission'")
    query="select client_name from `tabSite Master` where email_id__if_administrator='"+doc.raised_by+"'"
    #frappe.errprint(query)
    res=frappe.db.sql(query)
    #frappe.errprint(res[0][0])
    msg=etemp[0][1].replace('first_name',res[0][0]).replace('ticket_number',doc.name)
    sendmail(doc.raised_by, subject=etemp[0][0], msg = msg)
Exemple #18
0
def share_via_email(data):
    attachments = []
    files = data.get('files')
    patient_name = frappe.db.get_value(
        "User", {"profile_id": data.get('profile_id')},
        'concat(first_name, " ", last_name)') or data.get('lphr_name')
    for fl in files:
        fname = os.path.join(get_files_path(), fl)
        attachments.append({
            "fname": fname.split('/')[-1:][0],
            "fcontent": file(fname).read()
        })

    if attachments:
        msg = """Event Name is %(event)s <br>
				Event Date is %(event_date)s <br>
				Provider Name is %(provider_name)s <br>
				Sharing reason is %(reason)s <br>
				<hr>
					%(event_body)s <br>
					Please find below attachment(s) <br>
			""" % {
            'event': data.get('event_title'),
            'event_date': data.get('event_date') or data.get("str_visit_date"),
            'provider_name': data.get('doctor_name'),
            'event_body': data.get('email_body'),
            'reason': data.get('reason')
        }

        from frappe.utils.email_lib import sendmail

        sendmail([data.get('email_id')],
                 subject="PHR-Event Data",
                 msg=cstr(msg),
                 attachments=attachments)

        make_log(
            data.get('profile_id'), "Event", "Shared Via Email",
            "Event <b style='color: #89c148;'>%s</b> Shared Via Email %s" %
            (data.get('event_title'), data.get('email_id')))
        # args = {"patient":patient_name,"email":data.get('email_id')}
        # notify_provider(data.get('doctor_id'),data.get('profile_id'),"Event Share Email",args)
        return {
            "returncode": 1,
            "message_summary":
            "Selected image(s) has been shared with %(provider_name)s for event %(event)s "
            % {
                'event': data.get('event_title'),
                'provider_name': data.get('doctor_name')
            }
        }
    else:
        return {
            "returncode": 0,
            "message_summary": "Please select file(s) for sharing"
        }
Exemple #19
0
	def send_mail_funct(self):
		from frappe.utils.email_lib import sendmail

		receiver = frappe.db.get_value("Employee", self.employee, "company_email")
		if receiver:
			subj = 'Salary Slip - ' + cstr(self.month) +'/'+cstr(self.fiscal_year)
			sendmail([receiver], subject=subj, msg = _("Please see attachment"),
				attachments=[frappe.attach_print(self.doctype, self.name, file_name=self.name)])
		else:
			msgprint(_("Company Email ID not found, hence mail not sent"))
def promotional_follow():
    from frappe.utils.email_lib import sendmail
    etemp=frappe.db.sql("select subject,message from `tabTemplate Types` where name='Promotional Followup'")
    #frappe.errprint(etemp)
    qry="select lead_name,email_id,DATE_ADD(curdate(),INTERVAL 7 DAY) from `tabLead` where DATEDIFF(curdate(),creation) >=64 and WEEKDAY(curdate())=0 and customer is null"
    res = frappe.db.sql(qry)
    #frappe.errprint(res)
    for r in res:
        msg=etemp[0][1].replace('first_name',r[0]).replace('current_date+7',cstr(r[2]))
        sendmail(r[1], subject=etemp[0][0], msg = msg)
def ticket_submission(doc, method):
    from frappe.utils.email_lib import sendmail
    frappe.errprint("ticket submission")
    etemp = frappe.db.sql(
        "select subject,message from `tabTemplate Types` where name='Contact us, Feedback & Ticket submission'"
    )
    #frappe.errprint(doc.name)
    #frappe.errprint(doc.customer)
    msg = etemp[0][1].replace('first_name',
                              doc.customer).replace('ticket_number', doc.name)
    sendmail(doc.raised_by, subject=etemp[0][0], msg=msg)
def lead_sales_followup():
    from frappe.utils.email_lib import sendmail
    etemp = frappe.db.sql(
        "select subject,message from `tabTemplate Types` where name='Sales follow up'"
    )
    qry = "select lead_name,email_id,date(creation) from `tabLead` where DATEDIFF(curdate(),creation) <=64 and WEEKDAY(curdate())=0 and customer is null"
    res = frappe.db.sql(qry)
    for r in res:
        #frappe.errprint(r)
        msg = etemp[0][1].replace('first_name',
                                  r[0]).replace('act_date', cstr(r[2]))
        sendmail(r[1], subject=etemp[0][0], msg=msg)
def feedback_submission(doc, method):
    from frappe.utils.email_lib import sendmail
    etemp = frappe.db.sql(
        "select subject,message from `tabTemplate Types` where name='Contact us, Feedback & Ticket submission'"
    )
    query = "select client_name from `tabSite Master` where email_id__if_administrator='" + doc.raised_by + "'"
    #frappe.errprint(query)
    res = frappe.db.sql(query)
    #frappe.errprint(res[0][0])
    msg = etemp[0][1].replace('first_name',
                              res[0][0]).replace('ticket_number', doc.name)
    sendmail(doc.raised_by, subject=etemp[0][0], msg=msg)
Exemple #24
0
	def send_mail_funct(self):
		from frappe.utils.email_lib import sendmail

		receiver = frappe.db.get_value("Employee", self.employee, "company_email")
		if receiver:
			subj = 'Salary Slip - ' + cstr(self.month) +'/'+cstr(self.fiscal_year)
			sendmail([receiver], subject=subj, msg = _("Please see attachment"),
				attachments=[{
					"fname": self.name + ".pdf",
					"fcontent": frappe.get_print_format(self.doctype, self.name, as_pdf = True)
				}])
		else:
			msgprint(_("Company Email ID not found, hence mail not sent"))
def on_renewal_date():
    from frappe.utils.email_lib import sendmail
    etemp=frappe.db.sql("select subject,message from `tabTemplate Types` where name='On renewal date'")
    query="select client_name,expiry_date,email_id__if_administrator from `tabSite Master`"
    res=frappe.db.sql(query)
    for r in res:
        qr="select datediff('"+cstr(r[1])+"',curdate())"
        #frappe.errprint(qr)
        diff=frappe.db.sql(qr)
        #frappe.errprint(diff[0][0])
        if(diff[0][0]==0):
            msg=etemp[0][1].replace('first_name',r[0]).replace('Date',cstr(r[1]))
            sendmail(r[2], subject=etemp[0][0], msg = msg)
def promotional_follow():
    from frappe.utils.email_lib import sendmail
    etemp = frappe.db.sql(
        "select subject,message from `tabTemplate Types` where name='Promotional Followup'"
    )
    #frappe.errprint(etemp)
    qry = "select lead_name,email_id,DATE_ADD(curdate(),INTERVAL 7 DAY) from `tabLead` where DATEDIFF(curdate(),creation) >=64 and WEEKDAY(curdate())=0 and customer is null"
    res = frappe.db.sql(qry)
    #frappe.errprint(res)
    for r in res:
        msg = etemp[0][1].replace('first_name',
                                  r[0]).replace('current_date+7', cstr(r[2]))
        sendmail(r[1], subject=etemp[0][0], msg=msg)
Exemple #27
0
	def send_mail_funct(self):
		from frappe.utils.email_lib import sendmail

		receiver = frappe.db.get_value("Employee", self.employee, "company_email")
		if receiver:
			subj = 'Salary Slip - ' + cstr(self.month) +'/'+cstr(self.fiscal_year)
			sendmail([receiver], subject=subj, msg = _("Please see attachment"),
				attachments=[{
					"fname": self.name + ".pdf",
					"fcontent": frappe.get_print_format(self.doctype, self.name, as_pdf = True)
				}])
		else:
			msgprint(_("Company Email ID not found, hence mail not sent"))
def after_deactivation():
    from frappe.utils.email_lib import sendmail
    etemp=frappe.db.sql("select subject,message from `tabTemplate Types` where name='1 working day after deactivation'")
    query="select client_name,expiry_date,email_id__if_administrator from `tabSite Master`"
    res=frappe.db.sql(query)
    for r in res:
        qr="select datediff(curdate(),'"+cstr(r[1])+"')"
        #frappe.errprint(qr)
        diff=frappe.db.sql(qr)
        #frappe.errprint(diff[0][0])
        if(diff[0][0]==(-9)):
            msg=etemp[0][1].replace('first_name',r[0]).replace('Expiry date',cstr(r[1]))
            sendmail(r[2], subject=etemp[0][0], msg = msg)
Exemple #29
0
	def on_update(self):
		from frappe.templates.website_group.post import clear_post_cache
		from frappe.templates.generators.website_group import clear_cache

		clear_cache(website_group=self.website_group)
		clear_post_cache(self.parent_post or self.name)

		if self.assigned_to and self.assigned_to != self.assigned_to \
			and frappe.session.user != self.assigned_to:

			# send assignment email
			sendmail(recipients=[self.assigned_to],
				subject="You have been assigned this Task by {}".format(get_fullname(self.modified_by)),
				msg=self.get_reply_email_message(self.name, get_fullname(self.owner)))
Exemple #30
0
	def on_update(self):
		from frappe.templates.website_group.post import clear_post_cache
		from frappe.website.doctype.website_group.website_group import clear_cache

		clear_cache(website_group=self.website_group)
		clear_post_cache(self.parent_post or self.name)

		if self.assigned_to and self.assigned_to != self.assigned_to \
			and frappe.session.user != self.assigned_to:

			# send assignment email
			sendmail(recipients=[self.assigned_to],
				subject="You have been assigned this Task by {}".format(get_fullname(self.modified_by)),
				msg=self.get_reply_email_message(self.name, get_fullname(self.owner)))
Exemple #31
0
def notify_provider(provider_id,patient,template,args,email_msg=None):
	provider_info = frappe.db.get_value("Provider",{"provider_id":provider_id},"name")
	if provider_info:
		provider = frappe.get_doc("Provider",provider_info)
		if provider.mobile_number:
			from phr.templates.pages.patient import get_sms_template
			msg = get_sms_template(template,args)
			recipient_list = []
			recipient_list.append(provider.mobile_number)
			from erpnext.setup.doctype.sms_settings.sms_settings import send_sms
			send_sms(recipient_list,msg=msg)

		if provider.email and email_msg:
			from frappe.utils.email_lib import sendmail
			sendmail(provider.email, subject="HealthSnapp Updates:Data Shared With You", msg=email_msg)
def after_grace_date():
    from frappe.utils.email_lib import sendmail
    etemp = frappe.db.sql(
        "select subject,message from `tabTemplate Types` where name='On grace period expiry'"
    )
    query = "select client_name,expiry_date,email_id__if_administrator from `tabSite Master`"
    res = frappe.db.sql(query)
    for r in res:
        qr = "select datediff(curdate(),'" + cstr(r[1]) + "')"
        #frappe.errprint(qr)
        diff = frappe.db.sql(qr)
        #frappe.errprint(diff[0][0])
        if (diff[0][0] == (-8)):
            msg = etemp[0][1].replace('first_name', r[0])
            sendmail(r[2], subject=etemp[0][0], msg=msg)
def before1_renewal_date():
    from frappe.utils.email_lib import sendmail
    etemp = frappe.db.sql(
        "select subject,message from `tabTemplate Types` where name='1 Working day before renewal date'"
    )
    query = "select client_name,expiry_date,email_id__if_administrator from `tabSite Master`"
    res = frappe.db.sql(query)
    for r in res:
        qr = "select datediff('" + cstr(r[1]) + "',curdate())"
        #frappe.errprint(qr)
        diff = frappe.db.sql(qr)
        #frappe.errprint(diff[0][0])
        if (diff[0][0] == 1):
            msg = etemp[0][1].replace('first_name',
                                      r[0]).replace('renewal date', cstr(r[1]))
            sendmail(r[2], subject=etemp[0][0], msg=msg)
Exemple #34
0
    def send_auto_reply(self, d):
        signature = self.email_settings.get('support_signature') or ''
        response = self.email_settings.get('support_autoreply') or ("""
A new Ticket has been raised for your query. If you have any additional information, please
reply back to this mail.
		
We will get back to you as soon as possible
----------------------
Original Query:

""" + d.description + "\n----------------------\n" + cstr(signature))

        sendmail(\
         recipients = [cstr(d.raised_by)], \
         sender = cstr(self.email_settings.get('support_email')), \
         subject = '['+cstr(d.name)+'] ' + cstr(d.subject), \
         msg = cstr(response))
Exemple #35
0
	def send(self):
		# send email only to enabled users
		valid_users = [p[0] for p in frappe.db.sql("""select name from `tabUser`
			where enabled=1""")]
		recipients = filter(lambda r: r in valid_users,
			self.recipient_list.split("\n"))

		common_msg = self.get_common_content()
		if recipients:
			for user_id in recipients:
				msg_for_this_receipient = self.get_msg_html(self.get_user_specific_content(user_id) + \
					common_msg)
				if msg_for_this_receipient:
					sendmail(recipients=user_id,
						subject="[ERPNext] [{frequency} Digest] {name}".format(
							frequency=self.frequency, name=self.name),
						msg=msg_for_this_receipient)
Exemple #36
0
	def send(self):
		# send email only to enabled users
		valid_users = [p[0] for p in frappe.db.sql("""select name from `tabUser`
			where enabled=1""")]
		recipients = filter(lambda r: r in valid_users,
			self.recipient_list.split("\n"))

		common_msg = self.get_common_content()
		if recipients:
			for user_id in recipients:
				msg_for_this_receipient = self.get_msg_html(self.get_user_specific_content(user_id) + \
					common_msg)
				if msg_for_this_receipient:
					sendmail(recipients=user_id,
						subject="[ERPNext] [{frequency} Digest] {name}".format(
							frequency=self.frequency, name=self.name),
						msg=msg_for_this_receipient)
	def send_auto_reply(self, d):
		signature = self.email_settings.get('support_signature') or ''
		response = self.email_settings.get('support_autoreply') or ("""
A new Ticket has been raised for your query. If you have any additional information, please
reply back to this mail.
		
We will get back to you as soon as possible
----------------------
Original Query:

""" + d.description + "\n----------------------\n" + cstr(signature))

		sendmail(\
			recipients = [cstr(d.raised_by)], \
			sender = cstr(self.email_settings.get('support_email')), \
			subject = '['+cstr(d.name)+'] ' + cstr(d.subject), \
			msg = cstr(response))
def notify_errors(exceptions_list):
    subject = "[Important] [ERPNext] Error(s) while creating Material Requests based on Re-order Levels"
    msg = """Dear System Manager,

An error occured for certain Items while creating Material Requests based on Re-order level.

Please rectify these issues:
---
<pre>
%s
</pre>
---
Regards,
Administrator""" % ("\n\n".join(exceptions_list), )

    from frappe.utils.user import get_system_managers
    sendmail(get_system_managers(), subject=subject, msg=msg)
Exemple #39
0
def notify_errors(exceptions_list):
	subject = "[Important] [ERPNext] Error(s) while creating Material Requests based on Re-order Levels"
	msg = """Dear System Manager,

An error occured for certain Items while creating Material Requests based on Re-order level.

Please rectify these issues:
---
<pre>
%s
</pre>
---
Regards,
Administrator""" % ("\n\n".join(exceptions_list),)

	from frappe.utils.user import get_system_managers
	sendmail(get_system_managers(), subject=subject, msg=msg)
Exemple #40
0
	def send(self):
		frappe.local.lang = 'zh-cn'
		# send email only to enabled users
		valid_users = [p[0] for p in frappe.db.sql("""select name from `tabUser`
			where enabled=1""")]
		recipients = filter(lambda r: r in valid_users,
			self.recipient_list.split("\n"))

		common_msg = self.get_common_content()
		if recipients:
			for user_id in recipients:
				msg_for_this_receipient = self.get_msg_html(self.get_user_specific_content(user_id) + \
					common_msg)
				if msg_for_this_receipient:
					sendmail(recipients=user_id,
						subject=("[博实] [{frequency} " + _("Digest")+ "] {name}").format(
							frequency=_(self.frequency), name=_(self.name)),
						msg=msg_for_this_receipient)
Exemple #41
0
    def send_mail_funct(self):
        from frappe.utils.email_lib import sendmail

        receiver = frappe.db.get_value("Employee", self.employee,
                                       "company_email")
        if receiver:
            subj = 'Salary Slip - ' + cstr(self.month) + '/' + cstr(
                self.fiscal_year)
            sendmail([receiver],
                     subject=subj,
                     msg=_("Please see attachment"),
                     attachments=[
                         frappe.attach_print(self.doctype,
                                             self.name,
                                             file_name=self.name)
                     ])
        else:
            msgprint(_("Company Email ID not found, hence mail not sent"))
Exemple #42
0
def send_email_notification(mr_list):
	""" Notify user about auto creation of indent"""

	email_list = frappe.db.sql_list("""select distinct r.parent
		from tabUserRole r, tabUser p
		where p.name = r.parent and p.enabled = 1 and p.docstatus < 2
		and r.role in ('Purchase Manager','Material Manager')
		and p.name not in ('Administrator', 'All', 'Guest')""")

	msg="""<h3>Following Material Requests has been raised automatically \
		based on item reorder level:</h3>"""
	for mr in mr_list:
		msg += "<p><b><u>" + mr.name + """</u></b></p><table class='table table-bordered'><tr>
			<th>Item Code</th><th>Warehouse</th><th>Qty</th><th>UOM</th></tr>"""
		for item in mr.get("indent_details"):
			msg += "<tr><td>" + item.item_code + "</td><td>" + item.warehouse + "</td><td>" + \
				cstr(item.qty) + "</td><td>" + cstr(item.uom) + "</td></tr>"
		msg += "</table>"
	sendmail(email_list, subject='Auto Material Request Generation Notification', msg = msg)
Exemple #43
0
def send_email_notification(mr_list):
	""" Notify user about auto creation of indent"""

	email_list = frappe.db.sql_list("""select distinct r.parent
		from tabUserRole r, tabUser p
		where p.name = r.parent and p.enabled = 1 and p.docstatus < 2
		and r.role in ('Purchase Manager','Material Manager')
		and p.name not in ('Administrator', 'All', 'Guest')""")

	msg="""<h3>Following Material Requests has been raised automatically \
		based on item reorder level:</h3>"""
	for mr in mr_list:
		msg += "<p><b><u>" + mr.name + """</u></b></p><table class='table table-bordered'><tr>
			<th>Item Code</th><th>Warehouse</th><th>Qty</th><th>UOM</th></tr>"""
		for item in mr.get("indent_details"):
			msg += "<tr><td>" + item.item_code + "</td><td>" + item.warehouse + "</td><td>" + \
				cstr(item.qty) + "</td><td>" + cstr(item.uom) + "</td></tr>"
		msg += "</table>"
	sendmail(email_list, subject='Auto Material Request Generation Notification', msg = msg)
Exemple #44
0
def send_email(share_info, profile_id, disease):
    from email.mime.audio import MIMEAudio
    from email.mime.base import MIMEBase
    from email.mime.image import MIMEImage
    from email.mime.text import MIMEText
    import mimetypes
    import datetime

    attachments = []
    file_name = disease + '.pdf'
    files = os.path.join(get_files_path(), profile_id, file_name)

    attachments.append({"fname": files, "fcontent": file(files).read()})

    if attachments:
        msg = """Disease Name is %(event)s <br>
				Provider Name is %(provider_name)s <br>
				<hr>
					%(event_body)s <br>
					Please see attachment <br>
			""" % {
            'event': disease,
            'provider_name': share_info.get('doctor_name'),
            'event_body': share_info.get('email_body')
        }

        from frappe.utils.email_lib import sendmail

        sendmail([share_info.get('email_id')],
                 subject="PHR-Disease Monitoring Data",
                 msg=cstr(msg),
                 attachments=attachments)

        make_log(
            profile_id, "Disease Monitoring",
            "Shared Via Email to provider %s" % share_info.get('doctor_name'),
            "DM of <b style='color: #89c148;'>%s</b> Shared Via Email to provider %s"
            % (disease, share_info.get('doctor_name')))
        return {
            "returncode": 1,
            "message_display": "Disease Monitoring records has been shared"
        }
def send_email(success, service_name, error_status=None):
	from frappe.utils.email_lib import sendmail
	if success:
		subject = "Backup Upload Successful"
		message ="""<h3>Backup Uploaded Successfully</h3><p>Hi there, this is just to inform you 
		that your backup was successfully uploaded to your %s account. So relax!</p>
		""" % service_name
	else:
		subject = "[Warning] Backup Upload Failed"
		message ="""<h3>Backup Upload Failed</h3><p>Oops, your automated backup to %s
		failed.</p>
		<p>Error message: %s</p>
		<p>Please contact your system manager for more information.</p>
		""" % (service_name, error_status)
	
	if not frappe.db:
		frappe.connect()
	
	recipients = frappe.db.get_value("Backup Manager", None, "send_notifications_to").split(",")
	sendmail(recipients, subject=subject, msg=message)
Exemple #46
0
def notify_provider(provider_id, patient, template, args, email_msg=None):
    provider_info = frappe.db.get_value("Provider",
                                        {"provider_id": provider_id}, "name")
    if provider_info:
        provider = frappe.get_doc("Provider", provider_info)
        if provider.mobile_number:
            from phr.templates.pages.utils import get_sms_template
            msg = get_sms_template(template, args)
            recipient_list = []
            recipient_list.append(provider.mobile_number)
            from erpnext.setup.doctype.sms_settings.sms_settings import send_sms
            send_sms(recipient_list, msg=msg)

        if provider.email and email_msg:
            from frappe.utils.email_lib import sendmail
            sendmail(provider.email,
                     subject="HealthSnapp Updates:Data Shared With You",
                     msg=email_msg)

        return "done"
def send_email(success, service_name, error_status=None):
    from frappe.utils.email_lib import sendmail
    if success:
        subject = "Backup Upload Successful"
        message = """<h3>Backup Uploaded Successfully</h3><p>Hi there, this is just to inform you 
		that your backup was successfully uploaded to your %s account. So relax!</p>
		""" % service_name
    else:
        subject = "[Warning] Backup Upload Failed"
        message = """<h3>Backup Upload Failed</h3><p>Oops, your automated backup to %s
		failed.</p>
		<p>Error message: %s</p>
		<p>Please contact your system manager for more information.</p>
		""" % (service_name, error_status)

    if not frappe.db:
        frappe.connect()

    recipients = frappe.db.get_value("Backup Manager", None,
                                     "send_notifications_to").split(",")
    sendmail(recipients, subject=subject, msg=message)
def send_email(PR, method,code):
	recipients=[]
	expiry_date=''
	cust=''
	customer=frappe.db.sql("""select email_id ,customer from `tabBuy Back Requisition` where name='%s' """%(PR.buy_back_requisition_ref),as_list=1)
	if customer:
		recipients.append(cstr(customer[0][0]))
		cust=cstr(customer[0][1])
	no_of_days=frappe.db.sql("""select value from `tabSingles` where field='no_of_days'""",as_dict=1)
	if no_of_days:
		expiry_date=add_days(nowdate(),cint(no_of_days[0]['value']))
		if expiry_date:
			frappe.db.sql("update `tabPurchase Receipt` set pin_expiry='%s' where name='%s'"%(expiry_date,PR.name))
	if recipients:
		subject = "Voucher Generation"
		message ="""<h3>Dear   %s</h3><p>The  PIN  below  is  generated against your transaction   %s at    '%s' </p>
		<p>PIN:     %s</p>
		<p>PIN Expiry Date:    %s </p>
		<p>Kindly redeem the  voucher  before  the  expiry  date.</p>
		<p>Thank You,</p>
		""" %(cust,PR.buy_back_requisition_ref,PR.warehouse,code,formatdate(expiry_date))
		sendmail(recipients, subject=subject, msg=message)	
Exemple #49
0
def send_message(subject="Website Query", message="", sender=""):
	if not message:
		frappe.response["message"] = 'Please write something'
		return

	if not sender:
		frappe.response["message"] = 'Email Id Required'
		return

	# guest method, cap max writes per hour
	if frappe.db.sql("""select count(*) from `tabCommunication`
		where TIMEDIFF(%s, modified) < '01:00:00'""", now())[0][0] > max_communications_per_hour:
		frappe.response["message"] = "Sorry: we believe we have received an unreasonably high number of requests of this kind. Please try later"
		return

	# send email
	forward_to_email = frappe.db.get_value("Contact Us Settings", None, "forward_to_email")
	if forward_to_email:
		from frappe.utils.email_lib import sendmail
		sendmail(forward_to_email, sender, message, subject)

	return "okay"
def send_device_recv_email(BuyBackRequisition, method):
	recipients=[]
	expiry_date=''
	if BuyBackRequisition.email_id:
		recipients.append(BuyBackRequisition.email_id)
	recipient=frappe.db.sql("""select parent from `tabDefaultValue` where 
								defkey='Warehouse' and defvalue='%s' 
								and  parent in (select parent from `tabUserRole` 
								where role in('MPO','Collection Officer','Redemption Officer'))"""%BuyBackRequisition.warehouse,as_dict=1)
	if recipient:
		for resp in recipient:
			recipients.append(resp['parent'])
	if recipients:
		subject = "Device Received"
		message ="""<h3>Dear  %s</h3><p> We received your device at    '%s', below are the details</p>
		<p>Transaction ID:   %s</p>
		<p>Device Received:   %s</p>
		<p>Received Date:     %s </p>
		<p>Offered Price:    %s</p>
		<p>Your voucher will be sent to you in a separate email & sms correspondence.</p>
		<p>Thank You,</p>
		""" %(BuyBackRequisition.customer,BuyBackRequisition.warehouse,BuyBackRequisition.name,BuyBackRequisition.item_name,formatdate(BuyBackRequisition.creation),fmt_money(flt(BuyBackRequisition.offered_price)))
		sendmail(recipients, subject=subject, msg=message)
Exemple #51
0
def send_event_digest():
	today = nowdate()
	for user in frappe.db.sql("""select name, email, language
		from tabUser where ifnull(enabled,0)=1
		and user_type='System User' and name not in ({})""".format(", ".join(["%s"]*len(STANDARD_USERS))),
		STANDARD_USERS, as_dict=1):

		events = get_events(today, today, user.name, for_reminder=True)
		if events:
			text = ""
			frappe.set_user_lang(user.name, user.language)

			text = "<h3>" + frappe._("Events In Today's Calendar") + "</h3>"
			for e in events:
				if e.all_day:
					e.starts_on = "All Day"
				text += "<h4>%(starts_on)s: %(subject)s</h4><p>%(description)s</p>" % e

			text += '<p style="color: #888; font-size: 80%; margin-top: 20px; padding-top: 10px; border-top: 1px solid #eee;">'\
				+ frappe._("Daily Event Digest is sent for Calendar Events where reminders are set.")+'</p>'

			from frappe.utils.email_lib import sendmail
			sendmail(recipients=user.email, subject=frappe._("Upcoming Events for Today"),
				msg = text)
def send_reedemed_email(Voucher, method):
	transaction_id=''
	from frappe.utils.email_lib import sendmail
	recipients=[]
	buy_back_requisition_ref=frappe.db.sql("""select buy_back_requisition_ref,creation from `tabPurchase Receipt` where pin='%s' """%(Voucher.enter_pin),as_dict=1)
	if buy_back_requisition_ref:
		transaction_id=buy_back_requisition_ref[0]['buy_back_requisition_ref']
	if Voucher.customer:
		customer=frappe.db.sql("""select email_id from `tabCustomer` where name='%s' """%(Voucher.customer),as_list=1)
		if customer:
			recipients.append(customer[0][0])	
	recipient=frappe.db.sql("""select parent from `tabUserRole` where role in('MPO','Collection Officer','Redemption Officer')""",as_dict=1)
	if recipient:
		for resp in recipient:
			recipients.append(resp['parent'])
	if recipients:
		subject = "Voucher Redemption"
		if Voucher.mark_voucher_as_redeemed==1:
			message ="""<h3>Dear %s </h3><p>Your Voucher for Transaction %s  at   '%s' has been successfully redeemed</p>
			<p>Value of the voucher :    %s</p>
			<p>Redemption Date:    %s </p>
			<p>Thank You,</p>
			""" %(Voucher.customer,transaction_id,Voucher.warehouse,fmt_money(flt(Voucher.discount_amount)),formatdate(Voucher.creation))
			sendmail(recipients, subject=subject, msg=message)	
Exemple #53
0
def send_shared_data(data):
    from email.mime.audio import MIMEAudio
    from email.mime.base import MIMEBase
    from email.mime.image import MIMEImage
    from email.mime.text import MIMEText
    import mimetypes
    import datetime

    data = json.loads(data)

    if data.get('share_via') == 'Email':
        attachments = []
        files = data.get('files')
        for fl in files:
            fname = os.path.join(get_files_path(), fl)

            attachments.append({
                "fname": fname,
                "fcontent": file(fname).read()
            })

        if attachments:
            msg = """Event Name is %(event)s <br>
					Event Date is %(event_date)s <br>
					Provider Name is %(provider_name)s <br>
					<hr>
						%(event_body)s <br>
						Please see attachment <br>
				""" % {
                'event': data.get('event_title'),
                'event_date': data.get('event_date'),
                'provider_name': data.get('doctor_name'),
                'event_body': data.get('email_body')
            }

            from frappe.utils.email_lib import sendmail

            sendmail([data.get('email_id')],
                     subject="PHR-Event Data",
                     msg=cstr(msg),
                     attachments=attachments)

            return """Selected images has been shared with 
				%(provider_name)s %(doc_email)s for event %(event)s """ % {
                'event': data.get('event_title'),
                'provider_name': data.get('doctor_name')
            }
        else:
            frappe.msgprint('Please select file(s) for sharing')

    if data.get('share_via') == 'Provider Account':
        if not data.get('files'):
            event_data = {
                "sharelist": [{
                    "to_profile_id":
                    data.get('doctor_id'),
                    "received_from":
                    "desktop",
                    "from_profile_id":
                    data.get('profile_id'),
                    "event_tag_id":
                    data.get('entityid'),
                    "access_type":
                    "RDW",
                    "str_start_date":
                    datetime.datetime.strptime(
                        nowdate(), '%Y-%m-%d').strftime('%d/%m/%Y'),
                    "str_end_date":
                    data.get('sharing_duration')
                }]
            }

            request_type = "POST"
            url = "%s/sharephr/sharemultipleevent" % get_base_url()

            response = get_response(url, json.dumps(event_data), request_type)

            return eval(json.loads(
                response.text).get('sharelist'))[0].get('message_summary')

        else:
            sharelist = []
            for fl in data.get('files'):
                file_details = fl.split('/')
                sharelist.append({
                    "to_profile_id":
                    data.get('doctor_id'),
                    "received_from":
                    "desktop",
                    "from_profile_id":
                    data.get('profile_id'),
                    "visit_tag_id":
                    file_details[4],
                    "tag_id":
                    file_details[4] + '-' +
                    cstr(file_details[2].split('-')[1]) +
                    cstr(file_details[3].split('_')[1]),
                    "file_id": [file_details[5]],
                    "file_access": ['RW'],
                    "str_start_date":
                    datetime.datetime.strptime(
                        nowdate(), '%Y-%m-%d').strftime('%d/%m/%Y'),
                    "str_end_date":
                    data.get('sharing_duration')
                })

            request_type = "POST"
            url = "%s/sharephr/sharemultiplevisitfiles" % get_base_url()
            event_data = {'sharelist': sharelist}
            response = get_response(url, json.dumps(event_data), request_type)

            return eval(json.loads(
                response.text).get('sharelist'))[0].get('message_summary')
	def send_mail_funct(self):
		from frappe.utils.email_lib import sendmail
		receiver = frappe.db.get_value("Employee", self.employee, "company_email")
		if receiver:
			subj = 'Salary Slip - ' + cstr(self.month) +'/'+cstr(self.fiscal_year)
			earn_ret=frappe.db.sql("""select e_type, e_modified_amount from `tabSalary Slip Earning`
				where parent = %s""", self.name)
			ded_ret=frappe.db.sql("""select d_type, d_modified_amount from `tabSalary Slip Deduction`
				where parent = %s""", self.name)

			earn_table = ''
			ded_table = ''
			if earn_ret:
				earn_table += "<table cellspacing=5px cellpadding=5px width='100%%'>"

				for e in earn_ret:
					if not e[1]:
						earn_table += '<tr><td>%s</td><td align="right">0.00</td></tr>' % cstr(e[0])
					else:
						earn_table += '<tr><td>%s</td><td align="right">%s</td></tr>' \
							% (cstr(e[0]), cstr(e[1]))
				earn_table += '</table>'

			if ded_ret:

				ded_table += "<table cellspacing=5px cellpadding=5px width='100%%'>"

				for d in ded_ret:
					if not d[1]:
						ded_table +='<tr><td">%s</td><td align="right">0.00</td></tr>' % cstr(d[0])
					else:
						ded_table +='<tr><td>%s</td><td align="right">%s</td></tr>' \
							% (cstr(d[0]), cstr(d[1]))
				ded_table += '</table>'

			letter_head = frappe.db.get_value("Letter Head", {"is_default": 1, "disabled": 0},
				"content")

			msg = '''<div> %s <br>
			<table cellspacing= "5" cellpadding="5"  width = "100%%">
				<tr>
					<td width = "100%%" colspan = "2"><h4>Salary Slip</h4></td>
				</tr>
				<tr>
					<td width = "50%%"><b>Employee Code : %s</b></td>
					<td width = "50%%"><b>Employee Name : %s</b></td>
				</tr>
				<tr>
					<td width = "50%%">Month : %s</td>
					<td width = "50%%">Fiscal Year : %s</td>
				</tr>
				<tr>
					<td width = "50%%">Department : %s</td>
					<td width = "50%%">Branch : %s</td>
				</tr>
				<tr>
					<td width = "50%%">Designation : %s</td>
				</tr>
				<tr>
					<td width = "50%%">Bank Account No. : %s</td>
					<td  width = "50%%">Bank Name : %s</td>

				</tr>
				<tr>
					<td  width = "50%%">Arrear Amount : <b>%s</b></td>
					<td  width = "50%%">Payment days : %s</td>

				</tr>
			</table>
			<table border="1px solid #CCC" width="100%%" cellpadding="0px" cellspacing="0px">
				<tr>
					<td colspan = 2 width = "50%%" bgcolor="#CCC" align="center">
						<b>Earnings</b></td>
					<td colspan = 2 width = "50%%" bgcolor="#CCC" align="center">
						<b>Deductions</b></td>
				</tr>
				<tr>
					<td colspan = 2 width = "50%%" valign= "top">%s</td>
					<td colspan = 2 width = "50%%" valign= "top">%s</td>
				</tr>
			</table>
			<table cellspacing= "5" cellpadding="5" width = '100%%'>
				<tr>
					<td width = '25%%'><b>Gross Pay :</b> </td>
					<td width = '25%%' align='right'>%s</td>
					<td width = '25%%'><b>Total Deduction :</b></td>
					<td width = '25%%' align='right'> %s</td>
				</tr>
				<tr>
					<tdwidth='25%%'><b>Net Pay : </b></td>
					<td width = '25%%' align='right'><b>%s</b></td>
					<td colspan = '2' width = '50%%'></td>
				</tr>
				<tr>
					<td width='25%%'><b>Net Pay(in words) : </td>
					<td colspan = '3' width = '50%%'>%s</b></td>
				</tr>
			</table></div>''' % (cstr(letter_head), cstr(self.employee),
				cstr(self.employee_name), cstr(self.month), cstr(self.fiscal_year),
				cstr(self.department), cstr(self.branch), cstr(self.designation),
				cstr(self.bank_account_no), cstr(self.bank_name),
				cstr(self.arrear_amount), cstr(self.payment_days), earn_table, ded_table,
				cstr(flt(self.gross_pay)), cstr(flt(self.total_deduction)),
				cstr(flt(self.net_pay)), cstr(self.total_in_words))

			sendmail([receiver], subject=subj, msg = msg)
		else:
			msgprint(_("Company Email ID not found, hence mail not sent"))
def multitenanct(from_test=False):
    frappe.errprint("creation site -------------------------------- ")
    res = frappe.db.sql(
        """select name,client_name,email_id__if_administrator from `tabSite Master` where flag=0 limit 1 """
    )
    if res:
        sites = ''
        sites = frappe.db.sql(
            """select sites from  `tabUser` where name='administrator'""")
        print sites
        print 'gangadharkadam'
        auto_commit = not from_test
        ste = res[0][0]
        from frappe.utils import cstr
        import os
        import sys
        import subprocess
        import getpass
        import logging
        import json
        from distutils.spawn import find_executable
        from frappe.utils.email_lib import sendmail
        cwd = '/home/gangadhar/Documents/gnkuper/frappe-bench/'
        print cwd
        cmd = "./testenv.sh " + ste
        print cwd
        qr = "select email_id__if_administrator,client_name from `tabSite Master` where name='" + ste + "'"
        rs = frappe.db.sql(qr)

        frappe.errprint("hello gangadhar")
        from frappe.utils.email_lib import sendmail
        etemp = frappe.db.sql(
            "select subject,message from `tabTemplate Types` where name='Successful first purchase'"
        )
        #frappe.errprint(etemp)
        msg = etemp[0][1].replace('first_name', rs[0][1]).replace(
            'user_name',
            'administrator').replace('password',
                                     'admin').replace('click here', ste)
        sendmail(rs[0][0], subject=etemp[0][0], msg=msg)

        #msg1="Hello "+res[0][1]+", <br> Welcome to TailorPad! <br> Thank you for showing interest. You can use the following link and credentials for trying TailorPad:<br> 'http://"+ste+"' <br> user name :-administrator<br> password :- admin<br>In case you need any more information about our product, please visit FAQ page or write to us on [email protected], we will be glad to assist you.<br>Best Regards,<br>Team TailorPad"
        #sendmail(rs[0][0], subject='Welcome to Tailorpad', msg = msg1)
        import subprocess
        frappe.errprint(cmd)
        #subprocess.call(['cd /home/indictrans/webapps/tailorpad/'])
        #pass
        sites = cstr(sites[0][0]) + ' ' + ste
        frappe.db.sql(
            "update `tabUser` set sites= %s where name='administrator'", sites)
        try:
            subprocess.check_call(cmd, cwd=cwd, shell=True)
        except subprocess.CalledProcessError, e:
            print "Error:", e.output
            raise
        print 'creating nginx'
        nginx = """
        upstream frappe {
        server 127.0.0.1:8000 fail_timeout=0;
        }
        server {
        listen 80 ;
        client_max_body_size 4G;
        server_name stich1.tailorpad.com %s;
        keepalive_timeout 5;
        sendfile on;
        root /home/gangadhar/Documents/gnkuper/frappe-bench/sites;

        location /private/ {
            internal;
            try_files /$uri =424;
        }

        location /assets {
            try_files $uri =404;
        }

        location / {
            try_files /stich1.tailorpad.com/public/$uri @magic;
        }

        location @magic {
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                        proxy_set_header Host $host;
                        proxy_set_header X-Use-X-Accel-Redirect True;
            proxy_read_timeout 120;
            proxy_redirect off;
            proxy_pass  http://frappe;
        }
        }""" % (sites)
        print nginx
        with open(
                "/home/gangadhar/Documents/gnkuper/frappe-bench/config/nginx.conf",
                "w") as conf_file:
            conf_file.write(nginx)
        cwd = '/home/'
        cmd = 'echo indictrans | sudo service nginx reload'
        print 'nginx reloading'
        try:
            subprocess.check_call(cmd, cwd=cwd, shell=True)
        except subprocess.CalledProcessError, e:
            print "Error:", e.output
            raise
def admin_notification(new_profiels):
	msg = get_message(new_profiels)
	receiver = frappe.db.get_value('User', 'Administrator', 'email')
	subj = "Newly Created profiels"

	sendmail(receiver, subject=subj, msg = cstr(msg))
def multitenanct(from_test=False):
    frappe.errprint("creation site -------------------------------- ")
    res=frappe.db.sql("""select name,client_name,email_id__if_administrator from `tabSite Master` where flag=0 limit 1 """)
    if res:
        sites=''
        sites = frappe.db.sql("""select sites from  `tabUser` where name='administrator'""")
        print sites
        print 'gangadharkadam'
        auto_commit = not from_test
        ste=res[0][0]
        from frappe.utils import cstr
        import os
        import sys
        import subprocess
        import getpass
        import logging
        import json
        from distutils.spawn import find_executable
        from frappe.utils.email_lib import sendmail
        cwd='/home/gangadhar/Documents/gnkuper/frappe-bench/'
        print cwd
        cmd="./testenv.sh "+ste
        print cwd
        qr="select email_id__if_administrator,client_name from `tabSite Master` where name='"+ste+"'"
        rs=frappe.db.sql(qr)

        frappe.errprint("hello gangadhar")
        from frappe.utils.email_lib import sendmail
        etemp=frappe.db.sql("select subject,message from `tabTemplate Types` where name='Successful first purchase'")
        #frappe.errprint(etemp)
        msg=etemp[0][1].replace('first_name',rs[0][1]).replace('user_name','administrator').replace('password','admin').replace('click here',ste)
        sendmail(rs[0][0], subject=etemp[0][0], msg = msg)

        #msg1="Hello "+res[0][1]+", <br> Welcome to TailorPad! <br> Thank you for showing interest. You can use the following link and credentials for trying TailorPad:<br> 'http://"+ste+"' <br> user name :-administrator<br> password :- admin<br>In case you need any more information about our product, please visit FAQ page or write to us on [email protected], we will be glad to assist you.<br>Best Regards,<br>Team TailorPad"
        #sendmail(rs[0][0], subject='Welcome to Tailorpad', msg = msg1)
        import subprocess
        frappe.errprint(cmd)
        #subprocess.call(['cd /home/indictrans/webapps/tailorpad/'])
        #pass
        sites=cstr(sites[0][0])+' '+ste
        frappe.db.sql("update `tabUser` set sites= %s where name='administrator'",sites)
        try:
                subprocess.check_call(cmd, cwd=cwd, shell=True)
        except subprocess.CalledProcessError, e:
                print "Error:", e.output
                raise
        print 'creating nginx'
        nginx="""
        upstream frappe {
        server 127.0.0.1:8000 fail_timeout=0;
        }
        server {
        listen 80 ;
        client_max_body_size 4G;
        server_name stich1.tailorpad.com %s;
        keepalive_timeout 5;
        sendfile on;
        root /home/gangadhar/Documents/gnkuper/frappe-bench/sites;

        location /private/ {
            internal;
            try_files /$uri =424;
        }

        location /assets {
            try_files $uri =404;
        }

        location / {
            try_files /stich1.tailorpad.com/public/$uri @magic;
        }

        location @magic {
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                        proxy_set_header Host $host;
                        proxy_set_header X-Use-X-Accel-Redirect True;
            proxy_read_timeout 120;
            proxy_redirect off;
            proxy_pass  http://frappe;
        }
        }"""%(sites)
        print nginx
        with open("/home/gangadhar/Documents/gnkuper/frappe-bench/config/nginx.conf","w") as conf_file:
                       conf_file.write(nginx)
        cwd='/home/'
        cmd='echo indictrans | sudo service nginx reload'
        print 'nginx reloading'
        try:
               subprocess.check_call(cmd, cwd=cwd, shell=True)
        except subprocess.CalledProcessError, e:
               print "Error:", e.output
               raise
def send_mail(recipient, message):
	import itertools
	from frappe.utils.email_lib import sendmail

	emails = [value for key, value in recipient.items()]
	sendmail(list(itertools.chain(*emails)), subject="Notification", msg=cstr(message))