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

使用python脚本发送带有嵌入图像的html电子邮件

  •  0
  • Rio  · 技术社区  · 7 年前

    我是Python的新手。我想发送html的电子邮件与公司标志嵌入在左上角的电子邮件正文。

    使用下面的代码,电子邮件绝对可以工作,但不再附加嵌入的图像。不知道我哪里做错了。谁能帮帮我吗。

    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email.MIMEImage import MIMEImage
    
    msg = MIMEMultipart('alternative')
    msg['Subject'] = "My text dated %s" % (today)
                msg['From'] = sender
                msg['To'] = receiver
    
    html = """\
    <html>
    <head></head>
    <body>
      <img src="cid:image1" alt="Logo" style="width:250px;height:50px;"><br>
      <p><h4 style="font-size:15px;">Some Text.</h4></p>
    </body>
    </html>
    """
    
    # The image file is in the same directory as the script
    fp = open('logo.png', 'rb')
    msgImage = MIMEImage(fp.read())
    fp.close()
    
    msgImage.add_header('Content-ID', '<image1>')
    msg.attach(msgImage)
    
    part2 = MIMEText(html, 'html')
    msg.attach(part2)
    
    mailsrv = smtplib.SMTP('localhost')
    mailsrv.sendmail(sender, receiver, msg.as_string())
    mailsrv.quit()
    
    1 回复  |  直到 7 年前
        1
  •  12
  •   Rio    7 年前

    我发现了问题所在。这是最新的代码供您参考。

    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email.MIMEImage import MIMEImage
    
    msg = MIMEMultipart('related')
    msg['Subject'] = "My text dated %s" % (today)
    msg['From'] = sender
    msg['To'] = receiver
    
    html = """\
    <html>
      <head></head>
        <body>
          <img src="cid:image1" alt="Logo" style="width:250px;height:50px;"><br>
           <p><h4 style="font-size:15px;">Some Text.</h4></p>           
        </body>
    </html>
    """
    # Record the MIME types of text/html.
    part2 = MIMEText(html, 'html')
    
    # Attach parts into message container.
    msg.attach(part2)
    
    # This example assumes the image is in the current directory
    fp = open('logo.png', 'rb')
    msgImage = MIMEImage(fp.read())
    fp.close()
    
    # Define the image's ID as referenced above
    msgImage.add_header('Content-ID', '<image1>')
    msg.attach(msgImage)
    
    # Send the message via local SMTP server.
    mailsrv = smtplib.SMTP('localhost')
    mailsrv.sendmail(sender, receiver, msg.as_string())
    mailsrv.quit()