我正在创建一张图片,希望可以在电子邮件中嵌入。但我无法弄清如何将图像创建为二进制并传递到MIMEImage中。以下是我的代码,当我尝试读取图像对象时出现错误 - 错误是“AttributeError:'NoneType'对象没有'read'属性”。
image=Image.new("RGBA",(300,400),(255,255,255))
image_base=ImageDraw.Draw(image)
emailed_password_pic=image_base.text((150,200),emailed_password,(0,0,0))
imgObj=emailed_password_pic.read()
msg=MIMEMultipart()
html="""<p>Please finish registration <br/><img src="cid:image.jpg"></p>"""
img_file='image.jpg'
msgText = MIMEText(html,'html')
msgImg=MIMEImage(imgObj)
msgImg.add_header('Content-ID',img_file)
msg.attach(msgImg)
msg.attach(msgText)
如果您看一下第4行 - 我试图读取图像,以便可以将其传递到MIMEImage中。显然,图像需要以二进制形式读取。但是,我不知道如何将其转换为二进制格式,以便 .read() 可以处理它。
跟进: 根据jsbueno的建议,我编辑了代码 - 非常感谢!!!
emailed_password=os.urandom(16)
image=Image.new("RGBA",(300,400),(255,255,255))
image_base=ImageDraw.Draw(image)
emailed_password_pic=image_base.text((150,200),emailed_password,(0,0,0))
stream_bytes=BytesIO()
image.save(stream_bytes,format='png')
stream_bytes.seek(0)
#in_memory_file=stream_bytes.getvalue()
#imgObj=in_memory_file.read()
imgObj=stream_bytes.read()
msg=MIMEMultipart()
sender='xxx@abc.com'
receiver='jjjj@gmail.com'
subject_header='Please use code provided in this e-mail to confirm your subscription.'
msg["To"]=receiver
msg["From"]=sender
msg["Subject"]=subject_header
html="""<p>Please finish registration by loging into your account and typing in code from this e-mail.<br/><img src="cid:image.png"></p>"""
img_file='image.png'
msgText=MIMEText(html,'html')
msgImg=MIMEImage(imgObj) #Is mistake here?
msgImg.add_header('Content-ID',img_file)
msg.attach(msgImg)
msg.attach(msgText)
smtpObj=smtplib.SMTP('smtp.mandrillapp.com', 587)
smtpObj.login(userName,userPassword)
smtpObj.sendmail(sender,receiver,msg.as_string())
目前我没有收到错误信息,但电子邮件中没有图片。我对html/电子邮件部分中图片的添加和关联方式感到困惑。需要任何帮助!
更新: 这段代码实际上是可以工作的——我只是在我的PC上打错了几个字母。