python - 在 Python 电子邮件中附加文件

标签 python mime

所以我尝试了多种方法在 python 中将文件(特别是 CSV 文件)附加到电子邮件并发送。我的文本电子邮件工作正常,而且我确实收到了一份 CSV 文件,只是一个空文件。我目前正在发送我的附件,如下所示:

ctype, encoding = mimetypes.guess_type("results.csv")
if ctype is None or encoding is not None:
    ctype = "application/octet-stream"

maintype, subtype = ctype.split("/", 1)

# organizing receivers
receiver = receivers.split(',')

# creating subject
subject = 'BLAH BLAH'
timestamp = time.strftime("%m/%d/%Y:%H:%M:%S")
subject += str(timestamp)

# form email
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = " ".join(receivers)
msg['Subject'] = subject
msg['Message-Id'] = make_msgid()
msg['Date'] = formatdate(localtime=True)
msg.attach(MIMEText(msgstr, 'plain'))

if maintype == "text":
    fp = open("results.csv")
    attachment = MIMEText(fp.read(), _subtype=subtype)
    fp.close()

else:
    fp = open('results.csv', "rb")
    attachment = MIMEBase(maintype, subtype)
    attachment.set_payload(fp.read())
    fp.close()
    encoders.encode_base64(attachment)

attachment.add_header("Content-Disposition", "attachment", filename='results.csv')
msg.attach(attachment)

try:
    smtpobj = smtplib.SMTP('smtp.gmail.com:587')
    smtpobj.ehlo()
    smtpobj.starttls()
    smtpobj.ehlo()
    smtpobj.login(username, password)

    smtpobj.sendmail(sender, receiver, msg.as_string())
    smtpobj.quit()

except smtplib.SMTPException:
    print 'Error: unable to send mail'

这与此处的答案类似:python can't send attachment files through email 我还尝试过更简单的方法,类似于: 奥 git _a How to send email attachments with Python

和其他人,但没有成功。如何发送完整的附件?

最佳答案

因此,经过多次调试后,我意识到在尝试再次读取该文件以了解电子邮件的组成之前,我没有正确关闭该文件。我有类似于下面的代码:

with open('results.csv', "rb") as csvfile:
    #compose the csv file
    #blah
    #blah
    #blah
    #then I called my email function but the file hadn't yet been closed and I was trying to reopen.

为了解决这个问题,我只是简单地在 with 语句之外调用我的电子邮件函数来关闭文件。

with open('results.csv', "rb") as csvfile:
        #compose the csv file
        #blah
        #blah
        #blah

send_the_email()

我希望这可以防止其他人像我一样在如此简单的事情上浪费大量时间。

关于python - 在 Python 电子邮件中附加文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30314538/

相关文章:

python - Numpy Where 有两个以上的条件

c# - 纯文本 mime 电子邮件发送至 MailMessage

c# - 如何从 .NET Core 中的 ContentType(MIME 类型)获取文件扩展名?

python - 忽略python元组的一部分

Python使用递归反转整数

python - 从 Python Flask 中的链接获取信息

xml - 将 XML 文件作为附件通过电子邮件发送时对内容传输编码感到困惑

python - 如何测试 django 消息中是否存在某个级别

html - 当涉及 MIME 类型时,文件扩展名是否重要?这会影响服务器上的其他东西吗?

android - 获取图片路径