sendmail with HTML message

此生再无相见时 提交于 2019-12-13 04:33:32

问题


I am programming with Python. I already have a function that sends an email with a message and an attachment....My only problem is that I want the message to be HTML, but mine does not respect that.....

Here is the function that I'm using

def enviarCorreo(fromaddr, toaddr, text, file):
   msg = MIMEMultipart('mixed')
   msg['From'] = fromaddr
   msg['To'] = toaddr
   msg['Subject'] = 'asunto'
   msg.attach(MIMEText(text))
   #adjunto
   adjunto = MIMEBase('application', "octet-stream")
   adjunto.set_payload(open(file, "rb").read())
   encode_base64(adjunto)
   anexo = os.path.basename(file)
   adjunto.add_header('Content-Disposition', 'attachment; filename= "%s"' % anexo)
   msg.attach(adjunto)
   #enviar
   server = smtplib.SMTP('localhost')
   server.set_debuglevel(1)
   server.sendmail(fromaddr, toaddr, msg.as_string())
   server.quit()
   return

I hope you can tell me what to change or what to add so the message I send could be HTML....

I am using the "MIXED" Multipart because the HTML message will contain some images that would not be attached but would be part of the message.....


回答1:


replace

msg.attach(MIMEText(text))

by

msg.attach(MIMEText(text, 'html'))

(default is 'plain')




回答2:


There is an example on the official documentation page that sends HTML email - http://docs.python.org/library/email-examples.html



来源:https://stackoverflow.com/questions/8300860/sendmail-with-html-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!