问题
So I'm trying to send a .txt file as an attachment and I can't find the right code to work. Here is my code:
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()
And when I run the module I get this error:
Traceback (most recent call last):
File "C:\Python278\emailonlytester.pyw", line 19, in <module>
msg.attach(attachment)
AttributeError: 'str' object has no attribute 'attach'
Any help would be much appreciated.
回答1:
The error is clearly stating the reason. msg
is a string in your case. You may want to do the following instead:
msg = MIMEMultipart()
Docs are here.
回答2:
You can try this to send an attached file with 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)
This is the part for the creation of the Email, not the sending.
来源:https://stackoverflow.com/questions/27621041/sending-email-attachment-txt-file-using-python-2-7-smtplib