【问题标题】:Sending Email attachment (.txt file) using Python 2.7 (smtplib) [duplicate]使用 Python 2.7(smtplib)发送电子邮件附件(.txt 文件)[重复]
【发布时间】:2015-02-21 15:15:17
【问题描述】:

因此,我尝试将 .txt 文件作为附件发送,但找不到合适的代码。这是我的代码:

import pythoncom
import win32gui
import win32console
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


fromaddr = 'zover1@gmail.com'
toaddrs = 'zover2@gmail.com'
msg = "contrl text file"
username = 'zover1@gmail.com'
password= 'xxxxxxxxxxxx'
server = smtplib.SMTP('smtp.gmail.com:587')
f = file("d:/control.txt")
attachment = MIMEText(f.read())
attachment.add_header('Content-Disposition', 'attachment', filename="d:/control.txt")
msg.attach(attachment)
server.ehlo()
server.starttls()
server.login(username, password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()

当我运行该模块时,我得到了这个错误:

Traceback (most recent call last):
  File "C:\Python278\emailonlytester.pyw", line 19, in <module>
msg.attach(attachment)
AttributeError: 'str' object has no attribute 'attach'

任何帮助将不胜感激。

【问题讨论】:

  • 你知道你暴露了你的账户密码???
  • 编辑了问题以隐藏 OP 的密码。 @Zover Lul,如果密码是真实的,我建议您更改密码。 :)
  • 不是正品,哈哈

标签: python email smtplib


【解决方案1】:

你可以试试这个用python发送附件:

msg = MIMEMultipart()
msg['From'] = 'your adress'
msg['To'] = 'someone'
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = 'a random subject'
msg.attach(MIMEText("some text"))
file = 'd:/control.txt'
attachment = MIMEBase('application', 'octet-stream')
attachment.set_payload(open(file,'rb').read())
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
msg.attach(attachment)

这是创建电子邮件的部分,而不是发送部分。

【讨论】:

  • 我粘贴了上面的代码,但我收到了这样的错误: Traceback (last recent call last): File "C:\Python278\emailonlytester.pyw", line 26, in server.ehlo() NameError: name 'server' is not defined 看不出它是怎么定义的,我已经导入了 smtplib。当我不发送附件时它起作用了
  • 我提供的代码不包含对server的任何引用,你能告诉我你是如何在你的代码中实现这段代码的吗?
  • file = 'd:/control.txt' attachment = MIMEBase('application', 'octet-stream') attachment.set_payload(open(file,'rb').read()) 附件.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file)) msg​​.attach(attachment) username = 'zover.lul@gmail.com' password= 'battlefield34 ' msg = "控制文本文件" server.ehlo() server.starttls() server.login(username, password) server.sendmail(fromaddr, toaddrs, msg) server.quit()
  • 好吧,从你在这里给我的来看,没有服务器定义,如果这是你使用的所有代码,难怪它不起作用。您应该首先尝试重用您提供给我们的代码的一些旧部分。
【解决方案2】:

错误清楚地说明了原因。 msg 在您的情况下是一个字符串。您可能需要执行以下操作:

msg = MIMEMultipart()

Docs are here.

【讨论】:

    猜你喜欢
    • 2015-03-06
    • 2011-10-19
    • 2014-05-27
    • 2021-08-19
    • 2020-09-19
    • 2021-04-26
    • 1970-01-01
    • 2014-01-31
    • 2023-02-11
    相关资源
    最近更新 更多