def check_student_email_id_and_send_mail(student_mail_id, name_of_student,
                                         print_format, name,
                                         predefined_text_content,
                                         predefined_text_value,
                                         email_id_of_cc):
    orientation = "Landscape" if print_format == 'Microsoft Certificate' or print_format == "Microsoft Zertifikat" else "Portrait"
    if print_format in ["Microsoft Certificate", "Microsoft Zertifikat"]:
        attach_file_name = print_format
        print_format = "Microsoft Certificate"
    elif print_format in [
            "New Horizons Certificate", "New Horizons Zertifikat"
    ]:
        attach_file_name = print_format
        print_format = "New Horizons Certificate"

    if student_mail_id:
        recipients = [student_mail_id]
        cc = email_id_of_cc
        attachments = [
            frappe.attach_print("Certificate",
                                name,
                                file_name=attach_file_name,
                                print_format=print_format,
                                orientation=orientation)
        ]
        subject = print_format
        message = predefined_text_value
    else:
        recipients = [frappe.session.user]
        cc = email_id_of_cc
        attachments = [
            frappe.attach_print("Certificate",
                                name,
                                file_name=attach_file_name,
                                print_format=print_format,
                                orientation=orientation)
        ]
        subject = print_format
        message = _("Please Send Certificate to <b>{0}</b> <br>".format(
            name_of_student)) + predefined_text_value

    try:
        frappe.sendmail(recipients=(recipients or []),
                        cc=cc,
                        expose_recipients="header",
                        sender=None,
                        reply_to=None,
                        subject=_(subject),
                        content=None,
                        reference_doctype=None,
                        reference_name=None,
                        attachments=attachments,
                        message=message,
                        message_id=None,
                        unsubscribe_message=None,
                        delayed=False,
                        communication=None)
    except Exception, e:
        frappe.throw(
            _("Mail has not been Sent. Kindly Contact to Administrator"))
Beispiel #2
0
	def send_acknowlement(self):
		settings = frappe.get_doc("Non Profit Settings")
		if not settings.send_email:
			frappe.throw(_("You need to enable <b>Send Acknowledge Email</b> in {0}").format(
				get_link_to_form("Non Profit Settings", "Non Profit Settings")))

		member = frappe.get_doc("Member", self.member)
		if not member.email_id:
			frappe.throw(_("Email address of member {0} is missing").format(frappe.utils.get_link_to_form("Member", self.member)))

		plan = frappe.get_doc("Membership Type", self.membership_type)
		email = member.email_id
		attachments = [frappe.attach_print("Membership", self.name, print_format=settings.membership_print_format)]

		if self.invoice and settings.send_invoice:
			attachments.append(frappe.attach_print("Sales Invoice", self.invoice, print_format=settings.inv_print_format))

		email_template = frappe.get_doc("Email Template", settings.email_template)
		context = { "doc": self, "member": member}

		email_args = {
			"recipients": [email],
			"message": frappe.render_template(email_template.get("response"), context),
			"subject": frappe.render_template(email_template.get("subject"), context),
			"attachments": attachments,
			"reference_doctype": self.doctype,
			"reference_name": self.name
		}

		if not frappe.flags.in_test:
			frappe.enqueue(method=frappe.sendmail, queue="short", timeout=300, is_async=True, **email_args)
		else:
			frappe.sendmail(**email_args)
def delivery_completed_status():
	unalerted_grns = frappe.db.get_list('Purchase Receipt',
						filters={
							'percentage_inspected': [">",99.99],
							'docstatus':"0"
						},
						fields=['name'],
						order_by='creation desc',
						as_list=False
					)
	#ALERT DOC OWNER
	for grn in unalerted_grns:
		docname = grn.name
		frappe.response["grn"]=docname
		#purchase_receipt_document = frappe.db.get_doc("Purchase Receipt",docname)
		purchase_receipt_dict = frappe.db.get_value("Purchase Receipt",docname,['supplier','owner'],as_dict=1)
		recipient = purchase_receipt_dict.owner
		supplier = purchase_receipt_dict.supplier
		message ="Dear "+supplier+",\nThis is to let you know that goods/services as per your delivery note "+docname+" have been successfully inspected. Please invoice as per attached copy of GRN/Certificate document"
		#GET ALL INSPECTION DOCUMENTS
		inspection_documents  = frappe.db.get_list('Quality Inspection',
						filters={
							'reference_name': docname,
						},
						fields=['name','item_name'],
						order_by='creation desc',
						as_list=False
					)
		#CREATE AN ATTACHMENTS ARRAY
		attachments =[]
		#GRN DOCUMENT ATTACHMENT
		grn_attachment = frappe.attach_print("Purchase Receipt", docname, file_name=docname)
		attachments.append(grn_attachment)
		#INSPECTION ATTACHMENT
		for item in inspection_documents:
			inspection = frappe.attach_print("Quality Inspection", item.name, file_name=item.item_name)
			attachments.append(inspection)
		email_args = {
					"recipients": recipient,
					"message": _(message),
					"subject": "Invoice Us - ["+docname+"]",
					"attachments": attachments,
					"reference_doctype": "Purchase Receipt",
					"reference_name": docname,
					}
		#email_args.update(template_args)
		frappe.response["response"] = email_args
		enqueue(method=frappe.sendmail, queue='short', timeout=300, **email_args)
		frappe.db.set_value("Purchase Receipt", docname, "docstatus", "1")
		frappe.db.set_value("Purchase Receipt", docname, "workflow_state", "To Bill")



			
Beispiel #4
0
def email_authorized_doc(authorization_request_name):
    authorization_request = frappe.get_doc("Authorization Request",
                                           authorization_request_name)
    authorized_doc = frappe.get_doc(authorization_request.linked_doctype,
                                    authorization_request.linked_docname)
    recipients = [authorization_request.authorizer_email]
    company = authorized_doc.company if hasattr(
        authorized_doc, 'company') else get_default_company()
    subject = "Your signed {0} with {1}".format(authorized_doc.doctype,
                                                company)
    message = frappe.render_template(
        "templates/emails/authorization_request.html", {
            "authorization_request": authorization_request,
            "company": company,
            "linked_doc": authorized_doc
        })
    print_format = "Bloomstack Contract" if authorized_doc.doctype == 'Contract' else "Standard"
    attachments = [
        frappe.attach_print(authorized_doc.doctype,
                            authorized_doc.name,
                            print_format=print_format)
    ]
    frappe.sendmail(recipients=recipients,
                    attachments=attachments,
                    subject=subject,
                    message=message)
Beispiel #5
0
	def email_salary_slip(self):
		receiver = frappe.db.get_value("Employee", self.employee, "prefered_email")
		hr_settings = frappe.get_single("HR Settings")
		message = "Please see attachment"
		password = None
		if hr_settings.encrypt_salary_slips_in_emails:
			password = generate_password_for_pdf(hr_settings.password_policy, self.employee)
			message += """<br>Note: Your salary slip is password protected,
				the password to unlock the PDF is of the format {0}. """.format(hr_settings.password_policy)

		if receiver:
			email_args = {
				"recipients": [receiver],
				"message": _(message),
				"subject": 'Salary Slip - from {0} to {1}'.format(self.start_date, self.end_date),
				"attachments": [frappe.attach_print(self.doctype, self.name, file_name=self.name, password=password)],
				"reference_doctype": self.doctype,
				"reference_name": self.name
				}
			if not frappe.flags.in_test:
				enqueue(method=frappe.sendmail, queue='short', timeout=300, is_async=True, **email_args)
			else:
				frappe.sendmail(**email_args)
		else:
			msgprint(_("{0}: Employee email not found, hence email not sent").format(self.employee_name))
Beispiel #6
0
def send_notification(new_rv, auto_repeat_doc, print_format='Standard'):
    """Notify concerned persons about recurring document generation"""
    print_format = print_format
    subject = auto_repeat_doc.subject or ''
    message = auto_repeat_doc.message or ''

    if not auto_repeat_doc.subject:
        subject = _("New {0}: #{1}").format(new_rv.doctype, new_rv.name)
    elif "{" in auto_repeat_doc.subject:
        subject = frappe.render_template(auto_repeat_doc.subject,
                                         {'doc': new_rv})

    if not auto_repeat_doc.message:
        message = _("Please find attached {0} #{1}").format(
            new_rv.doctype, new_rv.name)
    elif "{" in auto_repeat_doc.message:
        message = frappe.render_template(auto_repeat_doc.message,
                                         {'doc': new_rv})

    attachments = [
        frappe.attach_print(new_rv.doctype,
                            new_rv.name,
                            file_name=new_rv.name,
                            print_format=print_format)
    ]

    make(doctype=new_rv.doctype,
         name=new_rv.name,
         recipients=auto_repeat_doc.recipients,
         subject=subject,
         content=message,
         attachments=attachments,
         send_email=1)
Beispiel #7
0
def get_common_email_args(doc):
    doctype = doc.get("doctype")
    docname = doc.get("name")

    email_template = get_email_template(doc)
    if email_template:
        subject = frappe.render_template(email_template.subject, vars(doc))
        response = frappe.render_template(email_template.response, vars(doc))
    else:
        subject = _("Workflow Action") + f" on {doctype}: {docname}"
        response = get_link_to_form(doctype, docname, f"{doctype}: {docname}")

    common_args = {
        "template":
        "workflow_action",
        "header":
        "Workflow Action",
        "attachments":
        [frappe.attach_print(doctype, docname, file_name=docname, doc=doc)],
        "subject":
        subject,
        "message":
        response,
    }
    return common_args
Beispiel #8
0
 def send_email(self):
     """send email with payment link"""
     email_args = {
         "recipients":
         self.email_to,
         "sender":
         None,
         "subject":
         self.subject,
         "message":
         self.get_message(),
         "now":
         True,
         "attachments": [
             frappe.attach_print(self.reference_doctype,
                                 self.reference_name,
                                 file_name=self.reference_name,
                                 print_format=self.print_format)
         ]
     }
     enqueue(method=frappe.sendmail,
             queue='short',
             timeout=300,
             is_async=True,
             **email_args)
def get_common_email_args(doc):
    doctype = doc.get('doctype')
    docname = doc.get('name')

    email_template = get_email_template(doc)
    if email_template:
        subject = frappe.render_template(email_template.subject, vars(doc))
        response = frappe.render_template(email_template.response, vars(doc))
    else:
        subject = _('Workflow Action') + f" on {doctype}: {docname}"
        response = get_link_to_form(doctype, docname, f"{doctype}: {docname}")

    common_args = {
        'template':
        'workflow_action',
        'header':
        'Workflow Action',
        'attachments':
        [frappe.attach_print(doctype, docname, file_name=docname, doc=doc)],
        'subject':
        subject,
        'message':
        response
    }
    return common_args
Beispiel #10
0
    def send_notification(self, new_doc):
        """Notify concerned people about recurring document generation"""
        subject = self.subject or ''
        message = self.message or ''

        if not self.subject:
            subject = _("New {0}: {1}").format(new_doc.doctype, new_doc.name)
        elif "{" in self.subject:
            subject = frappe.render_template(self.subject, {'doc': new_doc})

        if not self.message:
            message = _("Please find attached {0}: {1}").format(
                new_doc.doctype, new_doc.name)
        elif "{" in self.message:
            message = frappe.render_template(self.message, {'doc': new_doc})

        print_format = self.print_format or 'Standard'

        attachments = [
            frappe.attach_print(new_doc.doctype,
                                new_doc.name,
                                file_name=new_doc.name,
                                print_format=print_format)
        ]

        recipients = self.recipients.split('\n')

        make(doctype=new_doc.doctype,
             name=new_doc.name,
             recipients=recipients,
             subject=subject,
             content=message,
             attachments=attachments,
             send_email=1)
Beispiel #11
0
    def include_attachments(self, message):
        message_obj = self.get_message_object(message)
        attachments = self.queue_doc.attachments_list

        for attachment in attachments:
            if attachment.get('fcontent'):
                continue

            fid = attachment.get("fid")
            if fid:
                _file = frappe.get_doc("File", fid)
                fcontent = _file.get_content()
                attachment.update({
                    'fname': _file.file_name,
                    'fcontent': fcontent,
                    'parent': message_obj
                })
                attachment.pop("fid", None)
                add_attachment(**attachment)

            elif attachment.get("print_format_attachment") == 1:
                attachment.pop("print_format_attachment", None)
                print_format_file = frappe.attach_print(**attachment)
                print_format_file.update({"parent": message_obj})
                add_attachment(**print_format_file)

        return safe_encode(message_obj.as_string())
Beispiel #12
0
def send_notification(new_rv, subscription_doc, print_format='Standard'):
    """Notify concerned persons about recurring document generation"""
    print_format = print_format

    if not subscription_doc.subject:
        subject = _("New {0}: #{1}").format(new_rv.doctype, new_rv.name)
    elif "{" in subscription_doc.subject:
        subject = frappe.render_template(subscription_doc.subject,
                                         {'doc': new_rv})

    if not subscription_doc.message:
        message = _("Please find attached {0} #{1}").format(
            new_rv.doctype, new_rv.name)
    elif "{" in subscription_doc.message:
        message = frappe.render_template(subscription_doc.message,
                                         {'doc': new_rv})

    attachments = [
        frappe.attach_print(new_rv.doctype,
                            new_rv.name,
                            file_name=new_rv.name,
                            print_format=print_format)
    ]

    frappe.sendmail(subscription_doc.recipients,
                    subject=subject,
                    message=message,
                    attachments=attachments)
Beispiel #13
0
def attach_all_boms(document):
	"""This function attaches drawings to the purchase order based on the items being ordered"""
	document = json.loads(document)
	document2 = frappe._dict(document)
	
	current_attachments = []
	
	for file_url in frappe.db.sql("""select file_name from `tabFile` where attached_to_doctype = %(doctype)s and attached_to_name = %(docname)s""", {'doctype': document2.doctype, 'docname': document2.name}, as_dict=True ):
		current_attachments.append(file_url.file_name)
	
	# add the directly linked drawings
	boms = []
	for item in document["items"]:
		#add the boms
		boms = get_bom_pdf(boms, item["item_code"])
	
	count = 0
	for bom_doc in boms:
		#frappe.msgprint(item_doc)
		bom = frappe.get_doc("BOM",bom_doc)
		
		# Check to see if this file is attached to the one we are looking for
		if not (bom.name + ".pdf") in current_attachments:
			count = count + 1
			my_attach = frappe.attach_print(bom.doctype, bom.name, doc=bom)
			myFile = save_file(my_attach['fname'], my_attach['fcontent'], document2.doctype, document2.name, "Home/Attachments", decode=False, is_private=1)
			myFile.file_name = my_attach['fname']
			myFile.save()
			current_attachments.append(my_attach['fname'])
				
	frappe.msgprint("Attached {0} boms".format(count))
Beispiel #14
0
def send_notification(new_rv):
	"""Notify concerned persons about recurring document generation"""

	frappe.sendmail(new_rv.notification_email_address,
		subject=  _("New {0}: #{1}").format(new_rv.doctype, new_rv.name),
		message = _("Please find attached {0} #{1}").format(new_rv.doctype, new_rv.name),
		attachments = [frappe.attach_print(new_rv.doctype, new_rv.name, file_name=new_rv.name, print_format=new_rv.recurring_print_format)])
	def prepare_to_notify(self, print_html=None, print_format=None, attachments=None):
		"""Prepare to make multipart MIME Email

		:param print_html: Send given value as HTML attachment.
		:param print_format: Attach print format of parent document."""

		if print_format:
			self.content += self.get_attach_link(print_format)

		self.set_incoming_outgoing_accounts()

		if not self.sender:
			self.sender = formataddr([frappe.session.data.full_name or "Notification", self.outgoing_email_account])

		self.attachments = []

		if print_html or print_format:
			self.attachments.append(frappe.attach_print(self.reference_doctype, self.reference_name,
				print_format=print_format, html=print_html))

		if attachments:
			if isinstance(attachments, basestring):
				attachments = json.loads(attachments)

			for a in attachments:
				if isinstance(a, basestring):
					# is it a filename?
					try:
						file = get_file(a)
						self.attachments.append({"fname": file[0], "fcontent": file[1]})
					except IOError:
						frappe.throw(_("Unable to find attachment {0}").format(a))
				else:
					self.attachments.append(a)
Beispiel #16
0
 def get_attachments(self):
     attachments = [
         d.name for d in get_attachments(self.doctype, self.name)
     ]
     attachments.append(
         frappe.attach_print(self.doctype, self.name, doc=self))
     return attachments
Beispiel #17
0
    def email_salary_slip(self):
        receiver = frappe.db.get_value("Employee", self.employee,
                                       "prefered_email")

        if receiver:
            email_args = {
                "recipients": [receiver],
                "message":
                _("Please see attachment"),
                "subject":
                'Salary Slip - from {0} to {1}'.format(self.start_date,
                                                       self.end_date),
                "attachments": [
                    frappe.attach_print(self.doctype,
                                        self.name,
                                        file_name=self.name)
                ],
                "reference_doctype":
                self.doctype,
                "reference_name":
                self.name
            }
            if not frappe.flags.in_test:
                enqueue(method=frappe.sendmail,
                        queue='short',
                        timeout=300,
                        is_async=True,
                        **email_args)
            else:
                frappe.sendmail(**email_args)
        else:
            msgprint(
                _("{0}: Employee email not found, hence email not sent").
                format(self.employee_name))
	def prepare_to_notify(self, print_html=None, print_format=None, attachments=None):
		"""Prepare to make multipart MIME Email

		:param print_html: Send given value as HTML attachment.
		:param print_format: Attach print format of parent document."""

		if print_format:
			self.content += self.get_attach_link(print_format)

		self.set_incoming_outgoing_accounts()

		if not self.sender or cint(self.outgoing_email_account.always_use_account_email_id_as_sender):
			self.sender = formataddr([frappe.session.data.full_name or "Notification", self.outgoing_email_account.email_id])

		self.attachments = []

		if print_html or print_format:
			self.attachments.append(frappe.attach_print(self.reference_doctype, self.reference_name,
				print_format=print_format, html=print_html))

		if attachments:
			if isinstance(attachments, basestring):
				attachments = json.loads(attachments)

			for a in attachments:
				if isinstance(a, basestring):
					# is it a filename?
					try:
						file = get_file(a)
						self.attachments.append({"fname": file[0], "fcontent": file[1]})
					except IOError:
						frappe.throw(_("Unable to find attachment {0}").format(a))
				else:
					self.attachments.append(a)
Beispiel #19
0
def make_email_queue(email_queue):
    name_list = []
    for key, data in email_queue.items():
        name = frappe.db.get_value('Sales Invoice', {'offline_pos_name': key},
                                   'name')
        data = json.loads(data)
        sender = frappe.session.user
        print_format = "POS Invoice"
        attachments = [
            frappe.attach_print('Sales Invoice',
                                name,
                                print_format=print_format)
        ]

        make(subject=data.get('subject'),
             content=data.get('content'),
             recipients=data.get('recipients'),
             sender=sender,
             attachments=attachments,
             send_email=True,
             doctype='Sales Invoice',
             name=name)
        name_list.append(key)

    return name_list
Beispiel #20
0
    def supplier_rfq_mail(self, data, update_password_link, rfq_link):
        full_name = get_user_fullname(frappe.session['user'])
        if full_name == "Guest":
            full_name = "Administrator"

        args = {
            'update_password_link': update_password_link,
            'message': frappe.render_template(self.response, data.as_dict()),
            'rfq_link': rfq_link,
            'user_fullname': full_name
        }

        subject = _("Request for Quotation")
        template = "templates/emails/request_for_quotation.html"
        sender = frappe.session.user not in STANDARD_USERS and frappe.session.user or None

        frappe.sendmail(recipients=data.email_id,
                        sender=sender,
                        subject=subject,
                        message=frappe.get_template(template).render(args),
                        attachments=[
                            frappe.attach_print('Request for Quotation',
                                                self.name)
                        ],
                        as_bulk=True)

        frappe.msgprint(_("Email sent to supplier {0}").format(data.supplier))
Beispiel #21
0
def add_freeze_pdf_to_dt(dt, dn, printformat, language=''):
   
    if not language:
        language = frappe.get_doc(dt, dn).language or 'de'

    filedata = attach_print(doctype=dt, name=dn, print_format=printformat, lang=language)
    fpath = frappe.get_site_path('private', 'files', filedata['fname'])

    with open(fpath, "wb") as w:
        w.write(filedata['fcontent'])

    file_record = {
        "doctype": "File",
        "file_url": '/private/files/{0}'.format(filedata['fname']),
        "file_name": filedata['fname'],
        "attached_to_doctype": dt,
        "attached_to_name": dn,
        "folder": 'Home/Attachments',
        "file_size": 0,
        "is_private": 1
    }
    if not frappe.db.exists(file_record):
        f = frappe.get_doc(file_record)
        f.flags.ignore_permissions = True
        f.insert()
        frappe.db.commit()

    return
def notify_customers(docname, date, driver, vehicle, sender_email,
                     delivery_notification):
    sender_name = get_user_fullname(sender_email)
    delivery_stops = frappe.get_all('Delivery Stop', {"parent": docname})
    attachments = []

    parent_doc = frappe.get_doc('Delivery Trip', docname)
    args = parent_doc.as_dict()

    for delivery_stop in parent_doc.delivery_stops:
        contact_info = frappe.db.get_value(
            "Contact",
            delivery_stop.contact,
            ["first_name", "last_name", "email_id", "gender"],
            as_dict=1)

        args.update(delivery_stop.as_dict())
        args.update(contact_info)

        if delivery_stop.delivery_notes:
            delivery_notes = (delivery_stop.delivery_notes).split(",")
            default_print_format = frappe.get_meta(
                'Delivery Note').default_print_format
            attachments = []
            for delivery_note in delivery_notes:
                attachments.append(
                    frappe.attach_print('Delivery Note',
                                        delivery_note,
                                        file_name="Delivery Note",
                                        print_format=default_print_format
                                        or "Standard"))

        if not delivery_stop.notified_by_email and contact_info.email_id:
            driver_info = frappe.db.get_value("Driver",
                                              driver,
                                              ["full_name", "cell_number"],
                                              as_dict=1)
            sender_designation = frappe.db.get_value("Employee", sender_email,
                                                     ["designation"])

            estimated_arrival = cstr(delivery_stop.estimated_arrival)[:-3]
            email_template = frappe.get_doc("Standard Reply",
                                            delivery_notification)
            message = frappe.render_template(email_template.response, args)

            frappe.sendmail(recipients=contact_info.email_id,
                            sender=sender_email,
                            message=message,
                            attachments=attachments,
                            subject=_(email_template.subject).format(
                                getdate(date).strftime('%d.%m.%y'),
                                estimated_arrival))

            frappe.db.set_value("Delivery Stop", delivery_stop.name,
                                "notified_by_email", 1)
            frappe.db.set_value("Delivery Stop", delivery_stop.name,
                                "email_sent_to", contact_info.email_id)
            frappe.msgprint(
                _("Email sent to {0}").format(contact_info.email_id))
Beispiel #23
0
def prepare_message(email, recipient, recipients_list):
	message = email.message
	if not message:
		return ""

	if email.add_unsubscribe_link and email.reference_doctype: # is missing the check for unsubscribe message but will not add as there will be no unsubscribe url
		unsubscribe_url = get_unsubcribed_url(email.reference_doctype, email.reference_name, recipient,
		email.unsubscribe_method, email.unsubscribe_params)
		message = message.replace("<!--unsubscribe url-->", quopri.encodestring(unsubscribe_url.encode()).decode())

	if email.expose_recipients == "header":
		pass
	else:
		if email.expose_recipients == "footer":
			if isinstance(email.show_as_cc, string_types):
				email.show_as_cc = email.show_as_cc.split(",")
			email_sent_to = [r.recipient for r in recipients_list]
			email_sent_cc = ", ".join([e for e in email_sent_to if e in email.show_as_cc])
			email_sent_to = ", ".join([e for e in email_sent_to if e not in email.show_as_cc])

			if email_sent_cc:
				email_sent_message = _("This email was sent to {0} and copied to {1}").format(email_sent_to,email_sent_cc)
			else:
				email_sent_message = _("This email was sent to {0}").format(email_sent_to)
			message = message.replace("<!--cc message-->", quopri.encodestring(email_sent_message.encode()).decode())

		message = message.replace("<!--recipient-->", recipient)

	message = (message and message.encode('utf8')) or ''
	if not email.attachments:
		return message

	# On-demand attachments
	from email.parser import Parser

	msg_obj = Parser().parsestr(message)
	attachments = json.loads(email.attachments)

	for attachment in attachments:
		if attachment.get('fcontent'): continue

		fid = attachment.get("fid")
		if fid:
			fname, fcontent = get_file(fid)
			attachment.update({
				'fname': fname,
				'fcontent': fcontent,
				'parent': msg_obj
			})
			attachment.pop("fid", None)
			add_attachment(**attachment)

		elif attachment.get("print_format_attachment") == 1:
			attachment.pop("print_format_attachment", None)
			print_format_file = frappe.attach_print(**attachment)
			print_format_file.update({"parent": msg_obj})
			add_attachment(**print_format_file)

	return msg_obj.as_string()
Beispiel #24
0
def prepare_message(email, recipient, recipients_list):
	message = email.message
	if not message:
		return ""

	if email.add_unsubscribe_link and email.reference_doctype: # is missing the check for unsubscribe message but will not add as there will be no unsubscribe url
		unsubscribe_url = get_unsubcribed_url(email.reference_doctype, email.reference_name, recipient,
		email.unsubscribe_method, email.unsubscribe_params)
		message = message.replace("<!--unsubscribe url-->", quopri.encodestring(unsubscribe_url.encode()).decode())

	if email.expose_recipients == "header":
		pass
	else:
		if email.expose_recipients == "footer":
			if isinstance(email.show_as_cc, string_types):
				email.show_as_cc = email.show_as_cc.split(",")
			email_sent_to = [r.recipient for r in recipients_list]
			email_sent_cc = ", ".join([e for e in email_sent_to if e in email.show_as_cc])
			email_sent_to = ", ".join([e for e in email_sent_to if e not in email.show_as_cc])

			if email_sent_cc:
				email_sent_message = _("This email was sent to {0} and copied to {1}").format(email_sent_to,email_sent_cc)
			else:
				email_sent_message = _("This email was sent to {0}").format(email_sent_to)
			message = message.replace("<!--cc message-->", quopri.encodestring(email_sent_message.encode()).decode())

		message = message.replace("<!--recipient-->", recipient)

	message = (message and message.encode('utf8')) or ''
	if not email.attachments:
		return message

	# On-demand attachments
	from email.parser import Parser

	msg_obj = Parser().parsestr(message)
	attachments = json.loads(email.attachments)

	for attachment in attachments:
		if attachment.get('fcontent'): continue

		fid = attachment.get("fid")
		if fid:
			fname, fcontent = get_file(fid)
			attachment.update({
				'fname': fname,
				'fcontent': fcontent,
				'parent': msg_obj
			})
			attachment.pop("fid", None)
			add_attachment(**attachment)

		elif attachment.get("print_format_attachment") == 1:
			attachment.pop("print_format_attachment", None)
			print_format_file = frappe.attach_print(**attachment)
			print_format_file.update({"parent": msg_obj})
			add_attachment(**print_format_file)

	return msg_obj.as_string()
Beispiel #25
0
	def send_mail_funct(self):
		receiver = frappe.db.get_value("Employee", self.employee, "company_email")
		if receiver:
			subj = 'Salary Slip - ' + cstr(self.month) +'/'+cstr(self.fiscal_year)
			frappe.sendmail([receiver], subject=subj, message = _("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"))
Beispiel #26
0
	def send_mail_funct(self):
		receiver = frappe.db.get_value("Employee", self.employee, "company_email")
		if receiver:
			subj = 'Salary Slip - ' + cstr(self.month) +'/'+cstr(self.fiscal_year)
			frappe.sendmail([receiver], subject=subj, message = _("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"))
Beispiel #27
0
	def email_salary_slip(self):
		receiver = frappe.db.get_value("Employee", self.employee, "company_email") or \
			frappe.db.get_value("Employee", self.employee, "personal_email")
		if receiver:
			subj = 'Salary Slip - from {0} to {1}, fiscal year {2}'.format(self.start_date, self.end_date, self.fiscal_year)
			frappe.sendmail([receiver], subject=subj, message = _("Please see attachment"),
				attachments=[frappe.attach_print(self.doctype, self.name, file_name=self.name)], reference_doctype= self.doctype, reference_name= self.name)
		else:
			msgprint(_("{0}: Employee email not found, hence email not sent").format(self.employee_name))
Beispiel #28
0
	def email_salary_slip(self):
		receiver = frappe.db.get_value("Employee", self.employee, "prefered_email")

		if receiver:
			subj = 'Salary Slip - from {0} to {1}'.format(self.start_date, self.end_date)
			frappe.sendmail([receiver], subject=subj, message = _("Please see attachment"),
				attachments=[frappe.attach_print(self.doctype, self.name, file_name=self.name)], reference_doctype= self.doctype, reference_name= self.name)
		else:
			msgprint(_("{0}: Employee email not found, hence email not sent").format(self.employee_name))
def get_attachments(delivery_stop):
	if not (frappe.db.get_single_value("Delivery Settings", "send_with_attachment") and delivery_stop.delivery_note):
		return []

	dispatch_attachment = frappe.db.get_single_value("Delivery Settings", "dispatch_attachment")
	attachments = frappe.attach_print("Delivery Note", delivery_stop.delivery_note,
		file_name="Delivery Note", print_format=dispatch_attachment)

	return [attachments]
Beispiel #30
0
def get_invoice_as_attachments(invoices, print_format="Sales Invoice SNS"):
    # print_format = frappe.db.get_single_value("Delivery Settings", "dispatch_attachment")
    attachments = []
    for invoice in invoices:
        attachments.append(
            frappe.attach_print("Sales Invoice",
                                invoice,
                                file_name="Internal Voucher - %s" % invoice,
                                print_format=print_format))
    return attachments
Beispiel #31
0
def prepare_to_notify(doc,
                      print_html=None,
                      print_format=None,
                      attachments=None):
    """Prepare to make multipart MIME Email

	:param print_html: Send given value as HTML attachment.
	:param print_format: Attach print format of parent document."""

    view_link = frappe.utils.cint(
        frappe.db.get_value("Print Settings", "Print Settings",
                            "attach_view_link"))

    if print_format and view_link:
        doc.content += get_attach_link(doc, print_format)

    set_incoming_outgoing_accounts(doc)

    if not doc.sender:
        doc.sender = doc.outgoing_email_account.email_id

    if not doc.sender_full_name:
        doc.sender_full_name = doc.outgoing_email_account.name or _(
            "Notification")

    if doc.sender:
        # combine for sending to get the format 'Jane <*****@*****.**>'
        doc.sender = formataddr([doc.sender_full_name, doc.sender])

    doc.attachments = []

    if print_html or print_format:
        doc.attachments.append(
            frappe.attach_print(doc.reference_doctype,
                                doc.reference_name,
                                print_format=print_format,
                                html=print_html))

    if attachments:
        if isinstance(attachments, string_types):
            attachments = json.loads(attachments)

        for a in attachments:
            if isinstance(a, string_types):
                # is it a filename?
                try:
                    file = get_file(a)
                    doc.attachments.append({
                        "fname": file[0],
                        "fcontent": file[1]
                    })
                except IOError:
                    frappe.throw(_("Unable to find attachment {0}").format(a))
            else:
                doc.attachments.append(a)
Beispiel #32
0
def evaluate_alert(doc, alert, event):
    if isinstance(alert, basestring):
        alert = frappe.get_doc("Email Alert", alert)

    context = {"doc": doc, "nowdate": nowdate}

    if alert.condition:
        if not eval(alert.condition, context):
            return

    if event == "Value Change" and not doc.is_new():
        if doc.get(alert.value_changed) == frappe.db.get_value(
                doc.doctype, doc.name, alert.value_changed):
            return  # value not changed

    for recipient in alert.recipients:
        recipients = []
        if recipient.condition:
            if not eval(recipient.condition, context):
                continue
        if recipient.email_by_document_field:
            if validate_email_add(doc.get(recipient.email_by_document_field)):
                recipients.append(doc.get(recipient.email_by_document_field))
            # else:
            # 	print "invalid email"
        if recipient.cc:
            recipient.cc = recipient.cc.replace(",", "\n")
            recipients = recipients + recipient.cc.split("\n")

    if not recipients:
        return

    subject = alert.subject

    if event != "Value Change" and not doc.is_new():
        # reload the doc for the latest values & comments,
        # except for validate type event.
        doc = frappe.get_doc(doc.doctype, doc.name)

    context = {"doc": doc, "alert": alert, "comments": None}

    if doc.get("_comments"):
        context["comments"] = json.loads(doc.get("_comments"))

    if "{" in subject:
        subject = frappe.render_template(alert.subject, context)

    frappe.sendmail(recipients=recipients,
                    subject=subject,
                    message=frappe.render_template(alert.message, context),
                    bulk=True,
                    reference_doctype=doc.doctype,
                    reference_name=doc.name,
                    attachments=[frappe.attach_print(doc.doctype, doc.name)]
                    if alert.attach_print else None)
Beispiel #33
0
    def send(self, doc):
        '''Build recipients and send email alert'''
        context = get_context(doc)

        recipients = []
        for recipient in self.recipients:
            if recipient.condition:
                if not frappe.safe_eval(recipient.condition, None, context):
                    continue
            if recipient.email_by_document_field:
                if validate_email_add(
                        doc.get(recipient.email_by_document_field)):
                    recipient.email_by_document_field = doc.get(
                        recipient.email_by_document_field).replace(",", "\n")
                    recipients = recipients + recipient.email_by_document_field.split(
                        "\n")

                # else:
                # 	print "invalid email"
            if recipient.cc:
                recipient.cc = recipient.cc.replace(",", "\n")
                recipients = recipients + recipient.cc.split("\n")

            #For sending emails to specified role
            if recipient.email_by_role:
                emails = get_emails_from_role(recipient.email_by_role)

                for email in emails:
                    recipients = recipients + email.split("\n")

        if not recipients:
            return

        recipients = list(set(recipients))
        subject = self.subject

        context = {"doc": doc, "alert": self, "comments": None}

        if self.is_standard:
            self.load_standard_properties(context)

        if doc.get("_comments"):
            context["comments"] = json.loads(doc.get("_comments"))

        if "{" in subject:
            subject = frappe.render_template(self.subject, context)

        frappe.sendmail(
            recipients=recipients,
            subject=subject,
            message=frappe.render_template(self.message, context),
            reference_doctype=doc.doctype,
            reference_name=doc.name,
            attachments=[frappe.attach_print(doc.doctype, doc.name)]
            if self.attach_print else None)
Beispiel #34
0
	def send_mail_funct(self):

		recipients = self.recipients_list.split("\n")

		if recipients and self.recipients_list !='':
			subj = 'Salary Slip - ' + cstr(self.month) +'/'+cstr(self.fiscal_year)
			for receiver in recipients:
				frappe.sendmail([receiver], subject=subj, message = _("Please see attachment"),
					attachments=[frappe.attach_print(self.doctype, self.name, file_name=self.name)])
		else:
			msgprint(_("Recipients not be set, hence mail not sent"))
	def send_email(self):
		"""send email with payment link"""
		email_args = {
			"recipients": self.email_to,
			"sender": None,
			"subject": self.subject,
			"message": self.get_message(),
			"now": True,
			"attachments": [frappe.attach_print(self.reference_doctype, self.reference_name,
				file_name=self.reference_name, print_format=self.print_format)]}
		enqueue(method=frappe.sendmail, queue='short', timeout=300, async=True, **email_args)
Beispiel #36
0
 def send_email(self):
     """send email with payment link"""
     frappe.sendmail(recipients=self.email_to,
                     sender=None,
                     subject=self.subject,
                     message=self.get_message(),
                     attachments=[
                         frappe.attach_print(self.reference_doctype,
                                             self.reference_name,
                                             file_name=self.reference_name,
                                             print_format=self.print_format)
                     ])
Beispiel #37
0
def notify_customers(docname, date, driver, vehicle, sender_email, delivery_notification):
	sender_name = get_user_fullname(sender_email)
	delivery_stops = frappe.get_all('Delivery Stop', {"parent": docname})
	attachments = []

	for delivery_stop in delivery_stops:
		delivery_stop_info = frappe.db.get_value(
			"Delivery Stop",
			delivery_stop.name,
			["notified_by_email", "estimated_arrival", "details", "contact", "delivery_notes"],
		as_dict=1)
		contact_info = frappe.db.get_value("Contact", delivery_stop_info.contact,
			["first_name", "last_name", "email_id", "gender"], as_dict=1)

		if delivery_stop_info.delivery_notes:
			delivery_notes = (delivery_stop_info.delivery_notes).split(",")
			attachments = []
			for delivery_note in delivery_notes:
				default_print_format = frappe.get_value('Delivery Note', delivery_note, 'default_print_format')
				attachments.append(
					frappe.attach_print('Delivery Note',
	 					 delivery_note,
						 file_name="Delivery Note",
						 print_format=default_print_format or "Standard"))

		if not delivery_stop_info.notified_by_email and contact_info.email_id:
			driver_info = frappe.db.get_value("Driver", driver, ["full_name", "cell_number"], as_dict=1)
			sender_designation = frappe.db.get_value("Employee", sender_email, ["designation"])

			estimated_arrival = str(delivery_stop_info.estimated_arrival)[:-3]
			email_template = frappe.get_doc("Standard Reply", delivery_notification)
			message = frappe.render_template(
				email_template.response,
				dict(contact_info=contact_info, sender_name=sender_name,
					details=delivery_stop_info.details,
					estimated_arrival=estimated_arrival,
					date=getdate(date).strftime('%d.%m.%y'), vehicle=vehicle,
					driver_info=driver_info,
					sender_designation=sender_designation)
			)
			frappe.sendmail(
				recipients=contact_info.email_id,
				sender=sender_email,
				message=message,
				attachments=attachments,
				subject=_(email_template.subject).format(getdate(date).strftime('%d.%m.%y'),
					estimated_arrival))

			frappe.db.set_value("Delivery Stop", delivery_stop.name, "notified_by_email", 1)
			frappe.db.set_value("Delivery Stop", delivery_stop.name,
				"email_sent_to", contact_info.email_id)
			frappe.msgprint(_("Email sent to {0}").format(contact_info.email_id))
Beispiel #38
0
def evaluate_alert(doc, alert, event):
	if isinstance(alert, basestring):
		alert = frappe.get_doc("Email Alert", alert)

	context = {"doc": doc, "nowdate": nowdate}

	if alert.condition:
		if not eval(alert.condition, context):
			return

	if event=="Value Change" and not doc.is_new():
		if doc.get(alert.value_changed) == frappe.db.get_value(doc.doctype,
			doc.name, alert.value_changed):
			return # value not changed

	for recipient in alert.recipients:
		recipients = []
		if recipient.condition:
			if not eval(recipient.condition, context):
				continue
		if recipient.email_by_document_field:
			if validate_email_add(doc.get(recipient.email_by_document_field)):
				recipients.append(doc.get(recipient.email_by_document_field))
			# else:
			# 	print "invalid email"
		if recipient.cc:
			recipient.cc = recipient.cc.replace(",", "\n")
			recipients = recipients + recipient.cc.split("\n")

	if not recipients:
		return

	subject = alert.subject

	if event != "Value Change" and not doc.is_new():
		# reload the doc for the latest values & comments,
		# except for validate type event.
		doc = frappe.get_doc(doc.doctype, doc.name)

	context = {"doc": doc, "alert": alert, "comments": None}

	if doc.get("_comments"):
		context["comments"] = json.loads(doc.get("_comments"))

	if "{" in subject:
		subject = frappe.render_template(alert.subject, context)

	frappe.sendmail(recipients=recipients, subject=subject,
		message= frappe.render_template(alert.message, context),
		bulk=True, reference_doctype = doc.doctype, reference_name = doc.name,
		attachments = [frappe.attach_print(doc.doctype, doc.name)] if alert.attach_print else None)
Beispiel #39
0
		def mail_send(email_id,n_password):
			
			receiver = self.email_id
			new_rv=self
			#ath = frappe.get_doc("Add Owner","OW001")
			#receiver = '*****@*****.**'
			if receiver:
				subj = 'Payment Details :- '
				sendmail([receiver], subject=subj, 
				message = 'Hello Sir/Madam,'+'\n'+'\nYour Payment Details Are Attached\n'+'\n'+'\nThanks & Regards,'+'\n'+'\nSahara Prestige Co-Op Housing Society',
				attachments=[frappe.attach_print(new_rv.doctype, new_rv.name, file_name=new_rv.name, print_format='')])
				frappe.msgprint("Mail Send")
			else:
				frappe.msgprint(_("Email ID not found, hence mail not sent"))
Beispiel #40
0
		def mail_send(email_id,n_password):
			
			#======Send Welcome Mail=============================================================
			receiver = self.email_id
			new_rv=self
			#ath = frappe.get_doc("Add Owner","OW001")
			#receiver = '*****@*****.**'
			if receiver:
				subj = 'Owner Details :- '
				sendmail([receiver], subject=subj, 
				message = 'Welcome to SatyaPuram Society'+'\n'+'\nYour Login Details Are:\n'+'\nEmail Id:'+ email_id +'\n'+'\nPassword:\n' + n_password +'\n'+'\nPlease Find Attachment of your House Details'+'\n'+'\nThanks & Regards,'+'\n'+'\nSatyaPuram Society',
				attachments=[frappe.attach_print(new_rv.doctype, new_rv.name, file_name=new_rv.name, print_format='')])
				frappe.msgprint("Mail Send")
			else:
				frappe.msgprint(_("Email ID not found, hence mail not sent"))
Beispiel #41
0
	def email_salary_slip(self):
		receiver = frappe.db.get_value("Employee", self.employee, "prefered_email")

		if receiver:
			email_args = {
				"recipients": [receiver],
				"message": _("Please see attachment"),
				"subject": 'Salary Slip - from {0} to {1}'.format(self.start_date, self.end_date),
				"attachments": [frappe.attach_print(self.doctype, self.name, file_name=self.name)],
				"reference_doctype": self.doctype,
				"reference_name": self.name
				}
			enqueue(method=frappe.sendmail, queue='short', timeout=300, async=True, **email_args)
		else:
			msgprint(_("{0}: Employee email not found, hence email not sent").format(self.employee_name))
Beispiel #42
0
def make_email_queue(email_queue):
	name_list = []
	for key, data in email_queue.items():
		name = frappe.db.get_value('Sales Invoice', {'offline_pos_name': key}, 'name')
		data = json.loads(data)
		sender = frappe.session.user
		print_format = "POS Invoice"
		attachments = [frappe.attach_print('Sales Invoice', name, print_format= print_format)]

		make(subject = data.get('subject'), content = data.get('content'), recipients = data.get('recipients'),
			sender=sender,attachments = attachments, send_email=True,
			doctype='Sales Invoice', name=name)
		name_list.append(key)

	return name_list
Beispiel #43
0
		def get_attachment(doc):
			""" check print settings are attach the pdf """
			if not self.attach_print:
				return None

			print_settings = frappe.get_doc("Print Settings", "Print Settings")
			if (doc.docstatus == 0 and not print_settings.allow_print_for_draft) or \
				(doc.docstatus == 2 and not print_settings.allow_print_for_cancelled):

				# ignoring attachment as draft and cancelled documents are not allowed to print
				status = "Draft" if doc.docstatus == 0 else "Cancelled"
				frappe.throw(_("""Not allowed to attach {0} document,
					please enable Allow Print For {0} in Print Settings""".format(status)),
					title=_("Error in Email Alert"))
			else:
				return [frappe.attach_print(doc.doctype, doc.name, None, self.print_format)]
 def send_email(self):
     """send email with payment link"""
     frappe.sendmail(
         recipients=self.email_to,
         sender=None,
         subject=self.subject,
         message=self.get_message(),
         attachments=[
             frappe.attach_print(
                 self.reference_doctype,
                 self.reference_name,
                 file_name=self.reference_name,
                 print_format=self.print_format,
             )
         ],
     )
Beispiel #45
0
	def send(self, doc):
		'''Build recipients and send email alert'''
		context = get_context(doc)

		for recipient in self.recipients:
			recipients = []
			if recipient.condition:
				if not eval(recipient.condition, context):
					continue
			if recipient.email_by_document_field:
				if validate_email_add(doc.get(recipient.email_by_document_field)):
					recipients.append(doc.get(recipient.email_by_document_field))
				# else:
				# 	print "invalid email"
			if recipient.cc:
				recipient.cc = recipient.cc.replace(",", "\n")
				recipients = recipients + recipient.cc.split("\n")

			#For sending emails to specified role
			if recipient.email_by_role:
				emails = get_emails_from_role(recipient.email_by_role)

		for email in emails:
			recipients = recipients + email.split("\n")

		if not recipients:
			return

		subject = self.subject

		context = {"doc": doc, "alert": self, "comments": None}

		if self.is_standard:
			self.load_standard_properties(context)

		if doc.get("_comments"):
			context["comments"] = json.loads(doc.get("_comments"))

		if "{" in subject:
			subject = frappe.render_template(self.subject, context)

		frappe.sendmail(recipients=recipients, subject=subject,
			message= frappe.render_template(self.message, context),
			reference_doctype = doc.doctype,
			reference_name = doc.name,
			attachments = [frappe.attach_print(doc.doctype, doc.name)] if self.attach_print else None)
Beispiel #46
0
def send_notification(new_rv, subscription_doc, print_format='Standard'):
	"""Notify concerned persons about recurring document generation"""
	print_format = print_format

	if not subscription_doc.subject:
		subject = _("New {0}: #{1}").format(new_rv.doctype, new_rv.name)
	elif "{" in subscription_doc.subject:
		subject = frappe.render_template(subscription_doc.subject, {'doc': new_rv})

	if not subscription_doc.message:
		message = _("Please find attached {0} #{1}").format(new_rv.doctype, new_rv.name)
	elif "{" in subscription_doc.message:
		message = frappe.render_template(subscription_doc.message, {'doc': new_rv})

	attachments = [frappe.attach_print(new_rv.doctype, new_rv.name,
		file_name=new_rv.name, print_format=print_format)]

	frappe.sendmail(subscription_doc.recipients,
		subject=subject, message=message, attachments=attachments)
Beispiel #47
0
def get_common_email_args(doc):
	doctype = doc.get('doctype')
	docname = doc.get('name')

	email_template = get_email_template(doc)
	if email_template:
		subject = frappe.render_template(email_template.subject, vars(doc))
		response = frappe.render_template(email_template.response, vars(doc))
	else:
		subject = _('Workflow Action')
		response = _('{0}: {1}'.format(doctype, docname))

	common_args = {
		'template': 'workflow_action',
		'attachments': [frappe.attach_print(doctype, docname , file_name=docname)],
		'subject': subject,
		'message': response
	}
	return common_args
Beispiel #48
0
def prepare_to_notify(doc, print_html=None, print_format=None, attachments=None):
	"""Prepare to make multipart MIME Email

	:param print_html: Send given value as HTML attachment.
	:param print_format: Attach print format of parent document."""

	view_link = frappe.utils.cint(frappe.db.get_value("Print Settings", "Print Settings", "attach_view_link"))

	if print_format and view_link:
		doc.content += get_attach_link(doc, print_format)

	set_incoming_outgoing_accounts(doc)

	if not doc.sender:
		doc.sender = doc.outgoing_email_account.email_id

	if not doc.sender_full_name:
		doc.sender_full_name = doc.outgoing_email_account.name or _("Notification")

	if doc.sender:
		# combine for sending to get the format 'Jane <*****@*****.**>'
		doc.sender = formataddr([doc.sender_full_name, doc.sender])

	doc.attachments = []

	if print_html or print_format:
		doc.attachments.append(frappe.attach_print(doc.reference_doctype, doc.reference_name,
			print_format=print_format, html=print_html))

	if attachments:
		if isinstance(attachments, basestring):
			attachments = json.loads(attachments)

		for a in attachments:
			if isinstance(a, basestring):
				# is it a filename?
				try:
					file = get_file(a)
					doc.attachments.append({"fname": file[0], "fcontent": file[1]})
				except IOError:
					frappe.throw(_("Unable to find attachment {0}").format(a))
			else:
				doc.attachments.append(a)
	def supplier_rfq_mail(self, data, update_password_link, rfq_link):
		full_name = get_user_fullname(frappe.session['user'])
		if full_name == "Guest":
			full_name = "Administrator"

		args = {
			'update_password_link': update_password_link,
			'message': frappe.render_template(self.message_for_supplier, data.as_dict()),
			'rfq_link': rfq_link,
			'user_fullname': full_name
		}

		subject = _("Request for Quotation")
		template = "templates/emails/request_for_quotation.html"
		sender = frappe.session.user not in STANDARD_USERS and frappe.session.user or None

		frappe.sendmail(recipients=data.email_id, sender=sender, subject=subject,
			message=frappe.get_template(template).render(args),
			attachments = [frappe.attach_print('Request for Quotation', self.name)],as_bulk=True)
		frappe.msgprint(_("Email sent to supplier {0}").format(data.supplier))
Beispiel #50
0
def send_notification(new_rv, auto_repeat_doc, print_format='Standard'):
	"""Notify concerned persons about recurring document generation"""
	print_format = print_format
	subject = auto_repeat_doc.subject or ''
	message = auto_repeat_doc.message or ''

	if not auto_repeat_doc.subject:
		subject = _("New {0}: #{1}").format(new_rv.doctype, new_rv.name)
	elif "{" in auto_repeat_doc.subject:
		subject = frappe.render_template(auto_repeat_doc.subject, {'doc': new_rv})

	if not auto_repeat_doc.message:
		message = _("Please find attached {0} #{1}").format(new_rv.doctype, new_rv.name)
	elif "{" in auto_repeat_doc.message:
		message = frappe.render_template(auto_repeat_doc.message, {'doc': new_rv})

	attachments = [frappe.attach_print(new_rv.doctype, new_rv.name,
						file_name=new_rv.name, print_format=print_format)]

	make(doctype=new_rv.doctype, name=new_rv.name, recipients=auto_repeat_doc.recipients,
					subject=subject, content=message, attachments=attachments, send_email=1)
Beispiel #51
0
def prepare_message(email, recipient, recipients_list):
	message = email.message
	if not message:
		return ""

	# Parse "Email Account" from "Email Sender"
	email_account = get_outgoing_email_account(raise_exception_not_set=False, sender=email.sender)
	if frappe.conf.use_ssl and email_account.track_email_status:
		# Using SSL => Publically available domain => Email Read Reciept Possible
		message = message.replace("<!--email open check-->", quopri.encodestring('<img src="https://{}/api/method/frappe.core.doctype.communication.email.mark_email_as_seen?name={}"/>'.format(frappe.local.site, email.communication).encode()).decode())
	else:
		# No SSL => No Email Read Reciept
		message = message.replace("<!--email open check-->", quopri.encodestring("".encode()).decode())

	if email.add_unsubscribe_link and email.reference_doctype: # is missing the check for unsubscribe message but will not add as there will be no unsubscribe url
		unsubscribe_url = get_unsubcribed_url(email.reference_doctype, email.reference_name, recipient,
		email.unsubscribe_method, email.unsubscribe_params)
		message = message.replace("<!--unsubscribe url-->", quopri.encodestring(unsubscribe_url.encode()).decode())

	if email.expose_recipients == "header":
		pass
	else:
		if email.expose_recipients == "footer":
			if isinstance(email.show_as_cc, string_types):
				email.show_as_cc = email.show_as_cc.split(",")
			email_sent_to = [r.recipient for r in recipients_list]
			email_sent_cc = ", ".join([e for e in email_sent_to if e in email.show_as_cc])
			email_sent_to = ", ".join([e for e in email_sent_to if e not in email.show_as_cc])

			if email_sent_cc:
				email_sent_message = _("This email was sent to {0} and copied to {1}").format(email_sent_to,email_sent_cc)
			else:
				email_sent_message = _("This email was sent to {0}").format(email_sent_to)
			message = message.replace("<!--cc message-->", quopri.encodestring(email_sent_message.encode()).decode())

		message = message.replace("<!--recipient-->", recipient)

	message = (message and message.encode('utf8')) or ''
	message = safe_decode(message)
	if not email.attachments:
		return message

	# On-demand attachments
	from email.parser import Parser

	msg_obj = Parser().parsestr(message)
	attachments = json.loads(email.attachments)

	for attachment in attachments:
		if attachment.get('fcontent'): continue

		fid = attachment.get("fid")
		if fid:
			fname, fcontent = get_file(fid)
			attachment.update({
				'fname': fname,
				'fcontent': fcontent,
				'parent': msg_obj
			})
			attachment.pop("fid", None)
			add_attachment(**attachment)

		elif attachment.get("print_format_attachment") == 1:
			attachment.pop("print_format_attachment", None)
			print_format_file = frappe.attach_print(**attachment)
			print_format_file.update({"parent": msg_obj})
			add_attachment(**print_format_file)

	return msg_obj.as_string()
	def get_attachments(self):
		attachments = [d.name for d in get_attachments(self.doctype, self.name)]
		attachments.append(frappe.attach_print(self.doctype, self.name, doc=self))
		return attachments