如何在python中为从数据库中获取的值发送电子邮件。

我正试图使用smtplib发送一封从mysql数据库获取的值的电子邮件。这里,是代码。

db = pymysql.connect('localhost', 'root', 'Gandharv@4me', 'ashmita')
cursor = db.cursor()

sql_query = "SELECT * FROM employees1 WHERE fname = 'gandharv' "
cursor.execute(sql_query)
result = cursor.fetchall()
for row in result:
        firstname = row[0]
        lastname = row[1]
        role = row[2]
response = """ First Name : {}, Last Name: {}, Role : {} """.format(
        firstname, lastname, role)
mail = smtplib.SMTP('smtp.gmail.com', '587')
content="FirstName: "+firstname+" Lastname: " +lastname + "Role: ",role
mail.ehlo()
mail.starttls()
mail.login('abc@gmail.com', 'myPassword')
mail.sendmail('abc@gmail.com',
                  'bcd@gmail.com', content)
mail.close()
print(response)

如果我使用content=” knsdlkds”,它工作正常,但如果我使用content=response或content=”FirstName: “+firstname+” Lastname: ” +lastname + “Role: “,roleIt gives me TypeError: expected string or bytes-like object. 能否通过转换来解决这个问题?

解决方案:

你在content变量上有个错别字,你可以检查一下这个是否对你有效。

HOST="localhost"
USER="root"
USER_PW="Gandharv@4me"
HOST_DB="ashmita"

gandharv = "VALUE_HERE"
sender = 'from@fromdomain.com'
debuglevel = 0

try:
    db = pymysql.connect(HOST, USER, USER_PW, HOST_DB)
    cursor = db.cursor()
    sql_query = "SELECT * FROM employees1 WHERE fname = '{0}' ".format(gandharv)
    cursor.execute(sql_query)
    result = cursor.fetchone()

    # Send Email
    firstname = result[0]
    lastname = result[1]
    role = result[2]
    receivers = ['to@todomain.com']

    response = " First Name : {0}, Last Name: {1}, Role : {2} ".format(firstname, lastname, role)

    try:
        smtp = SMTP()
        smtp.set_debuglevel(debuglevel)
        smtp.connect('YOUR.MAIL.SERVER', 26)
        smtp.login('USERNAME@DOMAIN', 'PASSWORD')
        smtp.sendmail(sender, receivers, response)
        smtp.quit()
        print(response)

    except SMTPException:
        print "Error: unable to send email"

except Exception as e:
    print "Error: {0}".format(e)

本文来自投稿,不代表运维实战侠立场,如若转载,请注明出处:https://www.shizhanxia.com/886.html

(0)
上一篇 2022年6月29日 下午4:01
下一篇 2022年6月29日 下午4:01

相关推荐

发表评论

登录后才能评论