Weird display of 'From' field in smtp email sent in python

Viewed 63

I am getting weird display of From field in smtp email.The display is like;

from: test@gmail.com To: test@gmail.com, Subject: Message test@gmail.com to:

to field is blank but the another 'to' recipient, ie test1@gmail.com received the email successfully. Below is my code.

import smtplib

def SendEmailScenario1():
    gmail_user = "test@gmail.com"
    gmail_password = '******'

    sent_from = gmail_user
    to = ["test1@gmail.com"]
    subject = 'Message'
    body = "Hi There! Done1"

    email_text = """\
    From: %s 
    To: %s 
    Subject: %s

    %s
    """ % (sent_from, ", ".join(to), subject, body)
    try:
        server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
        server.ehlo()
        server.login(gmail_user, gmail_password)
        server.sendmail(sent_from, to, email_text)
        server.close()

        print ('Email sent!')
    except:
        print ('Something went wrong...')
def SendEmailScenario2():
    gmail_user = "test@gmail.com"
    gmail_password = '******'

    sent_from = gmail_user
    to = ["test1@gmail.com"]
    subject = 'Message'
    body = "Hi There! Done 2"

    email_text = """\
    From: %s 
    To: %s 
    Subject: %s

    %s
    """ % (sent_from, ", ".join(to), subject, body)
    try:
        server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
        server.ehlo()
        server.login(gmail_user, gmail_password)
        server.sendmail(sent_from, to, email_text)
        server.close()

        print ('Email sent!')
    except:
        print ('Something went wrong...')
SendEmailScenario1()
SendEmailScenario2()

How to bring it to normal display without using MIMEText, MIMEMultipart

1 Answers

RFC822 specifies that a header should terminate with '\r\n':

field = field-name ":" [ field-body ] CRLF

Furthermore, the headers should be separated from the body by an empty '\r\n':

[The body] is separated from the headers by a null line (i.e., a line with nothing preceding the CRLF)

So the message should be constructed like this:

headers = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n"
email_text = headers + body

See also the example in the smtplib docs.

Related