Skip to content Skip to sidebar Skip to footer

Sending Email Attachment (.txt File) Using Python 2.7 (smtplib)

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 fr

Solution 1:

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.

Solution 2:

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.

Post a Comment for "Sending Email Attachment (.txt File) Using Python 2.7 (smtplib)"