我想将简单的文本文件发送到我的电子邮箱。 但是,当我尝试发送它时,文本文件成为电子邮件的内容,当我打开发送的电子邮件时,我将文本文件的内容视为电子邮件的内容。 我希望将文件作为文件附加到电子邮件中,而不仅仅是获取文件的内容并将其作为发送的信息的内容发送。
以下是代码:
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()