Gmail recently changed its security settings and disabled the "less secure apps" option. My attempt to send emails with the Python module smtplib got blocked. So I chose a SMTP mailer, sendinblue. After setting up sendinblue, I'm able to send emails again, but I fail to include images that are stored locally. The email only contains an icon of the missing image. A solution to this question has been proposed in php, but I am not able to apply it in Python.
from __future__ import print_function
import sib_api_v3_sdk
from sib_api_v3_sdk.rest import ApiException
from pprint import pprint
import base64
with open('MyPlot.png', 'rb') as fin:
data = fin.read()
base64_data = base64.b64encode(data)
configuration = sib_api_v3_sdk.Configuration()
configuration.api_key['api-key'] = 'my_api_key'
api_instance = sib_api_v3_sdk.TransactionalEmailsApi(sib_api_v3_sdk.ApiClient(configuration))
subject = "Weekly Report"
html_content = "<html> Here is your weekly report <img src=base64_data alt='Report'/> </html>"
sender = {"name":"Sender","email":"sender@gmail.com"}
to = [{"email":"receiver@gmail.com","name":"FirstName LastName"},
{"email":"receiver@gmail.com","name":"FirstName LastName"}]
reply_to = {"email":"replytome@gmail.ca","name":"FName LName"}
send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(to=to, reply_to=reply_to, html_content=html_content, sender=sender, subject=subject)
try:
api_response = api_instance.send_transac_email(send_smtp_email)
pprint(api_response)
except ApiException as e:
print("Exception when calling SMTPApi->send_transac_email: %s\n" % e)
This may work for you. I added that you need to .decode the encoded string of the png file and the attachment element in the .SendSmtpEmail function.
import sib_api_v3_sdk
from sib_api_v3_sdk.rest import ApiException
import base64
from pprint import pprint
filename = "MyPlot.png"
with open(filename, "rb") as file:
encoded_string = base64.b64encode(file.read())
base64_message = encoded_string.decode('utf-8')
configuration = sib_api_v3_sdk.Configuration()
configuration.api_key['api-key'] = 'my_api_key'
api_instance = sib_api_v3_sdk.TransactionalEmailsApi(sib_api_v3_sdk.ApiClient(configuration))
subject = "Weekly Report"
html_content = "<html> Here is your weekly report </html>"
sender = {"name":"Sender","email":"sender@gmail.com"}
to = [{"email":"receiver@gmail.com","name":"FirstName LastName"},
{"email":"receiver@gmail.com","name":"FirstName LastName"}]
attachment = [{"content":base64_message,"name":filename}]
send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(to=to, attachment = attachment, html_content=html_content, sender=sender, subject=subject)
try:
api_response = api_instance.send_transac_email(send_smtp_email)
pprint(api_response)
except ApiException as e:
print("Exception when calling SMTPApi->send_transac_email: %s\n" % e)