Python: 带图片的 Mime 消息

Python: Mime message with Pictures

我正在尝试使用我的邮件和 python 发送 png 图像。 这是我找到的脚本:

# Import smtplib for the actual sending function
import smtplib

# Here are the email package modules we'll need
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

COMMASPACE = ', '

# Create the container (outer) email message.
msg = MIMEMultipart()
msg['Subject'] = 'Our family reunion'
# me == the sender's email address
# family = the list of all recipients' email addresses
msg['From'] = me
msg['To'] = COMMASPACE.join(family)
msg.preamble = 'Our family reunion'

# Assume we know that the image files are all in PNG format
for file in pngfiles:
    # Open the files in binary mode.  Let the MIMEImage class automatically
    # guess the specific image type.
    with open(file, 'rb') as fp:
        img = MIMEImage(fp.read())
    msg.attach(img)

# Send the email via our own SMTP server.
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()

来源:https://docs.python.org/3/library/email-examples.html

我的问题是,当我想精确确定 pngfiles 路径时,我会写类似这样的内容:

pngfiles="/Desktop/Test2"

只返回这样的错误信息

Traceback (most recent call last):
  File "C:\Python27\work\Picture.py", line 46, in <module>
    fp = open(file, 'rb')
IOError: [Errno 13] Permission denied: '/'

这真是一个愚蠢的问题,但不知道如何正确地编写它...请帮忙? :)

谢谢!

你的文件路径:

"/Desktop/Test2"

和你的 python 路径:

"C:\Python27\work\Picture.py"

存在冲突(Unix 中的第一个,第二个是 Windows)。

首先是使用真实的 windows 路径。

pngfiles_folder = "C:\Python27\work\"

但是您还需要一种方法来确定要附加哪些文件(在本例中为 png)。为此,您可以使用 glob 包创建要附加的文件列表:

import glob
for file in glob.glob("C:\Python27\work\*.png"):
    ....