pythontextmime-message

Strange unwanted header when reading text file with MIMEText


I am writing a program to read from a text file. I have managed to get it to work, but am getting a strange header Which I do not want.

The Text file is called "SixMonthTextFile.txt and saved with notepad in windows.

The unwanted header I am getting is -

Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0

Content-Transfer-Encoding: 7bit

Body of text read from file here

I have tried stripping the first 3 lines and that is not working, just causes new problems. Any ideas on why it is happening and more importantly how to stop it?

My Code is

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

#Read an external text file for body of message
fp = open('SixMonthTextFile.txt', 'r')
SixMonthMessage = MIMEText(fp.read())
fp.close()

print(SixMonthMessage)

The result I get is

Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit

We would like to remind you that it has been six months
since your last service and its time for a precautionary service
since your equipment needs regular servicing to remain reliable.

Please reply to this email to book your FREE appointment.
[Finished in 0.4s]

I want only the original text from the text file as that is going into an email body.

Any ideas on why I am getting the strange unwanted extra header and how to get rid of it?


Solution

  • So I tried stovfl's suggestion and played with adding get_payload(),'3\n' to the MIMEText(fp.read() statement and it removed the unwanted header but also messed up the format of the text file and I still had an unuseable result.

    I got around the problem by coming at a different angle and replaced fp = open() etc with

    open('SixMonthTextFile.txt', 'r') as file: SixMonthTextFile = file.read()

    '''

    This gave me text that could then be used as formatted in the text file for insertion into the email.

    def sendsixmonthemail(address, EmailTo):
    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    
    #Read an external text file for body of message
    with open('SixMonthTextFile.txt', 'r') as file:
        SixMonthTextFile = file.read()
    
    
    
    host="smtp.gmail.com"
    email="myemailaddress@gmail.com"
    password = "123456786"
    
    from_addr='myemailaddress@gmail.com'
    to_addr=EmailTo
    reply_address = "myemailaddress@gmail.com"
    
    msg=MIMEMultipart()
    msg['From']=from_addr
    msg['To'] = to_addr
    msg['reply-to'] = "myemailaddress@gmail.com"
    msg['subject']='FREE 6 month Service Reminder for' + " " + address
    
    #Data read from Text File
    body= str(SixMonthTextFile)
    
    
    msg.attach(MIMEText(body,'plain'))
    
    mail=smtplib.SMTP_SSL(host,465)
    mail.login(email,password)
    text=msg.as_string()
    
    mail.sendmail(email,to_addr,text)
    mail.quit()