使用Python 2.7(smtplib)发送电子邮件附件(.txt文件)

时间:2014-12-23 13:07:34

标签: python email smtplib

所以我试图将.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'

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

您可以尝试使用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)

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

答案 1 :(得分:0)

该错误清楚地说明了原因。 msg是您的案例中的字符串。您可能希望执行以下操作:

msg = MIMEMultipart()

Docs are here