python [Python]发送包含嵌入式图像和应用程序附件的电子邮件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python [Python]发送包含嵌入式图像和应用程序附件的电子邮件相关的知识,希望对你有一定的参考价值。

#! /usr/bin/python

import smtplib

from optparse import OptionParser
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication

parser = OptionParser()
parser.add_option("-f", "--from", dest="sender", help="sender email address", default="no-reply@doma.in")
parser.add_option("-t", "--to", dest="recipient", help="recipient email address")
parser.add_option("-s", "--subject", dest="subject", help="email subject", default="Default Subject")
parser.add_option("-i", "--image", dest="image", help="image attachment", default=False)
parser.add_option("-p", "--pdf", dest="pdf", help="pdf attachment", default=False)

(options, args) = parser.parse_args()


# Create message container.
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = options.subject
msgRoot['From'] = options.sender
msgRoot['To'] = options.recipient

# Create the body of the message.
html = """\
    <p>This is an inline image<br/>
        <img src="cid:image1">
    </p>
"""

# Record the MIME types.
msgHtml = MIMEText(html, 'html')

if options.image is not False:
    img = open(options.image, 'rb').read()
    msgImg = MIMEImage(img, 'png')
    msgImg.add_header('Content-ID', '<image1>')
    msgImg.add_header('Content-Disposition', 'inline', filename=options.image)

if options.pdf is not False:
    pdf = open(options.pdf, 'rb').read()
    msgPdf = MIMEApplication(pdf, 'pdf') # pdf for exemple
    msgPdf.add_header('Content-ID', '<pdf1>') # if no cid, client like MAil.app (only one?) don't show the attachment
    msgPdf.add_header('Content-Disposition', 'attachment', filename=options.pdf)
    msgPdf.add_header('Content-Disposition', 'inline', filename=options.pdf)

msgRoot.attach(msgHtml)
msgRoot.attach(msgImg)
msgRoot.attach(msgPdf)

# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
#s.sendmail(options.sender, options.recipient, msgRoot.as_string())
s.sendmail(options.sender, options.recipient, msgRoot.as_string())
s.quit()

以上是关于python [Python]发送包含嵌入式图像和应用程序附件的电子邮件的主要内容,如果未能解决你的问题,请参考以下文章

发送包含嵌入图像的多部分 html 电子邮件

python 使用嵌入的附件和图像以HTML格式发送电子邮件。

Python - 使用嵌入图像向 GMAIL 发送邮件

如何使用 Outlook 2010(无 smtp)和 python 发送带有嵌入图像(不是附件)的 HTML 格式电子邮件

无法在使用 python smtplib/email 发送的 Outlook 2013 电子邮件中显示嵌入图像

Python,MIME,在电子邮件中嵌入图像