Search code examples
azure-functionstwiliosendgridemail-attachments

Send email with multiple attachments using python with Twilio send grid


I'm using Twilio sendgrid for emails. During my Azure function execution, I'm saving multiple files of different file types in temp directory. How can I pick all those files from temp directory and send multiple attachments in a single email using Python. Throwing error "can't set attribute" at message.attachments = list(lst_attchments)

message = Mail(
from_email='from_mail',
to_emails='to_mail',
subject='sample mail from fun2 part-no data - 123490-000',
html_content='<stron>mr. venkatesh, please find the updated data and let me know if any issues. \n regards,System</strong>')
#mail = Mail(from_email, to_email, subject, content)
try:
    sg = SendGridAPIClient(os.environ.get('sendgridkey'))
    #message.add_attachment(temp_path+'//'+'test_file2.pdf')
    files = ["test_file.pdf", "test_file2.pdf", "test_file1.pdf"]

    lst_attchments=[]
    for file_name in files:  # add files to the message
        file_path = os.path.join(temp_path, file_name)
        with open(file_path, 'rb') as file_data:
            data = file_data.read()
            file_data.close()
        encoded_file = base64.b64encode(data).decode()

        attachedFile = Attachment(
            FileContent(encoded_file),
            FileName(file_name),
            FileType('application/pdf'),
            Disposition('attachment')
        )
        lst_attchments.append(attachedFile)
    message.attachments = list(lst_attchments)
    
    mail_json = message.get()        
    response = sg.client.mail.send.post(request_body=mail_json)
    logging.info('mail sent succefully')
    
except Exception as e:
    logging.error(e)

Solution

  • As suggested by @Olasimbo Arigbabu and as per the twilio document here is the sample code for sending email through python using twilio and by attaching files.

    import os
    import base64
    from sendgrid import SendGridAPIClient
    from sendgrid.helpers.mail import (Mail, Attachment, FileContent, FileName, FileType, Disposition)
    message = Mail(from_email='from_email@example.com',to_emails='to@example.com',
    subject='Sending with Twilio SendGrid is Fun',html_content='<strong>and easy to do anywhere, even with Python</strong>'
    )
    with  open('attachment.pdf', 'rb') as f:
    data = f.read()
    f.close()
    encoded_file = base64.b64encode(data).decode()
    attachedFile = Attachment(
    FileContent(encoded_file),
    FileName('attachment.pdf'),
    FileType('application/pdf'),
    Disposition('attachment')
    )
    message.attachment = attachedFile
    sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
    response = sg.send(message)
    print(response.status_code, response.body, response.headers)