0

I am writing a mail function in Python using csvwriter and StringIo, my motive is to send the mails with attachment only if the attachment is containing some data.

But, the function is also sending mails in case of empty file. Please help me where i am making mistake.

def cbazaar_quantity_sync(self,products_data_quantity_sync,threep_numbers):
    channel = Channel.objects.get(name='CBazaar')
    channel_configurations = channel.channelconfiguration_set.all()
    listed_threep_numbers = self.filter_products_listed_on_channel(channel,threep_numbers)
    products_to_sync = self.filter_products_data(products_data_quantity_sync,listed_threep_numbers)
    # pdb.set_trace()
    data = products_to_sync
    current_time = datetime.now()
    task_start_time = "%s-%s-%s_%s:%s:%s"%(current_time.day, current_time.month, current_time.year, current_time.hour, current_time.minute, current_time.second)
    csvresult = StringIO.StringIO()
    csvresultwriter = csv.writer(csvresult)
    csvresultwriter.writerow(["Pri.Vendor Name","Product Code","Product Size","Design No","Stock Qty","Shipping Lead Time","Replicable (Yes / No)","Is stock Qty exclusively allocated to CBazaar ( Yes / No)"])
    if len(products_to_sync) != 0:
        for product in data:
            # pdb.set_trace()
            Store_Name = str('voylla retail pvt ltd')
            sku = str(product[2])
            size = str(product[3])
            threep_number =  str(product[1])
            qty = int(product[7])
            leadtime = int(product[8])
            mod = str(product[11])
            none = str('None')
            if mod == none:
                leadtime = 2
            replicable = str('Yes')
            product_obj = Product.objects.get(threep_number=threep_number)
            channel_sku = self.threep_sku_mapping_method(channel,product_obj)
            # pdb.set_trace()
            if channel_sku != 0:
                sku=str(channel_sku)
                if qty == 0:
                    continue
                else:
                    csvresultwriter.writerow(['%s'%Store_Name,'%s'%sku,'%s'%size,'%s'%threep_number,'%d'%qty,'%d'%leadtime,'%s'%replicable])
    else:
        self.stdout.write('No products to sync with CBazaar.')
    # #Build message for Production
    # email = EmailMessage(subject='CBazaar Quantity Sync Details File', body='PFA CSV File attached with this mail.', from_email='help@voylla.com',
    #         to=['tamilmaran@cbazaar.com'], cc=['3pcatalogging@voylla.in'],
    #         headers = {'Reply-To': '3pcatalogging@voylla.in'})
    # # Build message for Local
    email = EmailMessage(subject='CBazaar Quantity Sync Details File', body='PFA CSV File attached with this mail.', from_email='help@voylla.com',
            to=['abhishek.g@qa.voylla.com'],
            headers = {'Reply-To': '3pcatalogging@voylla.in'})
    # Attach csv file
    email.attach("cbazaar_quantity_sync_"+task_start_time+".csv", csvresult.getvalue(), 'text/csv')
    # Send message with built-in send() method
    email.send()

    #=================================================================#
    ##For sending Mail for "Zero Quantity Product" to Threep-Team
    #=================================================================#
    csvresult = StringIO.StringIO()
    csvresultwriter = csv.writer(csvresult)
    csvresultwriter.writerow(["Pri.Vendor Name","Product Code","Product Size","Design No","Stock Qty","Shipping Lead Time","Replicable (Yes / No)","Is stock Qty exclusively allocated to CBazaar ( Yes / No)"])
    if len(products_to_sync) != 0:
        for product in data:
            # pdb.set_trace()
            Store_Name = str('voylla retail pvt ltd')
            sku = str(product[2])
            size = str(product[3])
            threep_number =  str(product[1])
            qty = int(product[7])
            leadtime = int(product[8])
            mod = str(product[11])
            none = str('None')
            if mod == none:
                leadtime = 2
            replicable = str('Yes')
            product_obj = Product.objects.get(threep_number=threep_number)
            channel_sku = self.threep_sku_mapping_method(channel,product_obj)
            if qty == 0:
                        if channel_sku != 0:
                            sku=str(channel_sku)
                            csvresultwriter.writerow(['%s'%Store_Name,'%s'%sku,'%s'%size,'%s'%threep_number,'%d'%qty,'%d'%leadtime,'%s'%replicable])
                        else:
                            self.stdout.write('No Zero Quantity products to sync with CBazaar.')                        
    # Build message for Threep-Team
    email = EmailMessage(subject='CBazaar_"Zero_Quantity_product"_File', body='PFA CSV File attached with this mail.', from_email='help@voylla.com',
    to=['abhishek.g@qa.voylla.com'])
    # # Attach csv file
    email.attach("cbazaar_zero_quantity_"+task_start_time+".csv", csvresult.getvalue(), 'text/csv')
    # # Send message with built-in send() method
    email.send()
    return

The output i am getting also contains empty file with headers which i am passing.

  • When you say empty file, you mean - `csvresult.getvalue()` - would be empty string? Can't you just check that? – Anand S Kumar Aug 11 '15 at 06:34
  • Didn't see how empty file can be filtered out -- you put a header row right after opening `csvresultwriter`, outside the `product in data` loop, which means the output MUST have the header. How do you want your "empty" file to be treated? – charlee Aug 11 '15 at 06:34
  • @AnandSKumar I've checked csvresult.getvalue() yes it is showing csvresultwriter.writerow() data. Not the products_to_sync data. tell me what can i do to stop sending the mails if the file is empty – Abhishek Gupta Aug 11 '15 at 06:52
  • @charlee I've also tried that your opinion but then also it is sending file with corrupted mail attachment – Abhishek Gupta Aug 11 '15 at 06:54
  • you should stop doing `email.attach()` if csv does not contain any data. – charlee Aug 11 '15 at 06:56
  • @charlee But it stops attaching the file if the file contains some data except headers. How can i manage – Abhishek Gupta Aug 11 '15 at 06:58

1 Answers1

0

I solved the problem to making the condition false : the code snippet i change is just :

if len(products_to_sync) != 0:
        for product in data:
            # pdb.set_trace()
            Store_Name = str('voylla retail pvt ltd')
            sku = str(product[2])
            size = str(product[3])
            threep_number =  str(product[1])
            qty = int(product[7])
            leadtime = int(product[8])
            mod = str(product[11])
            none = str('None')
            if mod == none:
                leadtime = 2
            replicable = str('Yes')
            product_obj = Product.objects.get(threep_number=threep_number)
            channel_sku = self.threep_sku_mapping_method(channel,product_obj)
            # pdb.set_trace()
            if channel_sku != 0:
                sku=str(channel_sku)
                if qty == 0:
                    continue
                else:
                    csvresultwriter.writerow(['%s'%Store_Name,'%s'%sku,'%s'%size,'%s'%threep_number,'%d'%qty,'%d'%leadtime,'%s'%replicable])
        email = EmailMessage(subject='CBazaar Quantity Sync Details File', body='PFA CSV File attached with this mail.', from_email='help@voylla.com',
            to=['abhishek.g@qa.voylla.com'],
            headers = {'Reply-To': '3pcatalogging@voylla.in'})
        # Attach csv file
        email.attach("cbazaar_quantity_sync_"+task_start_time+".csv", csvresult.getvalue(), 'text/csv')
        # Send message with built-in send() method
        email.send()
else:
     self.stdout.write('No products to sync with CBazaar.')