I want to send a simple text file to my email. But, when Im trying to send it, the text file becomes the content of the email, and when I open the sent email, I see the content of the text file as the content of the email. I want the file to be attached to the email as a file, and not just taking the content of the file and send it as the content of the messege sent.
Here is the code:
import time
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
msg = MIMEMultipart()
_from = '**************'
_to = '**************'
msg['Subject'] = 'This will be my subject.'
msg['From'] = _from
msg['To'] = _to
msg.preamble = 'This is just mememememe...'
with open('temp.txt', 'rt') as temp_file:
msg.attach(MIMEText(temp_file.read()))
print 'Create smtp object...'
mail = smtplib.SMTP_SSL('smtp.gmail.com', 465)
print 'Object created.'
print 'Recognized in front of the server'
mail.ehlo()
print 'Recognized...'
print 'Log in to email...'
mail.login('*******', '****')
print 'Loged in.'
while True:
time.sleep(2)
print 'Sending mail...'
try:
mail.sendmail(_from, _to, msg.as_string())
print 'Mail sent...'
break
except:
print 'Error...'
pass
mail.close()