sendgrid/sendgrid-python

How to Send attachment with each personalization instance through mail helper

mahadikrushikesh opened this issue · 3 comments

I am using template id to send dynamic data and managed through personalization mail helper

Issue Summary

Is there way to send multiple emails with multiple attachments through personalization.

Code Snippet

      personalization1 = Personalization()
      personalization1.dynamic_template_data = dynamic_data
      # We are preparing list or recipients & passing singly to it's function accordingly to, cc, bcc
      [personalization1.add_email(To(i.strip(), str(i.split("@")[0]))) for i in to_emails]
      if cc_emails:
          [personalization1.add_email(Cc(i.strip())) for i in cc_emails]
      if bcc_emails:
          [personalization1.add_email(Bcc(i.strip())) for i in bcc_emails]

      date = datetime.utcnow() + timedelta(seconds=10, milliseconds=counter)
      personalization1.send_at = calendar.timegm(date.utctimetuple())
      message.add_personalization(personalization1)

      # Attachment 
      file_path = r'\Downloads\Sales.pdf'
      with open(file_path, 'rb') as f:
          data = f.read()
          f.close()
      encoded = base64.b64encode(data).decode()
      attachment = Attachment()
      attachment.file_content = FileContent(encoded)
      attachment.file_type = FileType('application/pdf')
      attachment.file_name = FileName('Sales.pdf')
      attachment.disposition = Disposition('attachment')
      attachment.content_id = ContentId('pdffile')
      message.attachment = attachment

the above written code is inside for loop and it is attaching for each email, due to loop making n number of attachments based on loops iteration but i want it to be with each personalization separately. does it possible in sendgrid in any another way.

Technical details:

  • sendgrid-python version:
  • sendgrid==6.5.0
  • python version:
    3.7

I have gone through all present documentation for sendgrid python API's but i didn't find any helpful, any help would be appreciate. thanks in advance!

You can pass in a list of attachments (e.g., message.attachment = [attachment1, attachment2, ...]) or invoke add_attachment for each attachment (e.g., [message.add_attachment(attachment) for attachment in attachments]).

Underlying source:

def attachment(self, attachment):
"""Add attachment(s) to this email
:param attachment: Add attachment(s) to this email
:type attachment: Attachment, list(Attachment)
"""
if isinstance(attachment, list):
for a in attachment:
self.add_attachment(a)
else:
self.add_attachment(attachment)
def add_attachment(self, attachment):
"""Add an attachment to this email
:param attachment: Add an attachment to this email
:type attachment: Attachment
"""
self._attachments = self._ensure_append(attachment, self._attachments)

Closing due to lack of activity.