代码之家  ›  专栏  ›  技术社区  ›  alias51

如何显示EmailMultiAlternatives邮件对象的html内容

  •  0
  • alias51  · 技术社区  · 6 年前

    发送电子邮件时:

    from django.core.mail import EmailMultiAlternatives
    
    subject, from_email, to = 'hello', 'from@example.com', 'to@example.com'
    text_content = 'This is an important message.'
    html_content = '<p>This is an <strong>important</strong> message.</p>'
    msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
    msg.attach_alternative(html_content, "text/html")
    msg.send()
    

    如何显示 "text/html" 调用对象时的替代方案?例如。

    msg.html_content
    
    0 回复  |  直到 6 年前
        1
  •  0
  •   Harben    6 年前

    您可以在您的 msg.alternatives 这是一个元组列表。

    请参阅下面的用法

    from django.core.mail import EmailMultiAlternatives
    
    subject, from_email, to = 'hello', 'from@example.com', 'to@example.com'
    text_content = 'This is an important message.'
    html_content = '<p>This is an <strong>important</strong> message.</p>'
    
    msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
    msg.attach_alternative(html_content, "text/html")
    
    # This prints [('<p>This is an <strong>important</strong> message.</p>', 'text/html')]
    print(msg.alternatives)
    
    # Prints ('<p>This is an <strong>important</strong> message.</p>', 'text/html')
    print(msg.alternatives[0])
    
    # Prints '<p>This is an <strong>important</strong> message.</p>'
    print(msg.alternatives[0][0])
    
    msg.send()
    
    推荐文章