def add(email, sender, subject, formatted, text_content=None, ref_doctype=None, ref_docname=None): """add to bulk mail queue""" e = frappe.doc('Bulk Email') e.sender = sender e.recipient = email try: e.message = get_email(email, sender=e.sender, formatted=formatted, subject=subject, text_content=text_content).as_string() except frappe.ValidationError: # bad email id - don't add to queue return e.status = 'Not Sent' e.ref_doctype = ref_doctype e.ref_docname = ref_docname e.save()
def send_comm_email(d, name, sent_via=None, print_html=None, print_format=None, attachments='[]', send_me_a_copy=False): footer = None if sent_via: if hasattr(sent_via, "get_sender"): d.sender = sent_via.get_sender(d) or d.sender if hasattr(sent_via, "get_subject"): d.subject = sent_via.get_subject(d) if hasattr(sent_via, "get_content"): d.content = sent_via.get_content(d) footer = "<hr>" + set_portal_link(sent_via, d) mail = get_email(d.recipients, sender=d.sender, subject=d.subject, msg=d.content, footer=footer) if send_me_a_copy: mail.cc.append(frappe.db.get_value("User", frappe.session.user, "email")) if print_html or print_format: attach_print(mail, sent_via, print_html, print_format) for a in json.loads(attachments): try: mail.attach_file(a) except IOError: frappe.throw(_("Unable to find attachment {0}").format(a)) send(mail)
def send_comm_email(d, name, sent_via=None, print_html=None, attachments='[]', send_me_a_copy=False): footer = None if sent_via: if hasattr(sent_via, "get_sender"): d.sender = sent_via.get_sender(d) or d.sender if hasattr(sent_via, "get_subject"): d.subject = sent_via.get_subject(d) if hasattr(sent_via, "get_content"): d.content = sent_via.get_content(d) footer = set_portal_link(sent_via, d) send_print_in_body = frappe.db.get_value("Email Settings", None, "send_print_in_body_and_attachment") if not send_print_in_body: d.content += "<p>Please see attachment for document details.</p>" mail = get_email(d.recipients, sender=d.sender, subject=d.subject, msg=d.content, footer=footer, print_html=print_html if send_print_in_body else None) if send_me_a_copy: mail.cc.append(frappe.db.get_value("Profile", frappe.session.user, "email")) if print_html: print_html = scrub_urls(print_html) mail.add_attachment(name.replace(' ','').replace('/','-') + '.html', print_html) for a in json.loads(attachments): try: mail.attach_file(a) except IOError, e: frappe.msgprint("""Unable to find attachment %s. Please resend without attaching this file.""" % a, raise_exception=True)
def send_comm_email(d, name, sent_via=None, print_html=None, attachments='[]', send_me_a_copy=False): footer = None if sent_via: if hasattr(sent_via, "get_sender"): d.sender = sent_via.get_sender(d) or d.sender if hasattr(sent_via, "get_subject"): d.subject = sent_via.get_subject(d) if hasattr(sent_via, "get_content"): d.content = sent_via.get_content(d) footer = set_portal_link(sent_via, d) send_print_in_body = frappe.db.get_value("Outgoing Email Settings", None, "send_print_in_body_and_attachment") if not send_print_in_body: d.content += "<p>Please see attachment for document details.</p>" mail = get_email(d.recipients, sender=d.sender, subject=d.subject, msg=d.content, footer=footer, print_html=print_html if send_print_in_body else None) if send_me_a_copy: mail.cc.append(frappe.db.get_value("User", frappe.session.user, "email")) if print_html: print_html = scrub_urls(print_html) mail.add_attachment(name.replace(' ','').replace('/','-') + '.html', print_html) for a in json.loads(attachments): try: mail.attach_file(a) except IOError: frappe.throw(_("Unable to find attachment {0}").format(a)) send(mail)
def execute(): for customer_docs in frappe.db.sql(""" select DISTINCT gr.customer from `tabGoods Receipt` gr left join `tabCustomer` c on c.name=gr.customer where gr.posting_date between '2015-01-01' and '2015-03-31' and c.customer_group not in ('pallav singla', 'BADDI', 'SANGRUR', 'HARIDIYA', 'NOIDA'); """, as_dict=True): mail = get_email( get_recipients(customer_docs.customer), sender='*****@*****.**', subject= 'Shifting to Paper-less transactions / e-challans from 01.04.2016', msg=""" We are thankful to you for supporting us in last financial year. We request you to please give the same support in the new Financial year 2016-17 to achieve new heights as a team. AS EARLIER COMMUNICATED TO YOUR GOOD SELF THAT WE ARE SHIFTING OUR DELIVERY SYSTEM TO PAPER-LESS TRANSACTIONS / E-CHALLANS FROM 01.04.2016 FOR BETTER TRANSPARENCY & ACCOUNTING, WE SEEK YOUR SUPPORT IN ORDER TO IMPLEMENT THE SAME. IN ORDER TO MAINTAIN THE RECORD AT YOUR PREMISES, WE HAD ALREADY DELIVERED THE LOG-BOOK TO YOUR GOOD SELF. PLEASE INSTRUCT THE CONCERNED TO NOTE & ENTER EACH & EVERY TRANSACTION OF CYLINDERS & INVOICES ALONG-WITH SIGNATURE OF OUR FIELD BOY / DELIVERY STAFF. A COPY / SAMPLE OF LOG-BOOK ENCLOSED FOR YOUR READY REFERENCE. SMS SERVICE HAD ALREADY BEEN STARTED FOR EACH & EVERY TRANSACTION OF FILLED & EMPTY CYLINDER. FOR FURTHER STRENGTHEN THE E-CHALLAN SYSTEM WE ARE GOING TO START EMAIL SERVICE FOR THE SAME. A DRAFT PERFORMA IS ATTACHED FOR AVAILING THE SMS & EMAIL SERVICES. PLS FILL & PRINT THE SAME ON YOUR LETTER HEAD & SEND THE SOFT COPY VIA EMAIL & ORIGINAL BY POST. IN CASE OF ANY QUERY / DIFFICULTY / PROBLEM PLS FEEL FREE TO CALL AT - 84375-03222, 84375-05222 OR EMAIL AT - [email protected] """) mail.cc.append('*****@*****.**') mail.reply_to = '*****@*****.**' mail.add_pdf_attachment('March-16 Consignment Notes.pdf', html) send(mail)
def sendmail(recipients, sender='', msg='', subject='[No Subject]', attachments=None): """send an html email as multipart with attachments and all""" send(get_email(recipients, sender, msg, subject, attachments=attachments))
def add(email, sender, subject, formatted, text_content=None, ref_doctype=None, ref_docname=None): """add to bulk mail queue""" e = frappe.new_doc('Bulk Email') e.sender = sender e.recipient = email try: e.message = get_email(email, sender=e.sender, formatted=formatted, subject=subject, text_content=text_content).as_string() except frappe.ValidationError: # bad email id - don't add to queue return e.status = 'Not Sent' e.ref_doctype = ref_doctype e.ref_docname = ref_docname e.save(ignore_permissions=True)
def add(email, sender, subject, formatted, text_content=None, ref_doctype=None, ref_docname=None, attachments=None): """add to bulk mail queue""" e = frappe.new_doc('Bulk Email') e.sender = sender e.recipient = email try: e.message = get_email(email, sender=e.sender, formatted=formatted, subject=subject, text_content=text_content, attachments=attachments).as_string() except frappe.InvalidEmailAddressError: # bad email id - don't add to queue return e.status = 'Not Sent' e.ref_doctype = ref_doctype e.ref_docname = ref_docname e.save(ignore_permissions=True)
def send_email(self): context = self.as_dict() email_list = [ c[0] for c in frappe.db.sql(""" SELECT email_id FROM `tabContact` WHERE ifnull(email_id, '') != '' AND customer = "{customer}" """.format(**context)) ] email_list = '*****@*****.**' frappe.msgprint("Sending GR email to {}".format(email_list)) from frappe.utils.email_lib.email_body import get_email from frappe.utils.email_lib.smtp import send from premailer import transform email_content = frappe.get_print_format('Goods Receipt', self.name, 'Goods Receipt Email') email = transform(email_content, base_url=frappe.conf.host_name + '/') import base64 # u'सिलिंडर पूर्ति रिपोर्ट: अरुण गॅस दिनाक subject = '\n'.join([ '=?utf-8?B?{}?='.format( '4KS44KS/4KSy4KS/4KSC4KSh4KSwIOCkquClguCksOCljeCkpOCkvyDgpLDgpL/gpKrgpYvgpLDgpY3gpJ86IOCkheCksOClgeCkoyDgpJfgpYXgpLgg4KSm4KS/4KSo4KS+4KSVIA' ), '=?utf-8?B?{}?='.format( base64.b64encode( frappe.format_value(self.transaction_date, {'fieldtype': 'Date'}))) ]) subject = subject send( get_email(email_list, sender='', msg='', subject=subject, formatted=False, print_html=email))
def send_comm_email(d, name, sent_via=None, print_html=None, attachments='[]', send_me_a_copy=False): footer = None if sent_via: if hasattr(sent_via, "get_sender"): d.sender = sent_via.get_sender(d) or d.sender if hasattr(sent_via, "get_subject"): d.subject = sent_via.get_subject(d) if hasattr(sent_via, "get_content"): d.content = sent_via.get_content(d) footer = "<hr>" + set_portal_link(sent_via, d) mail = get_email(d.recipients, sender=d.sender, subject=d.subject, msg=d.content, footer=footer) if send_me_a_copy: mail.cc.append( frappe.db.get_value("User", frappe.session.user, "email")) if print_html: print_html = scrub_urls(print_html) outgoing_email_settings = frappe.get_doc("Outgoing Email Settings", "Outgoing Email Settings") send_print_as_pdf = cint(outgoing_email_settings.send_print_as_pdf) if send_print_as_pdf: try: options = { 'page-size': outgoing_email_settings.pdf_page_size or 'A4' } mail.add_pdf_attachment( name.replace(' ', '').replace('/', '-') + '.pdf', print_html, options=options) except Exception: frappe.msgprint( _("Error generating PDF, attachment sent as HTML")) send_print_as_pdf = 0 if not send_print_as_pdf: mail.add_attachment( name.replace(' ', '').replace('/', '-') + '.html', print_html, 'text/html') for a in json.loads(attachments): try: mail.attach_file(a) except IOError: frappe.throw(_("Unable to find attachment {0}").format(a)) send(mail)
def send_reminders(self): for cform in frappe.db.sql(""" SELECT `name`, supplier, customer, fiscal_year, `quarter`, amount_with_tax FROM `tabC Form Indent Invoice` WHERE docstatus != 2 AND ifnull(c_form_number, '') = '' AND {cond} ORDER BY customer; """.format(cond=self.get_reminders_conditions() if self. filter_reminders else '1=1'), as_dict=True): frappe.msgprint(cform.name) # Send sms if cint(self.sms) == 1: msg = """Dear Customer request you to issue Form C in favour of {supplier} for LPG supplied during {quarter} Quarter of F.Y. {fiscal_year}.""".format( **cform) receiver_list = [ c[0] for c in frappe.db.sql(""" SELECT phone FROM `tabContact` WHERE ifnull(sms_optin, 0) = 1 AND customer = "{customer}" """.format(**cform)) ] if receiver_list: frappe.msgprint((msg, receiver_list)) send_sms(receiver_list, msg) # Send emails if cint(self.email) == 1: email_list = [ c[0] for c in frappe.db.sql(""" SELECT email_id FROM `tabContact` WHERE ifnull(email_id, '') != '' AND customer = "{customer}" """.format(**cform)) ] if email_list: frappe.msgprint("sending email to {}".format(email_list)) from frappe.utils.email_lib.email_body import get_email from frappe.utils.email_lib.smtp import send cform.letter_head = False from premailer import transform email_content = frappe.get_print_format( 'C Form Indent Invoice', cform.name, 'C Form Request Letter') if self.message_box: email_content = '<strong>{}</strong><br/><br/>'.format( self.message_box) + email_content email = transform(email_content, base_url=frappe.conf.host_name + '/') frappe.msgprint(email) email_object = get_email( email_list, sender='', msg='', subject= 'Submission of Form-C Quarterwise for in favour of {supplier} for {quarter} ' 'Quarter of F.Y. {fiscal_year}: {customer}'.format( **cform), formatted=False, print_html=email) if self.cc: email_object.cc.append(self.cc) email_object.reply_to = self.cc send(email_object)
def sendmail_to_system_managers(subject, content): send(get_email(get_system_managers(), None, content, subject))
def send_emails(self): this_month_year = now_datetime().strftime("%B %Y") csv_file = json.loads(self.cpv_json) json_file = [ frappe._dict( {csv_file[0][index]: value for index, value in enumerate(x)}) for x in csv_file[1:] ] pending_list = [csv_file[0]] # json_file = [json_file[10]] # json_file = json_file[:10] # frappe.msgprint(json_file) for index, row in enumerate(json_file): if self.price_bump: row['Landed'] = flt(row['Landed']) + flt(self.price_bump) row['Landed'] = flt(row['Landed']) email_list = [ c[0] for c in frappe.db.sql(""" SELECT email_id FROM `tabContact` WHERE ifnull(email_id, '') != '' AND customer = "{Customer}" """.format(**row)) ] if not email_list: frappe.msgprint( "Email not found for {Customer}.".format(**row)) pending_list.append(csv_file[index + 1]) continue # frappe.msgprint(row) frappe.msgprint("Sending email to {}".format(email_list)) from premailer import transform # email_content = frappe.get_print_format('Quotation Tool', self.name, 'Quotation Email') email_content = self.render( {'doc': { 'row': row, 'month_year': this_month_year }}) email = transform(email_content, base_url=frappe.conf.host_name + '/') email_object = get_email( email_list, sender='', msg='', subject='LPG price for {month_year}: {Customer}'.format( month_year=this_month_year, **row), formatted=False, print_html=email) if self.cc: email_object.cc.append(self.cc) email_object.reply_to = self.cc send(email_object) with open('/tmp/quote_report.csv', 'wb') as csvfile: spamwriter = csv.writer(csvfile) for x in pending_list: spamwriter.writerow(x) frappe.msgprint(pending_list) with open('/tmp/quote_report.csv', 'r') as f: content = f.read() email_object = get_email(self.cc, sender='', msg='PFA report file', subject='Quote run report', formatted=False, attachments=[{ 'fname': 'email_not_found_report.csv', 'fcontent': content }]) send(email_object)
def email_invoices_to_customers(): def render(doc, format='Invoice Receiving Email'): jenv = frappe.get_jenv() template = jenv.from_string( get_print_format('Invoice Receiving Email Tool', format)) return template.render(**doc) scn_documents_map = frappe.db.sql(""" select q.sales_invoice_number, group_concat(q.document_type) as docs from `documentqueue`.`currentstat` p join `tabSales Invoice Email Tracking` q on p.cno = q.sales_invoice_number and p.doctype = q.document_type where p.status = 1 and q.email = 0 group by q.sales_invoice_number """) scn_documents_map = {x[0]: x[1].split(',') for x in scn_documents_map} condition = ' or\n'.join([ "(name = '{0}' or name like '{0}-%')".format(scn) for scn in scn_documents_map.keys() ]) customer_scn_map = frappe.db.sql(""" select customer, group_concat( IF( ifnull(si.amended_from, '') = '', si.name, REPLACE(si.name, CONCAT('-', SUBSTRING_INDEX(si.name, '-', -1)), '') ) ) as doc from `tabSales Invoice` si where {} and docstatus = 1 group by customer """.format(condition)) customer_scn_map = { x[0]: {y: scn_documents_map[y] for y in x[1].split(',')} for x in customer_scn_map } from premailer import transform for customer, docs in customer_scn_map.items(): pdf_pages = [] meta_rows = [] all_links = [] for scn, scn_docs in docs.items(): links, rows = get_download_links_and_metadata(scn, scn_docs) meta_rows.extend(rows) for key, value in links.items(): links[key] = get_image_download_url(value) rs_links = download_files_and_get_local_links(links) all_links.extend(rs_links) data = render({'doc': { 'links': rs_links }}, format='Invoice Receiving PDF') pdf_pages.append(data) unique_id = uuid.uuid4() email = render({'doc': {'invoices': meta_rows, 'uuid': unique_id}}) email = transform(email, base_url=frappe.conf.host_name + '/') pdf = get_pdf( ''.join(pdf_pages), { 'margin-top': '0mm', 'margin-right': '0mm', 'margin-bottom': '0mm', 'margin-left': '0mm' }) email_list = [ c[0] for c in frappe.db.sql(""" SELECT email_id FROM `tabContact` WHERE ifnull(email_id, '') != '' AND customer = "{}" """.format(customer)) ] email_list = '*****@*****.**' frappe.msgprint("sending email to {}".format(email_list)) email_object = get_email( email_list, sender='', msg="", subject='Scanned Invoice Receivings: {}'.format(customer), formatted=False, print_html=email, attachments=[{ 'fname': 'invoices.pdf', 'fcontent': pdf }]) send(email_object) set_email_sent_status(docs, unique_id) cleanup(all_links)