python sending email with sendgrid with attachment

Solutions on MaxInterview for python sending email with sendgrid with attachment by the best coders in the world

showing results for - "python sending email with sendgrid with attachment"
Emelie
31 Jul 2020
1from sendgrid import SendGridAPIClient
2from sendgrid.helpers.mail import (Mail, Attachment, FileContent, FileName, FileType, Disposition)
3
4message = Mail(
5        from_email='email@mail.com',
6        to_emails='test@test.com',
7        subject='Sending email with Sengrid',
8        html_content='<p>My first mail using Sendgrid</p>'
9        )
10    
11        try:
12            sg = SendGridAPIClient('<SENDGRID_API_KEY>')
13            response = sg.send(message)
14            print(response.status_code)
15            print(response.body)
16            print(response.headers)
17        except Exception as e:
18            #print(e.message)
19            print(e)
Silvia
27 Feb 2017
1import base64
2
3from sendgrid import SendGridAPIClient
4from sendgrid.helpers.mail import (Mail, Attachment, FileContent, FileName, FileType, Disposition)
5
6message = Mail(
7        from_email='email@mail.com',
8        to_emails='test@test.com',
9        subject='Sending email with attachment with Sengrid',
10        html_content='<p>My first attachment sent with help of Sendgrid</p>'
11        )
12    
13        with open('attachment.pdf', 'rb') as f:
14            data = f.read()
15            f.close()
16        encoded_file = base64.b64encode(data).decode()
17
18        attachedFile = Attachment(
19            FileContent(encoded_file),
20            FileName('attachment.pdf'),
21            FileType('application/pdf'),
22            Disposition('attachment')
23        )
24        message.attachment = attachedFile
25    
26        try:
27            sg = SendGridAPIClient('<SENDGRID_API_KEY>')
28            response = sg.send(message)
29            print(response.status_code)
30            print(response.body)
31            print(response.headers)
32        except Exception as e:
33            #print(e.message)
34            print(e)