sendgrid / sendgrid-python

The Official Twilio SendGrid Python API Library
https://sendgrid.com
MIT License
1.54k stars 714 forks source link

How to Send attachment with each personalization instance through mail helper #1047

Closed mahadikrushikesh closed 2 years ago

mahadikrushikesh commented 2 years ago

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:

mahadikrushikesh commented 2 years ago

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!

childish-sambino commented 2 years ago

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: https://github.com/sendgrid/sendgrid-python/blob/d7d292cf2241c18d052b8e3705dcc134cc0912d5/sendgrid/helpers/mail/mail.py#L771-L789

rakatyal commented 2 years ago

Closing due to lack of activity.