1

i have this python send html mail, and within this code, i can send email but the body of the message is blank.

below is my code

#!/usr/bin/python
import smtplib
import MySQLdb
import time
import os
from datetime import datetime

def timestamp():
        now = datetime.now()
        return now.strftime("%Y-%m-%d %H:%M:%S")
def write_log(log):
        date_today = datetime.now().strftime("%Y-%m-%d") 

    if os.path.isfile('logs/log.'+date_today+'.txt') == True:
            wlog = open('logs/log.'+date_today+'.txt','a')
            wlog.writelines('\n'+timestamp()+' - '+log)
    else:
            wlog = open('logs/log.'+date_today+'.txt','w')
            wlog.writelines(timestamp()+' - '+log)

def login():
    now = time.strftime("%c")
    username = "[email protected]"
    pwd = 'password'
    smtpserver = smtplib.SMTP("[email protected]",587)
    smtpserver.login(username, pwd)

db_ip = 'localhost'
db_user = 'USER'
db_pass = 'DBPASSWORD'
db_dbase = 'DBASE'

while 1:
    db = MySQLdb.connect(db_ip,db_user,db_pass,db_dbase)
    cur = db.cursor()
    cur.execute("SELECT * FROM form_number WHERE tag = 2")
    data = cur.fetchall()

    for row in data:
        recipient = row[6]
        sender = 'NO REPLY EMAIL<[email protected]>'
        assigned_person = row[5]
        header = 'Date: ' + now + '\n' + 'To:' + recipient + '\n' + 'From: ' +sender + '\n' + 'Subject:Liquidation record of ' + assigned_person +  '\n'
        msg = """Content-type: text/html
                    Subject: liquidation for """+ row[5] +"""
                            <font color='#000000'>
                                """ + row[5] +  """ has sent you a request.
                                to view click on the link below.
                             </font>"""
        message = header + msg
        print message
        smtpserver.sendmail(sender, recipient, message)
        cur.execute("UPDATE form_number SET tag = 3, time_sent = '" + now + "' WHERE form_number = '" + str(row[0]) + "'")

    db.commit()
    db.close()
    time.sleep(15)

def run():
    try:
        login()
    except:
        pass

run()
#login()

i can successfully send email to my desired recipient but when the recipient receive the email, it has only have a blank mesage. any comments will do. thanks in advance!

3
  • 1
    PLEASE DON'T YELL AT US Commented Sep 2, 2014 at 2:49
  • @PatrickCollins i'm not yelling. i'm sorry. Commented Sep 2, 2014 at 2:53
  • 1
    IT LOOKS LIKE YOU STILL ARE, MAYBE YOU SHOULD EDIT YOUR QUESTION Commented Sep 2, 2014 at 2:55

3 Answers 3

1

The white space in your message is incorrect. I believe your message looks like this:

From: NO REPLY SMSGT<[email protected]>
Subject:Liquidation record of assigned_person
Content-type: text/html
                Subject: liquidation for John
                        <font color='#000000'>
                            John has sent you a request.
                            to view click on the link below.
                         </font>

But it should look like this:

From: NO REPLY SMSGT<[email protected]>
Subject:Liquidation record of assigned_person
Content-type: text/html
Subject: liquidation for John

<font color='#000000'>
John has sent you a request.
to view click on the link below.
 </font>

Try replacing your assignment to msg like so:

msg = \
"""Content-type: text/html
Subject: liquidation for """+ row[5] +"""

<font color='#000000'>
""" + row[5] +  """ has sent you a request.
to view click on the link below.
</font>"""
Sign up to request clarification or add additional context in comments.

1 Comment

i tried to clear the whitespace just like your sample above but instead my msg was transformed into a textfile.
1

First thing I would do is use python's email module instead of building the email by hand. It will take care of correctly building the envelope for HTML vs. plain text. The documentation there even shows how to send an HTML email with smtplib (scroll down to the part that says "how to create an HTML message").

Also, be careful of SQL injection on this line!

cur.execute("UPDATE form_number SET tag = 3, time_sent = '" + now + "' WHERE form_number = '" + str(row[0]) + "'")

In this case you might (?) be safe because you have control over now and row[0], but it's always better and more secure to use a prepared statement and pass in the values as parameters instead of concatenating them into the query.

Here's how to use prepared statements with MySQLdb:

http://en.wikipedia.org/wiki/Prepared_statement#Python_DB-API

(ignore that the example is sqlite3, it works the same because they both follow python's DBAPI standard)

2 Comments

when i try to execute my python. my database updates and i have received an email, my only problem is that i received only a blank message. as in blank message.
I think the email is blank because the message you're creating (message = header + msg) isn't a valid email. If you use the email module I linked to then you don't need to worry about building it correctly by hand. If you really want to build the email manually then you should read RFC822, etc. to make sure you've got the format correct.
-1

Unless I'm not mistaking, """ are the equivalent of code comments in Python.

So essentially you're commenting out the message.

It has been a long time since I coded in py. Don't hurt me...

2 Comments

This is not quite right. Triple quotes (""", ''') are used to define strings, same as single quotes (', and "). Some people use it to comment out code, but in this case he's correctly assigning a string to msg.
if you read out the code @lost-theory, i have print the message and when i run the code, i successfully print out the whole message, my real problem is when i received the email i have problem on my code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.