Как я могу прикрепить данные модели django в виде файла Excel и отправить их по почте с помощью SMTP

У меня есть некоторые данные в моделях django и я хочу сделать файл excel из этих данных и прикрепить его в SMTP как файл и отправить его целевому пользователю. Я также использую django-import-export для экспорта файлов excel, но в этом случае я хочу прикрепить файл к электронной почте.

Модель

class FinalBill(models.Model):
shipDate = models.DateField(blank = True, null = True, auto_now=False, auto_now_add=False)
customerReference = models.CharField(max_length = 200, blank = True, null = True)
customerConfirmation = models.CharField(max_length = 200, blank = True, null = True)
deliveryConfirmation = models.CharField(max_length = 200, blank = True, null = True)
address = models.CharField(max_length = 200, blank = True, null = True)
service = models.CharField(max_length = 200, blank = True, null = True)
weight = models.FloatField(blank = True, null = True)
pricingZone = models.CharField(max_length = 200, blank = True, null = True)
uspsCompRate = models.FloatField(blank = True, null = True)
charges = models.FloatField(blank = True, null = True)
surcharges = models.FloatField(blank = True, null = True)
totalSavings = models.FloatField(blank = True, null = True)
totalCharges = models.FloatField(blank = True, null = True)
customerID = models.CharField(max_length = 200)
is_exported = models.BooleanField(default=False)
exported_date = models.DateField(blank = True, null = True, auto_now=False, auto_now_add=False)
def __str__(self):
    return str(self.deliveryConfirmation)

Utills.py

def send_bill_on_mail(mailerID):
   customerBill = FinalBill.objects.filter(customerID=mailerID, is_exported=False)
   dataset = Bills().export(customerBill)
   mail_subject = "Subject Name"
   message = "Test Email Message"
   to_email = "xyz@gmail.com"
   file = "file"        
   mail = EmailMessage(mail_subject, message,  settings.EMAIL_HOST_USER, [to_email])
   mail.attach(file.name, file.read(), file.content_type)
   mail.send()

django-tables2 может помочь вам в этом, вы создаете свою таблицу как Class, которая будет питаться от ваших данных, а затем вы можете экспортировать таблицу в XLS документ, а затем вы можете отправить его по электронной почте пользователю.

Ссылки:

def export_data_to_excel(mailerID) -> None: 
  excelfile = BytesIO()
  workbook = Workbook()
  workbook.remove(workbook.active)
  worksheet = workbook.create_sheet(title='Title Name', index=1)

  bill_queryset =  Bills.objects.filter(cus_id=mailerID, is_exported=False)
  columns = ['Date', 'Reference', 'Confirmation', 'Confirmation', 'Address', 'Service', 'Weight', 'Pricing Zone', 'UspsRate', 'Charges', 'Sur Charges', 'Total Savings', 'Total Charges', 'Customer ID']
  row_num = 1

# Assign the titles for each cell of the header
  for col_num, column_title in enumerate(columns, 1):
    cell = worksheet.cell(row=row_num, column=col_num)
    cell.value = column_title
    cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=False)
    cell.font = Font(bold=True)
# Iterate through all coins
 for _, bill in enumerate(bill_queryset, 1):
    row_num += 1

    # Define the data for each cell in the row
    row = [
        bill.shipDate,
        bill.customerReference,
        bill.customerConfirmation,
        bill.deliveryConfirmation,
        bill.address,
        bill.service,
        bill.weight,
        bill.pricingZone,
        bill.uspsCompRate,
        bill.charges,
        bill.surcharges,
        bill.totalSavings,
        bill.totalCharges,
        bill.customerID,
    ]

    # Assign the data for each cell of the row
    for col_num, cell_value in enumerate(row, 1):
        cell = worksheet.cell(row=row_num, column=col_num)
        cell.value = cell_value
        cell.protection = Protection(locked=True)
workbook.save(excelfile)
mail_subject = f'Invoice {mailerID} on {date.today()}'
message = ""
to_email = "xyz@gmail.com"
message = EmailMessage(mail_subject, message, settings.EMAIL_HOST_USER, [to_email])
message.attach(f'Invoice {mailerID}.xlsx', excelfile.getvalue(), 'application/vnd.ms-excel')
message.send()
Вернуться на верх