Gmail最近更改了它的安全设置和禁用“较不安全的应用程序”选项。我用Python模块smtplib发送电子邮件的尝试被阻止了。所以我选择了一个SMTP邮件,sendinblue。在设置sendinblue之后,我能够再次发送电子邮件,但是我没有包括存储在本地的图像。电子邮件只包含丢失图像的图标。这个问题的解决办法是在php中提出的,但我无法在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)发布于 2022-10-04 08:37:26
这可能对你有用。我补充说,您需要.decode png文件的编码字符串和.SendSmtpEmail函数中的附件元素。
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)https://stackoverflow.com/questions/72463642
复制相似问题