【问题标题】:HTML not rendering correctly when sending email via python email通过 python 电子邮件发送电子邮件时 HTML 无法正确呈现
【发布时间】:2015-10-22 10:39:48
【问题描述】:

我正在使用我公司的 smtp 服务器使用 python 的电子邮件模块发送电子邮件。当我这样做时,我的电子邮件 html 无法正确呈现。这是我得到的:

  sender = 'abc@abc.com'
  # Create message container - the correct MIME type is multipart/alternative.
  msg = MIMEMultipart('multipart')
  msg['Subject'] = "My Report"
  msg['From'] = sender
  msg['To'] = ", ".join(recipients)

  # Create the body of the message using html in msg_body
  h = unicode(msg_body).encode("utf-8", "ignore")
  # Record the MIME type
  part = MIMEText(h, 'html')

  # Attach parts into message container.
  msg.attach(part)

  pngfiles = ['image.png']  
  for file in pngfiles:
      # Open the files in binary mode. 
      fp = open(file, 'rb')
      img = MIMEImage(fp.read())
      fp.close()
      msg.attach(img)

  # Send the message via local SMTP server.
  s = smtplib.SMTP('send.abc.com')  
  s.sendmail(msg.get("From"), recipients, msg.as_string())
  s.quit()

我应该做些什么不同的事情?

【问题讨论】:

  • 可能与this有关?
  • 如您所见,我的子类型已经是 'html'。
  • 问题是我必须将字符集设置为“utf-8”。来自文档:如果 _text(第一个参数)是 unicode,则使用 _charset 的 output_charset 对其进行编码,否则按原样使用。 默认为 us-ascii。在我的情况下,第一个参数是 unicode。部分 = MIMEText(h, 'html', 'utf-8')

标签: python html python-2.7 email smtp


【解决方案1】:

只是想说明使用yagmail 发送带有附件的电子邮件是多么容易(完全公开:我是开发人员)。我的理念是只需要弄清楚如何处理 MIME 的东西,然后永远不要回头。

您可以使用以下 3 行来发送您的电子邮件:

import yagmail
yag = yagmail.SMTP(sender, your_password)

# assuming your undefined "msg_body" is just some message (string)
yag.send(recipients, 'My report', contents = [msg_body, '/local/path/to/image.png'])

你可以用内容做各种各样的事情:如果你有一个东西列表,它会很好地组合它。例如,一个文件名列表将使其全部附加。将它与一些消息混合,它就会有一个消息。

将附加任何作为有效文件的字符串,其他字符串只是文本。

它将很好地处理 HTML 代码、图像(内联)、文本和任何其他文件。是的,我为此感到非常自豪。

我鼓励您阅读github documentation 以了解其他不错的功能,例如,您不必使用密钥环在脚本中包含您的密码/用户名(额外安全)。设置一次,你会很开心....

哦,是的,要安装,您可以使用:

pip install yagmail  # python 2
pip3 install yagmail # python 3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-21
    • 2018-04-18
    • 1970-01-01
    • 2022-10-23
    • 2013-08-09
    • 2016-03-13
    • 2019-02-04
    • 1970-01-01
    相关资源
    最近更新 更多